我有一張像這樣的桌子
create table widgets
(
id primary key,
created_at timestamp,
-- other fields
)
現在我想要一個查詢,顯示created_at每天在多個時間范圍之間的小部件計數。例如,created_at00:00:00 到 11:59:59 之間的小部件計數以及 12:00:00 到 23:59:59 之間的計數。輸出看起來像這樣:
date | morning widgets (before noon) | evening widgets (after noon) |
---------------|-------------------------------|------------------------------|
2022-05-01 | ## | ## |
2022-05-02 | ## | ## |
2022-05-03 | ## | ## |
2022-05-04 | ## | ## |
... etc.
到目前為止,我發現我可以每天計算:
select created_at::date as created_at_date, count(*) as total
from widgets
where created_at::date >= '2022-05-01' -- where clause for illustration purposes only and not critical to the central question here
group by created_at::date
我正在學習視窗函式,特別是partition by. 我認為這將幫助我得到我想要的,但不確定。我該怎么做呢?
我更喜歡“標準 SQL”解決方案。如有必要,我在 postgres 上,可以使用任何特定于其 SQL 風格的東西。
uj5u.com熱心網友回復:
如果我理解正確,我們可以嘗試使用條件視窗函式來制作。
morning widgets (before noon): 00:00:00 至 11:59:59evening widgets (after noon): 12:00:00 至 23:59:59
CASE WHEN通過運算式將條件放入聚合函式中。
SELECT created_at::date,
COUNT(CASE WHEN created_at >= created_at::date AND created_at <= created_at::date INTERVAL '12 HOUR' THEN 1 END) ,
COUNT(CASE WHEN created_at >= created_at::date INTERVAL '12 HOUR' AND created_at <= created_at::date INTERVAL '1 DAY' THEN 1 END)
FROM widgets w
GROUP BY created_at::date
ORDER BY created_at::date
sqliddle
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475239.html
標籤:sql PostgreSQL 窗函数
