CTE分区在单独的列中

时间:2017-04-06 01:19:15

标签: sql sql-server tsql

我正在尝试获取用户帐户和笔记类型的分区,我需要的是每个经理记录(AMID)有1行,多个列用户计算每个不同笔记的笔记数类型。

我可以使用以下方法获得正确的结果:

WITH CTE AS
(
    SELECT AMID, ActionTypeID, COUNT(*) AS total, ROW_NUMBER() OVER  (PARTITION BY AMID, ActionTypeID ORDER BY AMID) AS RN
    FROM personNote
    GROUP BY AMID, ActionTypeID
)
SELECT * FROM CTE

这给了我这样的东西:

AMID    ActionTypeID    total   RN
1       12              231002  1
1       15              354936  1
3       0               74441   1
3       3               4       1
3       7               18      1

但是这在我需要将此代码放入的报告工具中不起作用,我需要将每个actionType ID放在不同的列中,所以像这样:

AMID   ActionTypeID   Total     ActionTypeID2   Total2
1      12             231002    15              354936   

提前致谢!

1 个答案:

答案 0 :(得分:3)

对于具有非独特/重复Colums的动态数据透视表

现在,这将改变或压缩列数。例如,如果AMID只有1个ActionTypeID,则无论ActionTypeID如何,这些值都将显示在第1列和第2列中。这将是一个小问题/更容易使列不同,因此"更宽"

Declare @SQL varchar(max) = Stuff((Select ',' + QuoteName(concat(Col,'A')) + ',' + QuoteName(concat(Col,'T')) 
                                    From (
                                          Select Distinct Col=1000+Dense_Rank() over (Partition By AMID Order By ActionTypeID) 
                                           From  #PersonNote
                                         ) A
                                    Order by 1 
                                    For XML Path('')),1,1,'') 
Select  @SQL = '
Select [YAxis] as [AMID],' + replace(replace(@SQL,'A]','A] as [ActionTypeID]'),'T]','T] as [Total]')  + '
From (
        Select YAxis = AMID
              ,XAxis = B.XAxis
              ,Value = B.Value
         From  (
                Select AMID
                      ,ActionTypeID
                      ,XAxis = 1000+Dense_Rank() over (Partition By AMID Order By ActionTypeID)
                      ,Value=COUNT(*)
                 From  #PersonNote
                 Group By AMID, ActionTypeID
               ) A
         Cross Apply ( values (concat(A.XAxis,''A''),A.ActionTypeID)
                             ,(concat(A.XAxis,''T''),A.Value)
                     ) B (XAxis,Value)

     ) A
 Pivot (sum(Value) For [XAxis] in (' + @SQL + ') ) p'
--Print  @SQL
Exec(@SQL);

<强>返回

enter image description here

使用以下测试数据

Create Table #PersonNote (AMID int,ActionTypeID int)
Insert Into #PersonNote values
(1,12),(1,12),(1,12),(1,12),(1,12),(1,12),(1,12),                -- Cnt 7
(1,15),(1,15),(1,15),(1,15),(1,15),(1,15),(1,15),(1,15),(1,15),  -- Cnt 9
(3,3),(3,3),(3,3),                                               -- Cnt 3
(3,7),(3,7),(3,7),(3,7),(3,7),(3,7),                             -- Cnt 6
(3,12)                                                           -- Cnt 1