我很难计算c1的a1和a2并单独计算a1和a2。
C1 | C2
_______
a | a1
a | a2
b | a1
b | a2
c | a1
d | a2
结果。
a1 | a1 & a2 | a2 ---> from C2
________________
1 | 2 | 1 ---> from C1
我想计算c1的值和c2的2值的位置。
答案 0 :(得分:0)
请尝试以下查询。
select [a1], [a1&a2],[a2]
from
(
SELECT DISTINCT t2.c2 AS C2,COUNT(*) as col FROM Table1 t1
inner join Table1 t2 ON t1.c1=t2.c1 GROUP BY t2.c2,t2.c1 HAVING COUNT(*)<2
UNION ALL
select distinct
LTRIM(REPLACE(REPLACE(stuff((SELECT distinct '& ' + cast(c2 as varchar(10))
FROM Table1 t2
where t2.c1 = t1.c1
FOR XML PATH('')),1,1,''),'& ','&'),'amp;','')) AS C2,Count(*) as col
from Table1 t1 group by c1 HAVING COUNT(*)>1
) d
pivot
(
max(col)
for c2 in ([a1],[a1&a2] ,[a2])
) piv;