Sql 将分组结果拆分为不同列

Sql 将分组结果拆分为不同列,sql,sql-server-2008,common-table-expression,Sql,Sql Server 2008,Common Table Expression,我有一个列,其中包含日期范围和与特定ID关联的天数(一对多),根据关联的记录数,我希望将这些结果拆分为列,而不是单独的行,因此: id_hr dd beg end ---------------------------------------- 1 10 05/01/2019 15/01/2019 1 5 03/02/2019 08/02/2019 2 8 07/03/2019 15/03/2019 可能会变成这样: id_hr

我有一个列,其中包含日期范围和与特定
ID
关联的天数(一对多),根据关联的记录数,我希望将这些结果拆分为列,而不是单独的行,因此:

id_hr  dd beg          end
----------------------------------------
1      10 05/01/2019   15/01/2019
1      5  03/02/2019   08/02/2019
2      8  07/03/2019   15/03/2019
可能会变成这样:

id_hr  dd beg          end        dd beg          end
--------------------------------- ---------------------
1      10 05/01/2019   15/01/2019 5  03/02/2019   08/02/2019
2      8  07/03/2019   15/03/2019
我在一个工作表(透视表)中也做了同样的操作,但是该表变得非常慢,所以我正在寻找一种更友好的SQL方法,我做了一个CTE,对相关行进行编号,然后选择每一行并在新列中显示它们

;WITH CTE AS(
   SELECT PER_PRO, ID_HR, NOM_INC, rut_dv, dias_dur, INI, FIN,
       ROW_NUMBER()OVER(PARTITION BY ID_HR ORDER BY SUBIDO) AS RN
   FROM dbo.inf_vac WHERE PER_PRO = 201902
)
SELECT ID_HR, NOM_INC, rut_dv,
    (case when rn = 1 then DIAS_DUR end) as DIAS_DUR1,
    (case when rn = 1 then INI end) as INI1,
    (case when rn = 1 then FIN end) as FIN1,

    (case when rn = 2 then DIAS_DUR end) as DIAS_DUR2,
    (case when rn = 2 then INI end) as INI2,
    (case when rn = 2 then FIN end) as FIN2,

    (case when rn = 3 then DIAS_DUR end) as DIAS_DUR3,
    (case when rn = 3 then INI end) as INI3,
    (case when rn = 3 then FIN end) as FIN3
FROM CTE
这让我知道每一列应该在哪里,但不是分组。使用GROUP BY在CTE select上显示错误

rn id_hr  dd    beg          end        dd    beg          end
----------------------------------- ------------------------
1  1      10   05/01/2019   15/01/2019 NULL  NULL         NULL
2  1      NULL NULL         NULL       5     03/02/2019   08/02/2019
1  2      8    07/03/2019   15/03/2019 NULL  NULL         NULL

有没有办法在第二次选择时对它们进行分组?

是的,您可以按所有非大小写列进行分组,并对每个大小写表达式列应用MAX。

您在结果集中有其他不在查询中的列。然而,这应该是可行的:

SELECT ID_HR,
       max(case when rn = 1 then DIAS_DUR end) as DIAS_DUR1,
       max(case when rn = 1 then INI end) as INI1,
       max(case when rn = 1 then FIN end) as FIN1,

       max(case when rn = 2 then DIAS_DUR end) as DIAS_DUR2,
       max(case when rn = 2 then INI end) as INI2,
       max(case when rn = 2 then FIN end) as FIN2,

       max(case when rn = 3 then DIAS_DUR end) as DIAS_DUR3,
       max(case when rn = 3 then INI end) as INI3,
       max(case when rn = 3 then FIN end) as FIN3
FROM CTE
GROUP BY ID_HR;