SQL Server从两行获取结果

时间:2016-12-06 06:43:19

标签: sql-server tsql sql-server-2012

我正在寻找一种在SQL Server中将行转换为列的方法。我不知道该怎么做。我需要比较两年。例如,我有

Year  Item     Qty
-------------------
2014  Shoes    500
2014  Ties     300
2014  Pants    200
2015  Shoes    600
2015  Ties     200
2015  Buttons  100

我想得到如下数据:

Item    Year1   Qty1    Year2   Qty2
------------------------------------
Shoes   2014    500     2015    600
Ties    2014    300     2015    200
Pants   2014    200     -       -
Buttons  -      -       2015    100

查询应该如何才能获得结果?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码执行此操作:

DECLARE @DataSource TABLE
(
    [Year] SMALLINT
   ,[Item] VARCHAR(12)
   ,[Qty] SMALLINT
);

INSERT INTO @DataSource ([Year], [Item], [Qty])
VALUES (2014, 'Shoes', 500)
      ,(2014, 'Ties', 300)
      ,(2014, 'Pants', 200)
      ,(2015, 'Shoes', 600)
      ,(2015, 'Ties', 200)
      ,(2015, 'Buttons', 100);


SELECT [Item]
      ,IIF([2014] IS NOT NULL, 2014, NULL) AS [Year1]
      ,[2014] AS [Qty1]
      ,IIF([2015] IS NOT NULL, 2015, NULL) AS [Year2]
      ,[2015] AS [Qt2]
FROM @DataSource DS
PIVOT
(
    MAX([Qty]) FOR [Year] IN ([2014], [2015])
) PVT;

enter image description here

无论如何,您只能使用以下代码,比较似乎更容易,但我不了解您的具体需求:

SELECT [Item]
      ,[2014]
      ,[2015]
FROM @DataSource DS
PIVOT
(
    MAX([Qty]) FOR [Year] IN ([2014], [2015])
) PVT;

enter image description here