SQL Server:将多行合并为1行

时间:2018-10-05 09:14:50

标签: sql sql-server tsql query-performance

我正在使用SQL Server 2012 Standard,并且具有将多行合并为一行的性能关系。

示例:

enter image description here

我可以使用下面的查询来按预期方式获取数据,但性能不佳。 还有其他性能更好的查询吗?

WITH Data AS
(
    SELECT 88 ID, 1 AS [OrderFW],'a' AS Code,'n1' as Name UNION
    SELECT 88 ID,2 AS [OrderFW],'a' AS Code,'n2' as Name UNION
    SELECT 88 ID,3 AS [OrderFW],'a' AS Code,'n3' as Name UNION
    SELECT 99 ID,1 AS [OrderFW],'b' AS Code,'n4' as Name UNION
    SELECT 99 ID,2 AS [OrderFW],'b' AS Code,'n5' as Name
)
SELECT 
    d1.Code code1, d1.Name name1, 
    d2.Code code2, d2.Name name2,
    d3.Code code3, d3.Name name3
FROM
    Data d1
LEFT OUTER JOIN
    Data d2 ON d1.ID = d2.ID AND d2.OrderFW = 2
LEFT OUTER JOIN
    Data d3 ON d1.ID = d3.ID AND d3.OrderFW = 3
WHERE
    d1.OrderFW = 1

1 个答案:

答案 0 :(得分:3)

我会尝试聚合:

select Id, 
       max(case when seq = 1 then code end) as code1,
       max(case when seq = 1 then name end) as name1,
       max(case when seq = 2 then code end) as code2,
       max(case when seq = 2 then name end) as name2,
       max(case when seq = 3 then code end) as code3,
       max(case when seq = 3 then name end) as name3
from (select d.*,
             row_number() over (partition by code order by order) as seq
      from data d
     ) d
group by Id;

编辑:如果您已经有sequence(即Order),则仅聚合就足够了:

select Id, 
       max(case when [order] = 1 then code end) as code1,
       max(case when [order] = 1 then name end) as name1,
       max(case when [order] = 2 then code end) as code2,
       max(case when [order] = 2 then name end) as name2,
       max(case when [order] = 3 then code end) as code3,
       max(case when [order] = 3 then name end) as name3
from data d
group by Id;

编辑::感谢JohnLBevan的演示。

这里是SQL Fiddle Example

相关问题