当前位置: 代码迷 >> Sql Server >> sql行行转列,该如何解决
  详细解决方案

sql行行转列,该如何解决

热度:73   发布时间:2016-04-24 21:46:06.0
sql行行转列
我有两张表A,B
A表 有 Num,Type,MainNum,OperaName
B表有  Num,CostName,ShouldMoney,RealMoney,CostType(标示应收应付(1,0)),FlagClosIng

我想查出这样的格式
Num,Type,MainNum,OperaName,CostName,ShouldMoney(应收金额),RealMoney(实收金额),ShouldMoney(应付金额),RealMoney(实付金额),FlagClosIng

让应收和应付显示在一行,求高手给个sql语句



------解决方案--------------------
目测楼上的可能会报错,稍微改动一下


;WITH aaa AS
(
select Num,CostName,
sum(case CostType when 1 then RealMoney else 0 end) as RealMoney(实付金额),
sum(case CostType when 1 then ShouldMoney else 0 end) as ShouldMoney(应付金额),
sum(case CostType when 0 then RealMoney else 0 end) as RealMoney(实收金额),
sum(case CostType when 0 then ShouldMoney else 0 end) as ShouldMoney(应收金额)
from B 
GROUP BY Num,CostName
)
SELECT 
    a.NUM,TYPE,MainNum,OperaName,CostName,RealMoney(实付金额),
ShouldMoney(应付金额),RealMoney(实收金额),ShouldMoney(应收金额)
FROM A INNER JOIN aaa AS B ON A.Num=B.Num

  相关解决方案