将GROUP BY结果分成不同的列

时间:2019-03-05 19:46:43

标签: 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  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选择上显示错误。

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

有什么办法可以将它们组合在第二个选择项上?

2 个答案:

答案 0 :(得分:1)

是的,您可以GROUP BY所有非CASE列,并将MAX应用于每个CASE表达式列。

答案 1 :(得分:1)

结果集中还有查询中没有的其他列。但是,这应该可行:

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;