SQL自联接/数据透视表查询

时间:2019-07-17 16:41:20

标签: sql-server tsql pivot-table self-join

我在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

我想将其转换为下表:

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

我认为我们可以通过自我联接或数据透视表来实现这一目标。实现此目标的最佳方法是什么?

4 个答案:

答案 0 :(得分:1)

假设使用条件聚合总是有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]

答案 1 :(得分:1)

select * 
from myTable PIVOT ( SUM(Value) FOR [Type] IN ( [1], [2], [3] ) ) pvt;

DbFiddle demo

答案 2 :(得分:1)

假设您始终有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  

以下是结果:

Pivot Results

答案 3 :(得分:1)

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;