具有不同值的情况

问题描述 投票:0回答:1

我需要计算每月有多少不同的客户访问过 tp.places,我尝试了三种不同的解决方案,但没有成功。我错过了什么?

SELECT
    DISTINCT tp.place,
    tp.brand,
    SUM (CASE WHEN kr.calendar_key BETWEEN '2024-01-01' AND '2024-01-31' THEN 1 END) as 1st,
    SUM (CASE WHEN kr.calendar_key BETWEEN '2024-02-01' AND '2024-02-29' THEN DISTINCT kr.customer_key END) as 2nd
    SUM (CASE WHEN kr.calendar_key BETWEEN '2024-03-01' AND '2024-03-31' THEN COUNT(DISTINCT kr.customer_key) END) as 3rd,
FROM
    orders.f_receipts kr
    INNER JOIN dim.d_place_of_business tp ON tp.business_key = kr.business_key
WHERE
    ...

我尝试了三种不同的解决方案,希望是这样的:

Place   Jan   Feb   March
nr1     1150  900   1300
nr2     800   990   700
etc.

编辑代码以使其看起来更具可读性。也是所需的输出。

sql count amazon-redshift case distinct
1个回答
1
投票

不要使用

SUM
,当您想要计算不同客户时使用
COUNT(DISTINCT)

SELECT
    tp.place,
    tp.brand,
    COUNT (DISTINCT CASE WHEN kr.calendar_key BETWEEN '2024-01-01' AND '2024-01-31' THEN kr.customer_key END) as january,
    COUNT (DISTINCT CASE WHEN kr.calendar_key BETWEEN '2024-02-01' AND '2024-02-29' THEN kr.customer_key END) as february,
    COUNT (DISTINCT CASE WHEN kr.calendar_key BETWEEN '2024-03-01' AND '2024-03-31' THEN kr.customer_key END) as march,
    ...
FROM
    orders.f_receipts kr
    INNER JOIN dim.d_place_of_business tp ON tp.business_key = kr.business_key
WHERE
    ...
GROUP BY tp.place, tp.brand
ORDER BY tp.place, tp.brand;
© www.soinside.com 2019 - 2024. All rights reserved.