我的实际表格就像这样
-----------------------------------------------------------------------------
[Code | Name | PrevYear | NextYear | PrevYearQty | NextYearQty |]
-----------------------------------------------------------------------------
A Adapter Jan13 Jan14 100 110
A Adapter Feb13 Feb14 50 55
B Baloon Jan13 Jan14 30 33
B Baloon Mar13 Mar14 80 88
D Deodrant Feb13 Feb14 110 121
C Camera Mar13 Mar14 200 220
我想要这样的结果
-----------------------------------------------------------------------------
Code | Name | Jan13 | Jan14 | Feb13 | Feb14 | Mar13 | Mar14 |
-----------------------------------------------------------------------------
A Adapter 100 110 - - - -
A Adapter - - 50 55 - -
B Baloon 30 33 - - - -
B Baloon - - - - 80 88
D Deodrant - - 110 121 - -
C Camera - - - - 200 220
_______________________________________________________________________________
请帮我解决这个问题。
答案 0 :(得分:1)
测试数据
DECLARE @TableName TABLE(Code CHAR(1), Name VARCHAR(10),PrevYear VARCHAR(10)
,NextYear VARCHAR(10), PrevYearQty INT, NextYearQty INT)
INSERT INTO @TableName VALUES
('A','Adapter' ,'Jan13','Jan14',100,110),('A','Adapter' ,'Feb13','Feb14',50 ,55),
('B','Baloon' ,'Jan13','Jan14',30 ,33),('B','Baloon' ,'Mar13','Mar14',80 ,88),
('D','Deodrant','Feb13','Feb14',110,121),('C','Camera' ,'Mar13','Mar14',200,220)
<强>查询强>
SELECT * FROM
(
SELECT Code, Name, PrevYear AS Yr, PrevYearQty AS Qty FROM @TableName
UNION ALL
SELECT Code, Name, NextYear, NextYearQty FROM @TableName
)t
PIVOT (SUM(Qty)
FOR Yr
IN ([Jan13],[Jan14],[Feb13],[Feb14],[Mar13],[Mar14])
)p
结果集
╔══════╦══════════╦═══════╦═══════╦═══════╦═══════╦═══════╦═══════╗
║ Code ║ Name ║ Jan13 ║ Jan14 ║ Feb13 ║ Feb14 ║ Mar13 ║ Mar14 ║
╠══════╬══════════╬═══════╬═══════╬═══════╬═══════╬═══════╬═══════╣
║ A ║ Adapter ║ 100 ║ 110 ║ 50 ║ 55 ║ NULL ║ NULL ║
║ B ║ Baloon ║ 30 ║ 33 ║ NULL ║ NULL ║ 80 ║ 88 ║
║ C ║ Camera ║ NULL ║ NULL ║ NULL ║ NULL ║ 200 ║ 220 ║
║ D ║ Deodrant ║ NULL ║ NULL ║ 110 ║ 121 ║ NULL ║ NULL ║
╚══════╩══════════╩═══════╩═══════╩═══════╩═══════╩═══════╩═══════╝
如果您希望查询动态选择列,请在此处了解如何执行此操作。
动态查询
DECLARE @Cols NVARCHAR(MAX);
DECLARE @Sql NVARCHAR(MAX);
SELECT @Cols = STUFF((SELECT DISTINCT ', ' + QUOTENAME(q.Yr)
FROM (
SELECT PrevYear AS Yr FROM TableName
UNION ALL
SELECT NextYear FROM TableName
)q
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,'')
SET @Sql = N'SELECT Code, Name, '+ @Cols +'
FROM
(
SELECT Code, Name, PrevYear AS Yr, PrevYearQty AS Qty FROM TableName
UNION ALL
SELECT Code, Name, NextYear, NextYearQty FROM TableName
)t
PIVOT (SUM(Qty)
FOR Yr
IN (' + @Cols + ')
)p'
EXECUTE sp_executesql @Sql