一个简单的枢轴,但无法绕开它-请协助.. :-)

时间:2019-05-29 07:59:05

标签: sql-server pivot

我尝试在MS SSMS中做一个简单的介绍,但无法弄清楚。

这是我的数据集:

Date        CallerANI      Skills               CallerDNIS
2019-05-27  27315391449    loc-SPD-CSR-OverFlow 47515070001
2019-05-27  27315391449    cc-Loc-Voice         Transfer

和声明:

SELECT [Date],
       CallerANI,
       [47515001101],
       [Transfer]
FROM (SELECT [Date], Skills, CallerANI, CallerDNIS FROM #TempDB) AS p
PIVOT (MAX(Skills)
       FOR CallerDNIS IN ([47515001101], [Transfer])) AS pvt;

我想旋转,以便结果看起来像这样:

Date            CallerANI              [47515070001]            [Transfer]
2019-05-27      273135391449           loc-SPD-CSR-OverFlow     cc-loc-Voice

2 个答案:

答案 0 :(得分:3)

就个人而言,我更喜欢在内置PIVOT函数上使用交叉表。我发现它更容易使用:

SELECT [Date],
       CallerANI,
       MAX(CASE WHEN V.CallerDNIS = '47515070001' THEN Skills END) AS [47515070001],
       MAX(CASE WHEN V.CallerDNIS = 'Transfer' THEN Skills END) AS [Transfer]
FROM (VALUES (CONVERT(date,'20190527'),27315391449,'loc-SPD-CSR-OverFlow','47515070001'),
             (CONVERT(date,'20190527'),27315391449,'cc-Loc-Voice','Transfer')) V([Date],CallerANI,Skills,CallerDNIS)
GROUP BY [Date],
         CallerANI;

答案 1 :(得分:3)

以下代码可帮助您动态 枢轴 N行

DECLARE @DynamicCols VARCHAR(MAX);

CREATE TABLE #temp ([Date] DATE, [CallerANI] VARCHAR(MAX), [Skills] VARCHAR(MAX), [CallerDNIS] VARCHAR(MAX))

INSERT INTO #temp 
VALUES ('2019-05-27','27315391449','loc-SPD-CSR-OverFlow','47515070001'),
       ('2019-05-27','27315391449','cc-Loc-Voice','Transfer'),
       ('2019-05-27','27315391449','cc-Loc-Voice-abc','SoMe')

SELECT * FROM #temp

SELECT @DynamicCols = STUFF([Cols],1,1,'') FROM (
SELECT [Cols] = (SELECT ',' + QUOTENAME([CallerDNIS]) FROM #temp A
                   FOR XML PATH('') ) ) A;

EXEC ('
SELECT [Date], [CallerANI], ' + @DynamicCols+'
FROM #temp
PIVOT 
(
  MAX([Skills])
  FOR [CallerDNIS] in (' + @DynamicCols+')
) PIV');