我在SQL数据库中有以下表格:
Lender State Revenue
A AK 13
A NJ 20
A CA 25
B AK 30
B NJ 25
C NJ 20
C CA 31
D CA 21
我希望创建一个包含不同状态组合和收入总和的表格:
State Revenue Lender Count
AK, NJ, CA 58 1
AK, NJ 55 1
NJ, CA 51 1
CA 21 1
这可以通过SQL实现吗?如果没有,最好的方法是什么?
答案 0 :(得分:1)
试试这个。
SELECT LEFT(cs.State, Len(cs.State) - 1) AS State,
Sum(Revenue) AS Revenue,
1 as Leader_Count
FROM Yourtable a
CROSS APPLY (SELECT State + ','
FROM Yourtable B
WHERE a.Lender = b.Lender
FOR XML PATH('')) cs (State)
GROUP BY Lender,
LEFT(cs.State, Len(cs.State) - 1)