这是我的示例表
**BranchId GroupCode Cash Credit**
1000 AA 10 8644
1000 AA 12 1244
1000 BB 20 7535
1000 CC 30 5633
1001 AA 50 5763
1001 AA 34 2343
1001 BB 60 1000
1001 BB 62 2346
1002 BB 34 1600
1002 CC 68 1700
我希望这种形式的示例输出如下所示
**BranchId | AA_Cash | AA_Credit | BB_Cash | BB_Credit | CC_Cash | CC_Credit**
1000 ?
1001
1002
? =我需要每个分支机构的现金和信用额度
select * from
(select bid, GroupCode, Cash FROM dueList) as T
PIVOT (sum(Cash) for GroupCode in([AA_Cash],[BB_Cash],[CC_Cash])) PT
此SQL仅给出现金列,我需要在输出中添加功劳列。
我尝试使用以下链接
In Sql Server how to Pivot for multiple columns
但是在我的数据库中只有16个分支。一旦我在上面的链接中尝试了示例,它就会在分支中显示重复的行,并在数字区域显示很多空值。
答案 0 :(得分:1)
您可以先取消对PIVOT的多列数据
为了获得更好的视觉效果,请在SELECT
子查询中运行src
示例
Select *
From (
Select A.BranchID
From YourTable A
Cross Apply ( values (GroupCode+'_Cash' ,Cash)
,(GroupCode+'_Credit',Credit)
) B(Item,Value)
) src
Pivot (sum(Value) for Item in ([AA_Cash],[AA_Credit]
,[BB_Cash],[BB_Credit]
,[CC_Cash],[CC_Credit]
) )pvt
编辑
在旁注中,仅使用所需的列来“馈送”数据透视表很重要。在您发布的示例中,您包括了GroupCode
。这将生成其他记录。
答案 1 :(得分:0)
只需使用条件聚合!
select BranchId,
sum(case when groupcode = 'AA' then cash end) as aa_cash,
sum(case when groupcode = 'AA' then credit end) as aa_credit,
sum(case when groupcode = 'BB' then cash end) as bb_cash,
sum(case when groupcode = 'BB' then credit end) as bb_credit,
sum(case when groupcode = 'CC' then cash end) as cc_cash,
sum(case when groupcode = 'CC' then credit end) as cc_credit
from t
group by BranchId;