Answers:
您可以尝试以下方法:
select
count(distinct tag) as tag_count,
count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
from
your_table_name;
首先count(distinct...)
很容易。第二个看上去有些复杂,实际上与第一个相同,只是您使用了case...when
子句。在case...when
子句中,您仅过滤正值。零或负值将被评估为null
并且不会计入计数。
这里要注意的一件事是,可以通过一次读取表格来完成此操作。当您似乎必须两次或多次读取同一张表时,实际上在大多数情况下可以通过一次读取来完成。结果,它将以更少的I / O更快地完成任务。
请尝试以下语句:
select distinct A.[Tag],
count(A.[Tag]) as TAG_COUNT,
(SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
from [TagTbl] AS A GROUP BY A.[Tag]
第一个字段是标签,第二个字段是整数,第三个字段是正数。
这也可能起作用:
SELECT
COUNT(DISTINCT T.tag) as DistinctTag,
COUNT(DISTINCT T2.tag) as DistinctPositiveTag
FROM Table T
LEFT JOIN Table T2 ON T.tag = T2.tag AND T.entryID = T2.entryID AND T2.entryID > 0
您需要在左联接中而不是在where子句中使用entryID条件,以确保在第一个DISTINCT中正确计数只有entryID为0的所有项目。
当[条目ID]> 0时,代码会计算标签和条目ID的唯一/不同组合
select count(distinct(concat(tag,entryId)))
from customers
where id>0
在输出中将显示唯一值的计数,希望对您有所帮助