SQL行转列(暂时记录,后期完善改文章)

/****** Script for SelectTopNRows command from SSMS  ******/

declare @Year Int,@Month int
set @Year=2015
set @Month=1



select *  into #t from (

SELECT  ReceiptAccount as Account,'InCome' [Type],SUM(Amount) Amount 
  FROM [dbo].[ReceiptVoucher]
  where YEAR([VoucherDate])=@Year and MONTH([VoucherDate])=@Month
  and IsDel=0
  and [Status]=2
  group by ReceiptAccount

union all

  
  SELECT  PaymentAccount Account,'Expense' [Type],SUM(Amount) Amount  
  FROM [dbo].[PaymentVoucher]
  where YEAR([VoucherDate])=@Year and MONTH([VoucherDate])=@Month
  and IsDel=0
  and [Status]=2
  group by PaymentAccount
  ) t
 
  
  select * from #t
  
  SELECT Account,

 max(CASE [Type] WHEN'InCome' THEN Amount ELSE 0 END) Income,

 max(CASE [Type] WHEN'Expense' THEN Amount ELSE 0 END) Expense


FROM #t

GROUP BY Account

drop table #t


 

你可能感兴趣的:(SQL行转列(暂时记录,后期完善改文章))