在SQL Server中透视数据

时间:2015-02-17 14:12:48

标签: sql sql-server tsql

我在使用此代码创建的sql server中有一个表

CREATE TABLE t3
(`NAME` varchar(20), `VALUE` varchar(17));

INSERT INTO t3
(`NAME`, `VALUE`)
VALUES
('Name_Screened', 'johny bravo'),
('Name_Screened', 'JOHNY CHAVO'),
('Match_Type', 'Direct'),
('Match_Type', 'Direct'),
('Disposition', 'Successful'),
('Disposition', 'Successful'),
('Compliance_Approval', 'Yes'),
('Compliance_Approval', 'Yes'),
('Supporting_Documents', 'Lexix Nexis Match'),
('Supporting_Documents', 'WORD NET MATCH');

我正在尝试使用代码

来转移此数据
SELECT  PVT.Match_Type,  PVT.Name_Screened,PVT.Disposition,PVT.Compliance_Approval,PVT.Supporting_Documents
FROM T3 
PIVOT (
 max(VALUE)
FOR NAME IN    (Match_Type,Name_Screened,Disposition,Compliance_Approval,Supporting_Documents)
) PVT

但我只得这样一行

Match_Type - Name_Screened - Disposition - Compliance_Approval - Supporting_Documents
Direct     - JOHNY CHAVO   - Successful  - Yes                 - WORD NET MATCH

我想从10个数据行中获得两行但只获得一行 我想我错过了仅在pivot中的右聚合功能。请帮忙

1 个答案:

答案 0 :(得分:2)

您需要稍微修改一下您的查询:

SELECT PVT.Match_Type, PVT.Name_Screened, PVT.Disposition, 
       PVT.Compliance_Approval,PVT.Supporting_Documents
FROM (
   SELECT NAME, VALUE, 
          ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY VALUE) AS rn
   FROM T3 ) AS src
PIVOT (
   MAX(VALUE)
   FOR NAME IN (Match_Type, Name_Screened, Disposition, 
                Compliance_Approval,Supporting_Documents)
) pvt

这会为rn的每个src值生成一个单独的行。