我有自行車租賃資料,我使用 postgresql 中的以下代碼按每天的使用次數對其進行分組:
SELECT date_trunc('day', rental_date) FROM rentalinfo;
SELECT COUNT(date_trunc('day', rental_date)) as counted_leads,
date_trunc('day', rental_date) as count_date
FROM rentalinfo
GROUP BY date_trunc('day', rental_date)
ORDER BY date_trunc('day', rental_date) ASC;
結果給出了一個名為 counted_leads 的列,其中包含每天的租金數量。我想查詢我可以分別提取和總結周末和作業日的租金數量。我試過平日:
SELECT SUM(counted_leads) AS sum_date WHERE count_date NOT IN ('2021-12-04',..)
但我收到一條錯誤訊息,提示“錯誤:在“SELECT”處或附近出現語法錯誤。
請問我該如何解決?
uj5u.com熱心網友回復:
在 where 子句中使用extract(dow ...)過濾所有作業日(或周末)行并計算它們:
select count(*) as weekdays
from rentalinfo
where extract(dow from rental_date) in (1, 2, 3, 4, 5)
或者使用條件聚合:
select count(case when extract(dow from rental_date) in (1, 2, 3, 4, 5) then 1 end) as weekdays
, count(case when extract(dow from rental_date) in (0, 6) then 1 end) as weekends
from rentalinfo
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475231.html
標籤:sql PostgreSQL 和 时间戳
上一篇:如果欄位匹配,則SQL查詢以獲取資料,如果不匹配則為null
下一篇:提高SQL查詢的運行時間
