首页 文章

SQL:计算表中的不同行值

提问于
浏览
0

我在SQL中有一个类似的表:

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

我想运行一个查询来计算表中的不同行(删除 id 列) . 结果应如下所示(或此表的转置):

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

这个查询应该是什么样的?

Note :事先不知道每列中的值 .

1 回答

  • 2

    您可以使用条件聚合执行此操作:

    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;
    

    但是,常规方法是将计数放在行中,而不是列中:

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

    这些行更加通用,因为您不必列出您可能想要匹配的每个组合 .

相关问题