0

我正在使用以下 SQL(与两个类似查询的联合):

SELECT
    distinct a.source,
    a.p_id,
    a.name,
    b.prod_count,
    b.prod_amt,
    'Def' as prod_type
FROM
    dwh.attribution_product_count a
        LEFT OUTER JOIN
        (
SELECT
    distinct source,
    p_id,
    name,
    sum(acct_count) as prod_count,
    sum(acct_amt) as prod_amt
FROM
    dwh.prod_count
WHERE
    month = 3 AND
    default_banner_flag = 0 AND
    loan_flag = 3
GROUP BY
    source,
    name,
    p_id ) as b
        ON
        a.p_id = b.p_id
UNION
SELECT
    distinct a.source,
    a.p_id,
    a.name,
    b.prod_count,
    b.prod_amt,
    'Other' as prod_type
FROM
    dwh.attribution_product_count a
        LEFT OUTER JOIN
        (
SELECT
    distinct source,
    p_id,
    name,
    sum(acct_count) as prod_count,
    sum(acct_amt) as prod_amt
FROM
    dwh.prod_count
WHERE
    month = 3 AND
    default_banner_flag = 1 AND
    loan_flag = 3
GROUP BY
    source,
    name,
    p_id
ORDER BY
    name ) as b
        ON
        a.p_id = b.p_id

我得到的输出如下所示:

在此处输入图像描述 本质上,因为 FakeName #2 有一行显示实际数字(非空),我只希望 FakeName #2 出现。这意味着我还想要 FakeName #2 的空行。但是,由于 FakeName #1 和 #3 有 2 个空行,我不需要它们显示。什么类型的 SQL 命令(或对我的查询进行编辑)可以完成此操作?

4

1 回答 1

1

UNION首先,如果我正确阅读了您的查询,您可以使用CASEand消除对 a 的需要IN。你也有几个 bogusDISTINCT在那里(因为你GROUP BY无论如何都在使用)。这给出了:

SELECT DISTINCT
    a.source,
    a.p_id,
    a.name,
    b.prod_count,
    b.prod_amt,
    Case When default_banner_flag = 0 Then 'Def' Else 'Other' End as prod_type
FROM
    dwh.attribution_product_count a
LEFT OUTER JOIN
    (
    SELECT
        source,
        p_id,
        name,
        default_banner_flag,
        sum(acct_count) as prod_count,
        sum(acct_amt) as prod_amt
    FROM
        dwh.prod_count
    WHERE
        month = 3 AND
        default_banner_flag in (0, 1) AND
        loan_flag = 3
    GROUP BY
        source,
        name,
        p_id,
        default_banner_flag
) as b
ON
a.p_id = b.p_id

但是,您真正想要的是有关p_id在 中至少有一行的 s 的信息dwh.prod_count,因此我认为您可以更改整个查询以将其用作子选择:

SELECT
    a.source,
    a.p_id,
    a.name,
    sum(acct_count) as prod_count,
    sum(acct_amt) as prod_amt,
    Case When default_banner_flag = 0 Then 'Def' Else 'Other' End as prod_type
FROM
    dwh.attribution_product_count a
LEFT OUTER JOIN
    dwh.prod_count b
    On a.p_id = b.p_id
INNER JOIN
    (
    SELECT DISTINCT
        p_id
    FROM
        dwh.prod_count
    WHERE
        month = 3 AND
        default_banner_flag in (0, 1) AND
        loan_flag = 3
    ) as c
    ON a.p_id = c.p_id
WHERE
    month = 3 AND
    default_banner_flag in (0, 1) AND
    loan_flag = 3

(您也可以将其重写为 aWHERE p_id IN ( sub-select )或稍作WHERE EXISTS ( ... )修改,但这似乎是最容易演示的版本。)

请注意,我实际上没有测试任何这些查询,但我认为它们在逻辑上是合理的。

于 2013-04-24T20:30:49.453 回答