sql - Sum 特定列(按星期几)

我有自行车租赁数据,并使用 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 的列,其中包含每天的租金数量。我想查询我可以在哪里提取和 sum 分别在周末和工作日的租金数量。我试过平日:

SELECT SUM(counted_leads) AS sum_date WHERE count_date NOT IN ('2021-12-04',..)

但是我收到一条错误消息,提示“错误:在“SELECT”处或附近出现语法错误。

请问我该如何解决?

回答1

在 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

相似文章

随机推荐

最新文章