我有
Groupvar | Subvar | Val |
---|---|---|
G1 | A | x|
G1 | A | x |
G1 | B | x |
G1 | B | y|
G1 | C | z |
G1 | C | z |
G2 | A | x |
G2 | A | x |
G2 | B | y |
G2 | B | z |
G2 | B | w |
G2 | C | z |
您需要COUNT()
聚合函数中的CASE
表达式来应用条件聚合:
SELECT Groupvar,
COUNT(DISTINCT Val) [All],
COUNT(DISTINCT CASE WHEN Subvar = 'A' THEN Val END) A,
COUNT(DISTINCT CASE WHEN Subvar = 'B' THEN Val END) B,
COUNT(DISTINCT CASE WHEN Subvar = 'C' THEN Val END) C
FROM tablename
GROUP BY Groupvar;
请参阅演示