我的动态轴的输出如下所示:
我假设如果我得到0
's 而不是NULL
's 那么EffectiveMMYY
将被分组并且不会有重复项。
那么如何用 0 替换 NULL 呢?
没有累积总输出应该是这样的:
累积总输出应如下所示:
链接到 dbfile
https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=b2e9d0a6fc58705b8f310babbe3f158e
这是示例查询:
IF OBJECT_ID('tempdb..##DynPivot') IS NOT NULL DROP TABLE ##DynPivot
DECLARE @Table1 TABLE (ID int, PolicyNumber varchar(50),EffectiveDate date, LossDate date)
INSERT INTO @Table1
(
ID,
PolicyNumber,
EffectiveDate,
LossDate
)
VALUES
( 1, 'Pol1', '2017-02-01', '2017-02-05'),
( 2, 'Pol2', '2017-03-04', '2017-03-18'),
( 3, 'Pol3', '2017-03-11', '2017-03-22'),
( 4, 'Pol4', '2017-03-11', NULL),
( 5, 'Pol5', '2017-03-15', '2017-04-22'),
( 6, 'Pol6', '2017-04-18', '2017-04-19'),
( 7, 'Pol7', '2017-04-22', '2017-04-29'),
( 8, 'Pol8', '2017-04-15', '2017-04-18'),
( 9, 'Pol9', '2017-12-15', '2018-01-23'),
( 10, 'Pol10', '2017-02-13', '2017-03-11'),
( 11, 'Pol11', '2017-02-18', '2017-03-22'),
( 12, 'Pol12', '2017-02-17', '2018-01-05'),
( 13, 'Pol13', '2017-05-28', '2017-05-30')
SELECT
FORMAT(EffectiveDate, 'MMM') + '-'+ FORMAT(EffectiveDate, 'yy') AS 'EffectiveMMYY',
YEAR(EffectiveDate) AS EffYear, MONTH(EffectiveDate) AS EffMonth,
YEAR(LossDate) AS LossYear, MONTH(LossDate) AS LossMonth,
FORMAT(LossDate, 'MMM') + '-'+ FORMAT(LossDate, 'yy') AS 'LossMMYY',
count(PolicyNumber) AS PolicyCout
into ##DynPivot
FROM @Table1
WHERE LossDate IS NOT NULL
GROUP BY FORMAT(EffectiveDate, 'MMM') + '-'+ FORMAT(EffectiveDate, 'yy'),
FORMAT(LossDate, 'MMM') + '-'+ FORMAT(LossDate, 'yy'),
YEAR(EffectiveDate),
MONTH(EffectiveDate),
YEAR(LossDate), MONTH(LossDate)
ORDER BY FORMAT(EffectiveDate, 'MMM') + '-'+ FORMAT(EffectiveDate, 'yy')
Declare @SQL varchar(max) = Stuff((Select ',' + QuoteName(LossMMYY) From ##DynPivot group by LossMMYY Order by min(LossYear), min(LossMonth) For XML Path('')),1,1,'')
select @SQL = '
select EffectiveMMYY,' + @SQL + '
from ##DynPivot
pivot ( sum(PolicyCout) for LossMMYY IN (' + @SQL + ') ) p
order by EffYear,EffMonth
'Exec(@SQL);