sql—具有空值和不同值的组行

4uqofj5v  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(286)

我试图对最后一列(leavedays)求和,并需要通过将所有列分组来将输出放在一行中,但我无法在此处对行进行分组,从而得到相同的未分组结果。谢谢!

我需要输出为:

YEAR   MONTHID   MONTH   C10 C11 C12 C13 C14 C15 C16 C17 C18 C19 C20 C21 C22 LEAVEDAYS

2020     6        JUNE    P   P   P   P   H   P   P   P   P   A   P   H   A    4
ldxq2e6h

ldxq2e6h1#

如果在c10到c22中发现了除p以外的其他字符,则将该其他字符带入结果中。
我想你可以用 maxkeep 条款如下:

SELECT
    YEAR, MONTHID, MONTH,
    MAX(C10) KEEP(DENSE_RANK LAST ORDER BY CASE WHEN C10='P' THEN 1 ELSE 2 END) AS C10,
    ...,
    MAX(C22) KEEP(DENSE_RANK LAST ORDER BY CASE WHEN C22='P' THEN 1 ELSE 2 END) AS C22,
    SUM(LEAVEDAYS) AS LEAVEDAYS
FROM your_table
GROUP BY
    YEAR, MONTHID, MONTH;

或者可以使用条件聚合,如下所示:

SELECT
    YEAR, MONTHID, MONTH,
    COALESCE(MAX(CASE WHEN C10<>'P' THEN C10 END),'P') AS C10,
    ...,
    COALESCE(MAX(CASE WHEN C22<>'P' THEN C22 END),'P') AS C22,
    SUM(LEAVEDAYS) AS LEAVEDAYS
FROM your_table
GROUP BY
    YEAR, MONTHID, MONTH;
xtfmy6hx

xtfmy6hx2#

按年度和月份汇总,并使用 COALESCE 显示 P 如果给定列没有非 NULL 价值:

SELECT
    YEAR,
    MONTHID,
    MONTH,
    COALESCE(MAX(C10), 'P') AS C10,
    COALESCE(MAX(C11), 'P') AS C11,
    ...,
    COALESCE(MAX(C22), 'P') AS C22,
    SUM(LEAVEDAYS) AS LEAVEDAYS
FROM yourTable
GROUP BY
    YEAR,
    MONTHID,
    MONTH;
gojuced7

gojuced73#

我理解的逻辑是,您只需要在每列中指定最小值:

SELECT YEAR, MONTHID, MONTH,
       MIN(C10) AS C10,
       ...,
       MIN(C22) AS C22,
       SUM(LEAVEDAYS) AS LEAVEDAYS
FROM t
GROUP BY YEAR, MONTHID, MONTH;

相关问题