很难在SQL Server中创建PIVOT

时间:2015-12-22 10:22:01

标签: sql-server pivot-table

大家好,我对如何在这种情况下实施PIVOT非常困惑

AccId   Year    Month   AccType     Value
225     2012    7           1       2
225     2012    7           2       0
225     2012    7           3       0
226     2012    7           1       3
226     2012    7           2       0
226     2012    7           3       0

我无法解决的主要问题是AccId加入了AccountTable,AccType也加入了AccountType表我需要输出如下:

AccId AccName Year Month AccType AccTypeName Value AccType AccTypeName Value AccType AccTypeName Value
225   ABC     2012  7      1        AAA        2     2         BBB       0      3       CCC    0 
226   ABC     2012  7      1        AAA        3     2         BBB       0      3       CCC    0

请帮助。感谢。

1 个答案:

答案 0 :(得分:0)

DECLARE @Table1 TABLE 
    (AccId int, Year int, Month int, AccType int, Value int)
;

INSERT INTO @Table1
    (AccId, Year, Month, AccType, Value)
VALUES
    (225, 2012, 7, 1, 2),
    (225, 2012, 7, 2, 0),
    (225, 2012, 7, 3, 0),
    (226, 2012, 7, 1, 3),
    (226, 2012, 7, 2, 0),
    (226, 2012, 7, 3, 0)
;


DECLARE @Tabletype TABLE 
    (AccId int, Type Varchar(6))
    INSERT INTO @Tabletype
    (AccId,Type )values (225,'AAA'), (226,'BBB')
;
;WITH CTE AS (
Select AccId, Year, Month,1 AS Acct1,2 AS Acct2,3 AS Acct3,Type from (
select T.AccId, T.Year, T.Month,T.AccType,TT.Type,ROW_NUMBER()OVER(PARTITION BY T.AccId ORDER BY T.Year,T.month)RN from @Table1 T
INNER JOIN  @Tabletype TT
ON T.AccId = TT.AccId)T
PIVOT(MAX(RN) FOR AccType IN([1],[2],[3]))PVT
GROUP BY AccId, Year, Month,pvt.Type)
, CTE2 AS (
Select AccId, Year, Month,[0] AS val1,[2] AS val2,[3] AS val3,Type from (
select T.AccId, T.Year, T.Month, T.Value,TT.Type,ROW_NUMBER()OVER(PARTITION BY T.AccId ORDER BY T.Year,T.month)RN from @Table1 T
INNER JOIN  @Tabletype TT
ON T.AccId = TT.AccId)T
PIVOT(MAX(RN) FOR value IN([0],[2],[3]))PVTt
GROUP BY AccId, Year, Month,PVTt.[0],PVTt.[2],PVTt.[3],PVTt.Type)



select c.AccId,
c.Year,
C.Month,
c.Acct1,
c.Type,
ISNULL(cc.val1,0)val1,
C.Acct2,
c.Type,
ISNULL(CC.val2,0)val2,
C.Acct3,
c.Type,
ISNULL(CC.val3,0)val3 from CTE c
inner join CTE2 cc
on c.AccId = cc.AccId