t-sql数据透视表上的辅助数据透视

时间:2018-08-30 22:07:18

标签: sql sql-server tsql pivot

我将如何再次旋转该表以解决名称差异?

到目前为止我所拥有的:


CREATE TABLE Temp
(
    badge  nvarchar(4)
   ,name   nvarchar(31)
   ,Job    nvarchar(4)
   ,KDA    float
   ,Match  int
)

INSERT INTO Temp
VALUES ('T996', 'Darrien', 'AP', 1.0, 20),
       ('T996', 'Mark', 'ADC', 2.8, 16),
       ('T996', 'Kevin', 'TOP', 5.0, 120)

SELECT badge, [AP_KDA], [AP_Match], [ADC_KDA], [ADC_Match], [TOP_KDA], [TOP_Match], [Person]
FROM (
    SELECT badge, Col, Val
    FROM (
          SELECT badge, Job + '_KDA' AS Col, CAST(KDA AS nvarchar(31)) AS Val
          FROM Temp
          UNION ALL
          SELECT badge, Job + '_Match' AS Col, CAST(Match AS nvarchar(31)) AS Val  
          FROM Temp
          UNION ALL
          SELECT badge, 'Person' AS Col, name AS Val
          FROM Temp
    ) AS t
) AS tt
PIVOT (MIN(Val) FOR Col IN ([AP_KDA], [AP_Match], [ADC_KDA], [ADC_Match], [TOP_KDA], [TOP_Match], [Person])
) AS pvt

哪个输出:


   badge AP_KDA AP_Match ADC_KDA ADC_Match  TOP_KDA TOP_Match Person
1  T996  1      20       2.8     16         5       120       Darrien

我希望将其格式化为:


   badge AP_KDA AP_Match ADC_KDA ADC_Match  TOP_KDA TOP_Match Person1 Person2 Person3
1  T996  1      20       2.8     16         5       120       Darrien Mark  Kevin

我相信我已经接近了,但是最后的枢轴把我赶走了。

任何帮助将不胜感激。 谢谢!

3 个答案:

答案 0 :(得分:2)

您可以尝试将条件聚集函数MAXCASE WHEN结合使用来构成枢纽。

CREATE TABLE Temp
(
    badge  nvarchar(4),
    name   nvarchar(31),
    Job   nvarchar(4),
    KDA   float,
    Match  int
 )

 INSERT INTO Temp VALUES
 ( 'T996'  ,  'Darrien'  , 'AP'  , 1.0,   20),
 ('T996'   ,  'Mark'  , 'ADC'  , 2.8   ,   16),
 ( 'T996'  ,  'Kevin'  , 'TOP' ,  5.0   ,   120)

查询1

SELECT badge,
      MAX(CASE WHEN Job = 'AP' THEN KDA END)    AP_KDA,
      MAX(CASE WHEN Job = 'AP' THEN Match END)  AP_Match,
      MAX(CASE WHEN Job = 'ADC' THEN KDA END)   ADC_KDA,
      MAX(CASE WHEN Job = 'ADC' THEN Match END) ADC_Match,
      MAX(CASE WHEN Job = 'TOP' THEN KDA END)   TOP_KDA,
      MAX(CASE WHEN Job = 'TOP' THEN Match END) TOP_Match,
      MAX(CASE WHEN Job = 'AP' THEN  name END)  Person1 ,
      MAX(CASE WHEN Job = 'ADC' THEN name END)  Person2 ,
      MAX(CASE WHEN Job = 'TOP' THEN name END)  Person3
FROM TEMP
GROUP BY  badge

Results

| badge | AP_KDA | AP_Match | ADC_KDA | ADC_Match | TOP_KDA | TOP_Match | Person1 | Person2 | Person3 |
|-------|--------|----------|---------|-----------|---------|-----------|---------|---------|---------|
|  T996 |      1 |       20 |     2.8 |        16 |       5 |       120 | Darrien |    Mark |   Kevin |

答案 1 :(得分:1)

请尝试一下...

paste the token

答案 2 :(得分:0)

如果您想动态创建列,这意味着您有一个<httpRuntime requestValidationMode="2.0" enableVersionHeader="false" targetFramework="4.5" maxRequestLength="51200" fcnMode="Single" /> ,那么仅使用person4就无法做到这一点。您必须使用PIVOT来转置数据,或者另一个选择是使用游标,但是我个人更喜欢For xml。参见此帖子,了解for xml