我有数据:
2014-10-28 Excess 1025 98297654999.82
2014-10-29 Excess 251 1902171582.07
2014-10-28 Pastdue 1590 7645464003.17
2014-10-29 Pastdue 13 3704776.10
我需要这样的数据:
Date ExcessCount ExcessAmt PassCount PassAmt
28/10/2015 1025 98297655000 1590 7645464003
29/10/2015 251 1902171582 13 3704776.1
请让我知道如何做到这一点。
答案 0 :(得分:5)
检查出来
SELECT column1 as date, SUM(ExcessCount) as ExcessCount, SUM(ExcessAmt) as ExcessAmt, SUM(PastdueCount) as PastdueCount, SUM(PastdueAmt) as PastdueAmt
FROM
(
select column1,column3,column4, column2+'Count' as tempcol1,column2+'Amt' as tempcol2
from tablename
) x
pivot
(
min(column3)
for tempcol1 in ([ExcessCount], [PastdueCount])
) p
pivot
(
min(column4)
for tempcol2 in ([ExcessAmt], [PastdueAmt])
) q
group by column1
将主表列名称放在column1,Column2,Column3,Column4
FYI ..
答案 1 :(得分:2)
您可以使用条件聚合执行此操作:
select DateColumn,
sum(case when ExcessColumn = 'Excess' then CountColumn else 0 end) as ExcessCount,
sum(case when ExcessColumn = 'Excess' then AtmColumn else 0 end) as ExcessAmt,
sum(case when ExcessColumn = 'Pastdue' then CountColumn else 0 end) as PassCount,
sum(case when ExcessColumn = 'Pastdue' then AtmColumn else 0 end) as PassAtm
from TableName
group by DateColumn
答案 2 :(得分:1)
Instead of Pivot
,转到 Simple Subquery
:
create table #test
(
dates datetime,
descs varchar(10),
value int,
amount varchar(30)
)
insert into #test values('2014-10-28','Excess',1025,'98297654999.82')
insert into #test values('2014-10-29','Excess',251,'1902171582.07')
insert into #test values('2014-10-28','Pastdue',1590,'7645464003.17')
insert into #test values('2014-10-29','Pastdue',13,'3704776.10')
select * from #test
select distinct a.dates
,(select value from #test b where descs='Excess' and a.dates=b.dates) as 'ExcessCount'
,(select amount from #test b where descs='Excess' and a.dates=b.dates) as 'ExcessAmt'
,(select value from #test b where descs='Pastdue'and a.dates=b.dates) as 'PassCount',
(select amount from #test b where descs='Pastdue'and a.dates=b.dates) as 'PassAmt'
from #test a
输出:
dates ExcessCount ExcessAmt PassCount PassAmt
2014-10-28 00:00:00.000 1025 98297654999.82 1590 7645464003.17
2014-10-29 00:00:00.000 251 1902171582.07 13 3704776.10