我有这样的东西:
此查询
SELECT DISTINCT Securitization, SUM(RemittableCollections) [RemittableCollections], ReportingDate
FROM Securitization.dbo.SecuritizationReporting
GROUP BY Securitization,ReportingDate
我想要的是报告日期在行上,所以我将证券化为列,然后对于每个报告日期,我将有一定数量的Remittable集合,该怎么办?
这是我正在尝试做的事,但没有用
SELECT DISTINCT Securitization, ReportingDate
FROM Securitization.dbo.SecuritizationReporting
PIVOT
(
SUM(RemittableCollections)
for dates in (SELECT DISTINCT ReportingDate FROM Securitization.dbo.SecuritizationReporting )
)
GROUP BY Securitization,ReportingDate
答案 0 :(得分:1)
未经测试,但这也许会有所帮助
Declare @SQL varchar(max) = '
Select *
From (Select Distinct
Securitization
,ReportingDate
,RemittableCollections
From Securitization.dbo.SecuritizationReporting
) src
Pivot ( sum(RemittableCollections) for ReportingDate in ( ' + Stuff((Select Distinct
',' + QuoteName(ReportingDate)
From Securitization.dbo.SecuritizationReporting
Order By 1
For XML Path('')),1,1,'') +' ) ) pvt
'
--Print(@SQL)
Exec(@SQL)
编辑-删除NULL
Declare @NoNulls varchar(max) = Stuff( (
Select Distinct
',' + QuoteName(ReportingDate) +' = IsNull(' + QuoteName(ReportingDate) +',0)'
From Securitization.dbo.SecuritizationReporting
Order By 1
For XML Path('')),1,1,'')
Declare @SQL varchar(max) = '
Select [Securitization]
,' + @NoNulls + '
From (Select Distinct
Securitization
,ReportingDate
,RemittableCollections
From Securitization.dbo.SecuritizationReporting
) src
Pivot ( sum(RemittableCollections) for ReportingDate in ( ' + Stuff((Select Distinct
',' + QuoteName(ReportingDate)
From Securitization.dbo.SecuritizationReporting
Order By 1
For XML Path('')),1,1,'') +' ) ) pvt
'
--Print(@SQL)
Exec(@SQL)