根据条件进行不同计数

问题描述 投票:0回答:7

我想在特定条件下计算列中不同项目的数量,例如,如果表是这样的:

tag | entryID
----+---------
foo | 0
foo | 0
bar | 3

如果我想将同一个表中不同标签的数量计算为“标签计数”,并将条目 id > 0 的不同标签的数量计算为“正标签计数”,我该怎么办?

我现在从两个不同的表中进行计数,其中在第二个表中我只选择了那些 EntryID 大于零的行。我认为应该有一个更紧凑的方法来解决这个问题。

sql
7个回答
380
投票

你可以试试这个:

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 更快地完成任务。


2
投票

这可能有效:

SELECT Count(tag) AS 'Tag Count'
FROM Table
GROUP BY tag

SELECT Count(tag) AS 'Negative Tag Count'
FROM Table
WHERE entryID > 0
GROUP BY tag

2
投票

尝试以下语句:

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]

第一个字段将是标签,第二个字段将是整个计数,第三个字段将是正计数。


2
投票

当 [Entry Id]>0 时,代码会计算标签和条目 ID 的唯一/不同组合

select count(distinct(concat(tag,entryId)))
from customers
where id>0

在输出中它将显示唯一值的计数 希望这有帮助


2
投票

我同意@ntalbs解决方案, 如果你想在另一列数据的条件有效时统计某一列的数据,你可以这样做

select
  count(distinct tag) as tag_count,
  count(distinct tag, case when entryId > 0 then tag end) as positive_tag_count
from
  your_table_name;

在第3行,我在

distinct
旁边添加了列名称,因此当entryId大于0时,它会计算不同的标签


0
投票

这也可能有效:

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条件,以确保任何只有entryID为0的项目在第一个DISTINCT中得到正确计数。


0
投票

如果您使用的 SQL 方言支持对计数进行 FILTER,例如 Postgresql,您可以以稍微更易读的形式编写 ntalbs 的答案

select
  count(distinct tag) as tag_count,
  count(distinct tag) FILTER (WHERE entryID > 0) as positive_tag_count
from
  your_table_name;

这可以推广到所有聚合函数。

© www.soinside.com 2019 - 2024. All rights reserved.