[英]Snowflake SQL count distinct with window function
我有一個包含每周客戶和商店信息的數據集,
問題-我必須計算截至本周為止的最后 1、2、3、4、5、6 ..so 周內的獨特客戶總數等特征。
在 window function 上使用不同客戶列的計數時出現錯誤-
我嘗試使用 concat function 創建數組,但也沒有成功 - 感謝您的幫助!
SELECT STORE,WEEK,
count(distinct Customers) over (partition by STORE order by WEEK rows between 1 preceding and 1 preceding) as last_1_week_customers,
count(distinct Customers) over (partition by STORE order by WEEK rows between 2 preceding and 2 preceding) as last_2_week_customers
from TEST_TABLE
group by STORE,WEEK
錯誤 - SQL 編譯錯誤: distinct 不能與 window 框架或訂單一起使用。
我該如何解決這個錯誤?
輸入
CREATE TABLE TEST_TABLE (STORE STRING,WEEK STRING,Customers STRING);
INSERT INTO TEST_TABLE VALUES
('A','1','AA'),
('A','1','DD'),
('A','2','AA'),
('A','2','BB'),
('A','2','CC'),
('A','3','AA');
Output
嗯...我認為您根本不需要 window 函數...
首先,我們可以從一個簡單的分組開始:
select
store,
week,
count(distinct customers) as cnt
from
test_table
where
week >= [this week's number minus 5]
group by
store, week
這將產生一個簡單的表:
店鋪 | 星期 | cnt |
---|---|---|
一個 | 1 | 2 |
一個 | 2 | 3 |
一個 | 3 | 1 |
在這一點上,我會要求您考慮這是否已經足夠了。 可能您已經可以將這種格式的數據用於您需要的任何目的。 但如果不是,那么我們可以進一步修改它以獲得“樞軸”output。
在此查詢中,將${w}
替換為本周的數字:
select
store,
count(distinct case when week=${w} then customers else null end) as cnt_now,
count(distinct case when week=${w-1} then customers else null end) as cnt_minus_1,
count(distinct case when week=${w-2} then customers else null end) as cnt_minus_2,
count(distinct case when week=${w-3} then customers else null end) as cnt_minus_3,
count(distinct case when week=${w-4} then customers else null end) as cnt_minus_4,
count(distinct case when week=${w-5} then customers else null end) as cnt_minus_5
from
test_table
where
week >= {$w-5}
group by
store
請記住 - COUNT()
和COUNT(DISTINCT)
只計算NON-NULL值。
店鋪 | cnt_now | cnt_minus_1 | cnt_minus_2 | cnt_minus_3 | cnt_minus_4 | cnt_minus_5 |
---|---|---|---|---|---|---|
一個 | 1 | 2 | 3 | 4 | 5 | 6 |
乙 | 9 | 8 | 7 | 6 | 5 | 4 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.