一周中的一天的特定列的总和

发布于 2025-01-29 01:23:40 字数 591 浏览 4 评论 0 原文

我有自行车租赁数据,并且使用以下代码在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”或附近的语法错误。

请问该如何解决?

I have bicycle rental data and I have grouped it by number of uses per day using the following code in 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;

The result gives a column called counted_leads which contains number of rentals per day. I want to make a query where I can extract and sum the number of rentals on weekends and weekdays separately. I tried for weekdays:

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

But it I get an error saying "ERROR: syntax error at or near "SELECT".

How can I fix it, please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

獨角戲 2025-02-05 01:23:41

在Where子句中使用提取(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

Use extract(dow ...) in the where clause to filter all weekday (or weekend) rows and count them:

select count(*) as weekdays
from rentalinfo
where extract(dow from rental_date) in (1, 2, 3, 4, 5)

Or use conditional aggregation:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文