简体   繁体   English

SQL:计算表中不同的行值

[英]SQL: Count distinct row values in table

I have a similar table to this in SQL: 我在SQL中有与此类似的表:

id |tag | entryID
---+----+--------
1  |foo | 0
2  |foo | 0
3  |bar | 3
5  |bar | 3
6  |foo | 3
7  |foo | 3

I want to run a query to count distinct rows in the table (with the id column dropped). 我想运行一个查询以计算表中的不同行(已删除id列)。 The result should look like this (or a transpose of this table): 结果应如下所示(或此表的转置):

(tag=foo, entryID=0) | (tag=foo, entryID=3) | (tag=bar, entryID=3)
---------------------+----------------------+---------------------
2                    | 2                    | 2

What should this query look like? 该查询应该是什么样?

Note : The values in each of the columns are not known beforehand. 注意 :每个列中的值都是事先未知的。

You can do this using conditional aggregation: 您可以使用条件聚合来做到这一点:

select sum(tag = 'foo' and entryId = 0) as "tag=foo, entryID=0",
       sum(tag = 'foo' and entryId = 3) as "tag=foo, entryID=3",
       sum(tag = 'bar' and entryId = 3) as "tag=bar, entryID=0"
from t;

However, the normal method is to put the counts in rows, not columns: 但是,通常的方法是将计数放在行中,而不是列中:

select tag, entryId, count(*)
from t
group by tag, entryId;

The rows are much more versatile, because you don't have to list out every combination you might want to match. 这些行的用途更加广泛,因为您不必列出可能要匹配的每个组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM