SQL Group By表达式返回相同的行数

时间:2018-07-13 00:20:45

标签: sql

我无法在联合查询中按表达式返回分组中的相同行。我当前使用的SQL返回以下结果 Current results 我想在2个表中显示相等的行数,因此即使数量为零,我也需要返回一行。 Proposed results

我的SQL当前看起来像这样

    SELECT
    'A' AS Code,
    'Internal Equipment' AS Description,
    'Project A' AS Project,
    Revision,
    'ME' AS Customer,
    Discipline,
    SUM(Amount)
FROM
    Table B
WHERE
    (
        Project = @Project
    )
AND (
        Revision = @Revision
    )
AND Amount > 0
AND RoleCode NOT LIKE 'AAA%'
GROUP BY
    Project,
    Revision,
    Customer,
    Discipline
UNION ALL
SELECT
    'B' AS Code,
    'External Equipment' AS Description,
    'Project A' AS Project,
    Revision,
    'ME' AS Customer,
    Discipline,
    SUM(Amount)
FROM
    Table B
WHERE
    (
        Project = @Project
    )
AND (
        Revision = @Revision
    )
AND Amount > 0
AND RoleCode LIKE 'AAA%'
GROUP BY
    Project,
    Revision,
    Customer,
    Discipline
UNION ALL
SELECT
    'C' AS Code,
    'Labour' AS Description,
    'Project A' AS Project,
    Revision,
    'ME' AS Customer,
    Discipline,
    SUM(Amount)
FROM
    Table A
WHERE
    (
        Project = @Project
    )
AND (
        Revision = @Revision
    )
GROUP BY
    Project,
    Revision,
    Customer,
    Discipline
UNION ALL
SELECT
    'D' AS Code,
    'Travel & Accomodation' AS Description,
    'Project A' AS Project,
    Revision,
    'ME' AS Customer,
    Discipline,
    SUM(Amount).
FROM
    Table B
WHERE
    (
        Project = @Project
    )
AND (
        Revision = @Revision
    )
AND Amount > 0
AND RoleCode IN('BBB', 'CCC', 'DDD')
GROUP BY
    Project,
    Revision,
    Customer,
    Discipline

有人可以帮忙吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

有几种方法取决于您使用的数据库。我可能会按照以下方式进行处理。

with CODES AS
(
SELECT
'A' AS Code, 'Internal Equipment' AS Description
UNION ALL
'B' AS Code, 'External Equipment' AS Description
),
DATA AS
(
...Your SQL HERE (without description)
)
SELECT * from Codes left outer join DATA on (Codes.Code=Data.Code)
ORDER BY CODES.Code

您必须决定如何处理缺失的值NULLCOALESCE可能是在此处使用的功能。

另外,您的问题是SELECT / UNION而不是GROUP BY!