SQL 自连接/透视 table 查询

SQL Self Join / Pivot table query

我在 SQL Server 2016 中有以下表 1:

SELECT Year, Type, Value From Table1

    Year  Type  Value
    2010  1     10
    2010  2     15
    2010  3     20
    2011  1     100
    2011  2     150
    2011  3     200

我想把它转换成下面的形式table:

Year  Type1  Type2  Type3
2010  10     15     20
2011  100    150    200

我认为我们可以通过自连接或枢轴 table 来实现这一点。实现这一目标的最佳方法是什么?

假设您始终有 3 种类型,使用条件聚合是解决此问题的简单方法。

select [Year]
    , Type1 = Max(case when [Type] = 1 then Value end)
    , Type2 = Max(case when [Type] = 2 then Value end)
    , Type3 = Max(case when [Type] = 3 then Value end)
from Table1
group by [Year]
order by [Year]
select * 
from myTable PIVOT ( SUM(Value) FOR [Type] IN ( [1], [2], [3] ) ) pvt;

DbFiddle demo

假设你总是有 3 种类型,你可以在 SQL.

中使用 PIVOT

以下是基于您的示例的示例:

if object_id('tempdb..#temp1') is not null
    drop table #temp1

create table #temp1 (
     Year  int
     ,Type  int
     ,Value int
)

insert into #temp1 values 
    (2010,1,10),
    (2010,2,15),
    (2010,3,20),
    (2011,1,100),
    (2011,2,150),
    (2011,3,200)

SELECT 
    Year
    , [1] AS Type1
    , [2] AS Type2
    , [3] AS Type3
FROM   
    #temp1 p  
PIVOT  
(  
sum(value)  
FOR type IN  
( [1], [2], [3])  
) AS pvt  
ORDER BY pvt.Year  

结果如下:

CREATE TABLE #myTable (
[Year] int, [Type] int, [Value] int, [ExtraColumn] varchar(10));

INSERT INTO #myTable ([Year], [Type], [Value], [ExtraColumn]) 
VALUES (2010, 1, 10, 'I'), 
       (2010, 2, 15, 'G'), 
       (2010, 3, 20, 'N'), 
       (2011, 1, 100, 'O'), 
       (2011, 2, 150, 'R'), 
       (2011, 3, 200, 'E'); 

select Year, [1] as Type1, [2] as Type2, [3] as Type3 
from ( 
 select [Year], [Type], [Value] 
 from #myTable 
 ) t 
PIVOT ( SUM(Value) FOR [Type] IN ( [1], [2], [3] ) ) pvt;

-- OR
with myData as
( 
 select [Year], [Type], [Value] 
 from #myTable 
)
select Year, [1] as Type1, [2] as Type2, [3] as Type3 
from myData
PIVOT ( SUM(Value) FOR [Type] IN ( [1], [2], [3] ) ) pvt;

drop table #myTable;