如何计算每列中每个不同值的独立值?

时间:2011-07-06 17:43:34

标签: sql aggregate-functions

给表mytable有两列letter和num

letter|num
------+------
a     |1
a     |1
b     |1
b     |2

我试过

SELECT letter, count(letter), num, count(num) from mytable group BY letter, num;

但它返回

letter|count|num   |count
------+-----+------+-----
  b   |  1  |  1   |  1
  a   |  2  |  1   |  2
  b   |  1  |  2   |  1

而我想要

letter|count|num   |count
------+-----+------+-----
  a   |  2  |  1   |  3
  b   |  2  |  2   |  1

这可以吗,我可以在一个查询中完成吗?

1 个答案:

答案 0 :(得分:2)

您可以将其更改为2个单独的聚合。

SELECT 'letter' as type, letter AS item, count(letter)
    from mytable group BY letter
UNION ALL  --CAST to be same type as letter
SELECT 'num', CAST(num AS varchar(100)), count(num)
    from mytable group BY num;