我有一个表,上面有一个月的偏移量。我想绕过此列,但对于输出,我想使用偏移量来计算月份名称/年份。
我需要能够做到execute
而无需动态SQL。
在生产中,我的MyMonthOffset
可能会达到24(或更多)。我知道在PIVOT
FOR
部分,我将像FOR MyMonthOffset IN ("0", "1", "2", "3", ... "24")
一样列出所有这些。
CREATE TABLE dbo.MyData
(
MyName [NVARCHAR](10) NOT NULL
, MyMonthOffset [INT] NOT NULL
, MyCount [INT] NOT NULL
) ON [DEFAULT];
INSERT INTO dbo.MyData
VALUES
('four', 0, 6),
('four', 1, 8),
('four', 1, 4),
('four', 2, 8),
('four', 2, 5),
('four', 2, 5),
('four', 3, 4),
('four', 3, 8),
('four', 3, 8),
('one', 0, 3),
('one', 0, 5),
('one', 0, 4),
('one', 0, 2),
('one', 1, 4),
('one', 2, 1),
('one', 2, 1),
('one', 3, 9),
('three', 1, 1),
('three', 3, 6),
('three', 3, 9),
('three', 3, 7),
('two', 0, 10),
('two', 0, 1),
('two', 1, 7),
('two', 3, 7)
+--------+---------------+---------+
| MYNAME | MYMONTHOFFSET | MYCOUNT |
+--------+---------------+---------+
| four | 0 | 6 |
| four | 1 | 8 |
| four | 1 | 4 |
| four | 2 | 8 |
| four | 2 | 5 |
| four | 2 | 5 |
| four | 3 | 4 |
| four | 3 | 8 |
| four | 3 | 8 |
| one | 0 | 3 |
| one | 0 | 5 |
| one | 0 | 4 |
| one | 0 | 2 |
| one | 1 | 4 |
| one | 2 | 1 |
| one | 2 | 1 |
| one | 3 | 9 |
| three | 1 | 1 |
| three | 3 | 6 |
| three | 3 | 9 |
| three | 3 | 7 |
| two | 0 | 10 |
| two | 0 | 1 |
| two | 1 | 7 |
| two | 3 | 7 |
+--------+---------------+---------+
SELECT
*
FROM
(
SELECT
MyName
, MyMonthOffset
, MyCount
FROM dbo.MyData
) SourceTable
PIVOT
(
SUM(MyCount)
FOR MyMonthOffset IN ("0", "1", "2", "3")
) PivotTable
+--------+------+----+------+----+
| MYNAME | 0 | 1 | 2 | 3 |
+--------+------+----+------+----+
| four | 6 | 12 | 18 | 20 |
| one | 14 | 4 | 2 | 9 |
| three | NULL | 1 | NULL | 22 |
| two | 11 | 7 | NULL | 7 |
+--------+------+----+------+----+
+--------+--------+--------+--------+--------+
| MYNAME | JUL 18 | AUG 18 | SEP 18 | OCT 18 |
+--------+--------+--------+--------+--------+
| four | 6 | 12 | 18 | 20 |
| one | 14 | 4 | 2 | 9 |
| three | NULL | 1 | NULL | 22 |
| two | 11 | 7 | NULL | 7 |
+--------+--------+--------+--------+--------+
答案 0 :(得分:1)
您需要使用动态数据透视
为枢轴列声明两个变量,为别名列名称声明另一个变量。
DECLARE @cols AS NVARCHAR(MAX),
@Pivotcols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT DISTINCT ',"' + CAST(MyMonthOffset AS VARCHAR(5)) +'"'
FROM MyData
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @Pivotcols = STUFF((SELECT DISTINCT ',[' + CAST(MyMonthOffset AS VARCHAR(5)) + '] as ''' + FORMAT(DATEADD(mm,MyMonthOffset,GETDATE()),'MMM yy') + ''''
FROM MyData
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT MyName, '+ @Pivotcols + '
FROM
(
SELECT
MyName
, MyMonthOffset
, MyCount
FROM dbo.MyData
) SourceTable
PIVOT
(
SUM(MyCount)
FOR MyMonthOffset IN ('+@cols+')
) PivotTable'
execute(@query)