重新格式化SQL输出

时间:2019-06-14 04:37:22

标签: sql sql-server

我有类似这样的数据

Name  XX YY
alpha 10 77
beta  10 90
alpha 20 72
beta  20 91
alpha 30 75
beta  30 94
alpha 40 76
beta  40 95

如果我使用

select * from scores order by Name, XX

我会得到

Name  XX YY
alpha 10 77
alpha 20 72
alpha 30 75
alpha 40 76
beta  10 90
beta  20 91
beta  30 94
beta  40 95

此刻,我正在以这种形式检索数据,并使用一些C编码对其进行格式化

Name   xx=10  xx=20  xx=30  xx=40
alpha  77     72     75     76
beta   90     91     94     95

假设每个名称总会有10、20、30、40个条目,这在SQL中可能是这样,而无需在SQL Reformatting table columns中创建新表

3 个答案:

答案 0 :(得分:3)

您需要使用PIVOT才能获得所需的结果。使用PIVOT之前,需要在第XX列的值中进行一些自定义,以便最终的列输出可以满足您的期望。

SELECT * FROM
(
SELECT Name,'XX='+CAST(XX AS VARCHAR) XX,YY 
FROM your_table
)AS P
PIVOT(
    SUM(YY)
    FOR XX IN ([XX=10],[XX=20],[XX=30],[XX=40])
) PP

输出-

Name    XX=10   XX=20   XX=30   XX=40
alpha   77      72      75      76
beta    90      91      94      95

通过以下查询也可以实现相同的输出-

SELECT Name,
[10] AS [XX=10],
[20] AS [XX=20],
[30] AS [XX=30],
[40] AS [XX=40]
FROM
(
    SELECT Name, XX,YY 
    FROM your_table
)AS P
PIVOT(
    SUM(YY)
    FOR XX IN ([10],[20],[30],[40])
) PP

答案 1 :(得分:1)

您可以使用动态PIVOT来获得相同的结果,但效果会更强大,

CREATE TABLE #table1 (Name varchar(100), XX INT, YY INT)

INSERT INTO #table1 VALUES
('alpha',10,77),
('beta',10,90),
('alpha',20,72),
('beta',20,91),
('alpha',30,75),
('beta',30,94),
('alpha',40,76),
('beta',40,95)

DECLARE @pvt NVARCHAR(MAX) = '';
DECLARE @dynamicCol NVARCHAR(MAX) = '';

SELECT @pvt +=  ', ' +QUOTENAME([XX]) FROM #table1 GROUP BY [XX];
SELECT @dynamicCol +=  ', ' +QUOTENAME([XX]) + ' AS ' + QUOTENAME('XX=' + CAST([XX] AS VARCHAR(25))) FROM #table1 GROUP BY [XX];
SET @pvt = STUFF(@pvt,1,1,'')
SET @dynamicCol = STUFF(@dynamicCol,1,1,'')

EXEC ('
SELECT [Name],' + @dynamicCol+'
FROM #table1 a
PIVOT 
(
  SUM([YY])
  FOR [XX] IN ('+ @pvt+')
) PIV');

结果如下,

Name    XX=10   XX=20   XX=30   XX=40
alpha   77      72      75      76
beta    90      91      94      95

答案 2 :(得分:0)

解决案件的另一种方法

SELECT Name
  ,SUM(CASE when XX = '10' then YY else 0 END) AS 'xx=10'
  ,SUM( CASE when XX = '20' then YY else 0 END) AS 'xx=20'
  ,SUM( CASE when XX = '30' then YY else 0 END) AS 'xx=30'
  ,SUM( CASE when XX = '40' then YY else 0 END) AS 'xx=40'
  FROM temp_0
  group by Name