请问这个类似交叉表的问题该怎么统计?
OA_LBStore
ID GoodsName
1 钢笔
2 笔记本
OA_LBUser
ID UserName
1 张山
2 李四
OA_LBUserGoods
ID UserID GoodsID OverPlusCount
1 1 1 3
2 1 2 5
我要想得到下面的结果该怎么查啊
UserName 钢笔 笔记本
张山 3 5
李四 0 0
------解决方案----------------------如果OA_LBUserGoods的GoodsID是固定的
Select
A.UserName,
SUM(Case When C.GoodsName = N '钢笔 ' Then B.OverPlusCount Else 0 End) As 钢笔,
SUM(Case When C.GoodsName = N '笔记本 ' Then B.OverPlusCount Else 0 End) As 笔记本
From
OA_LBUser A
Left Join
OA_LBUserGoods B On A.ID = B.UserID
Left Join
OA_LBStore C On C.ID = B.GoodsID
Group By
A.UserName
Order By
Min(A.ID)
--如果OA_LBUserGoods的GoodsID不是固定的
Declare @S Nvarchar(4000)
Select @S = ' Select A.UserName '
Select @S = @S + N ', SUM(Case When C.GoodsName = N ' ' ' + GoodsName + ' ' ' Then B.OverPlusCount Else 0 End) As [ ' + GoodsName + '] '
From OA_LBStore Order By ID
Select @S = @S + ' From OA_LBUser A Left Join OA_LBUserGoods B On A.ID = B.UserID Left Join OA_LBStore C On C.ID = B.GoodsID Group By A.UserName Order By Min(A.ID) '
EXEC(@S)