Table1
列出了带产品的人员名单(A,B,C)
我想使用SQL查询显示有多少人拥有每种产品组合的记录。
请注意:
1.产品未知,因此无法硬编码产品名称,表中可能有'n'个产品名称。
表1 :
ID Person Product
-------------------
1 Jannet A
2 Jannet B
3 Ross A
4 Jane C
5 Jane B
6 Jane A
7 Jannet A
需要输出:
Product A B C
----------------------
A 0 2 1
B 2 0 1
C 1 1 0
答案 0 :(得分:0)
试试这个:
SELECT Product ,
SUM(CASE WHEN productx = 'A' THEN 1 ELSE 0
END) A ,
SUM(CASE WHEN productx = 'B' THEN 1 ELSE 0
END) B ,
SUM(CASE WHEN productx = 'C' THEN 1 ELSE 0
END) C
FROM ( SELECT DISTINCT tb.Product product ,
tb2.Product productx ,
tb3.Person
FROM ( SELECT DISTINCT
Product
FROM Remsys.TABLE_1
) tb
CROSS JOIN ( SELECT DISTINCT
Product
FROM Remsys.TABLE_1
) tb2
INNER JOIN Remsys.TABLE_1 tb3
ON tb.Product = tb3.Product
INNER JOIN Remsys.TABLE_1 tb4
ON tb2.Product = tb4.Product
WHERE tb.product <> tb2.product
AND tb3.person = tb4.person
) otb
GROUP BY Product