假设我有下表:
first second
A 1
A 1
A 2
B 1
B 2
C 1
C 1
如果我运行以下查询:
select first, second, count(second) from tbl group by first, second
它将生成一个包含以下信息的表:
first second count(second)
A 1 2
A 2 1
B 1 1
B 2 1
C 1 2
如何编写查询,以便我从第二列的选项中获取信息作为列,这些列的值是这样的计数:
first 1 2
A 2 1
B 1 1
C 2 0
答案 0 :(得分:1)
您可以使用CASE
:
SELECT "first",
SUM(CASE WHEN "second" = 1 THEN 1 ELSE 0 END) AS "1",
SUM(CASE WHEN "second" = 2 THEN 1 ELSE 0 END) AS "2"
FROM tbl
GROUP BY "first"