开发者

How can I count how much each different values occur in each column independently?

Given table mytable with two columns letter and num

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

I tried doing

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

but it returns

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

whereas I wanted

letter|count|num   |count
------+-----+------+-----
  a   |  2  |  1   开发者_运维百科|  3
  b   |  2  |  2   |  1

Is this possible to do, and can I do it in one query?


You could change it to 2 separate aggregates like this.

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜