数据透视表上的t-sql辅助数据透视表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据透视表上的t-sql辅助数据透视表相关的知识,希望对你有一定的参考价值。
如何重新调整此表以解释名称的差异?
到目前为止我所拥有的:
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
我相信我很接近,但最后的枢轴让我失望。
任何帮助,将不胜感激。谢谢!
答案
如果你想动态创建列,意思是说你有一个person4
,你就是不能单独使用PIVOT
。您必须使用For xml
来转置您的数据或另一个选项是使用游标,但我个人更喜欢For Xml
。查看for xml的这篇文章
另一答案
你可以尝试使用条件聚合函数,MAX
和CASE 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
| 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 |
另一答案
请试试这个......
SELECT badge, [AP_KDA], [AP_Match], [ADC_KDA], [ADC_Match], [TOP_KDA], [TOP_Match],
[Person1],[Person2],[Person3]
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'+ CAST ((ROW_NUMBER() OVER (PARTITION BY badge
ORDER BY name DESC)) AS VARCHAR) AS Col, CAST(name AS VARCHAR) 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], [Person1],[Person2],[Person3])
) AS pvt
以上是关于数据透视表上的t-sql辅助数据透视表的主要内容,如果未能解决你的问题,请参考以下文章