親愛的社區!
我對 PRESTO 上的 SQL 查詢有點迷茫。本質上,我對以下列有一個看法:
分公司| 年月(varchar)| 出售 [... 和其他]
德國 | 2022-06 | 123q1239
我需要做的很簡單,我需要創建一個這樣的表:
分公司| 年月 | count(sellid) 實際月份 | 計數(賣出)上個月
除其他外,我嘗試了以下操作,但不幸的是我仍然遇到錯誤。
SELECT branch, year_month, count(sellid)as active_locs,
CASE
WHEN TO_DATE(year_month, '%Y-%m') = date_format(TO_DATE(year_month, '%Y-%m') - interval '1' month, '%Y-%m') THEN count(sellid) END as locs_LM
FROM table
GROUP BY branch, year_month
這是我得到的確切錯誤:
執行SQL命令時出錯:SELECT branch, year_month, count(sellid)as active_locs, CASE WHEN TO_DATE(year_month, '%Y-%m') = date_format(TO_DATE(year_month, '%Y-%m') - 采訪...
查詢失敗 (#20220628_093246_00650_e4kcc):第 3:39 行:“=”不能應用于日期,varchar [DB Errorcode=1] 1 陳述句失敗。
有人可以幫幫我嗎?
提前致謝
uj5u.com熱心網友回復:
date_format回傳 varchar 而TO_DATE回傳日期,所以你有型別不匹配。您還需要使用date_parse提供的格式:
SELECT branch, year_month, count(sellid)as active_locs,
CASE
WHEN year_month = date_format(date_parse(year_month, '%Y-%m') - interval '1' month, '%Y-%m') THEN count(sellid) END as locs_LM
FROM dataset
GROUP BY branch, year_month
這將使查詢執行,但不會使其正確。為了使它正確,您可以使用Windows 函式和子查詢:
--sample data
WITH dataset(branch, year_month, sellid) AS (
VALUES ('Germany', '2022-06', '123q1239'),
('Germany', '2022-05', '123q1239')
)
-- sample query
SELECT branch,
date_format(year_month, '%Y-%m') year_month,
active_locs,
if( -- if previous record is for previous month use previous active_locs
lag(year_month) over (partition by branch order by year_month)
= year_month - interval '1' month,
lag(active_locs) over (partition by branch order by year_month),
0
) locs_LM
FROM (
SELECT branch,
date_parse(year_month, '%Y-%m') year_month,
count(sellid) as active_locs
FROM dataset
GROUP BY 1,
2
)
輸出:
| 分支 | 年月 | active_locs | locs_LM |
|---|---|---|---|
| 德國 | 2022-05 | 1 | 0 |
| 德國 | 2022-06 | 1 | 1 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496821.html
上一篇:在Excel中重復日期序列
