我正在尝试在以下情况下编写查询
结果
示例:
ColumnA ColumnB
A B
B C
结果:
ColumnA countB countC
A 1 0
B 0 1
答案 0 :(得分:1)
它应该起作用:
Select
columnA,
count(ColumnB) as ColumnB,
count(ColumnC) as ColumnC
From Table
Group By
columnA
答案 1 :(得分:1)
没有足够的样本数据来确认这一点,但是根据您的问题的标题,您似乎正在寻找条件汇总:
SELECT
columnA,
COUNT(CASE WHEN columnB = 'B' THEN 1 END) countB,
COUNT(CASE WHEN columnB = 'C' THEN 1 END) countC
FROM mytable
GROUP BY columnA
答案 2 :(得分:1)
从您的示例数据中,不需要汇总:
SELECT columnA,
(CASE WHEN columnB = 'B' THEN 1 ELSE 0 END) as countB,
(CASE WHEN columnB = 'C' THEN 1 ELSE 0 END) as countC
FROM t;
答案 3 :(得分:0)
假设您的实际情况比那大,我认为使用枢轴会更好
DECLARE @table TABLE(ColumnA CHAR(1), ColumnB CHAR(1))
INSERT @table VALUES ('A', 'B')
INSERT @table VALUES ('B', 'C')
SELECT ColumnA, A AS CountA, B AS CountB, C AS CountC, D AS CountD....
FROM
(
SELECT ColumnA, ColumnB
FROM @table
) AS Source
PIVOT
(
Count(ColumnB)
FOR ColumnB IN ([A], [B], [C], [D].....)
) AS Pvt