【发布时间】:2016-04-28 15:01:16
【问题描述】:
我可以进行查询,以获取每月和每家商店从 18 岁到 24 岁进店的顾客数量。 我是这样做的:
select year, month, shop_id, count(birthday)
from customers
where birthday
BETWEEN '1992-01-01 00:00:00' AND '1998-01-01 00:00:00'
group by year, month, shop_id;
现在,我在同时对多个范围进行此查询时遇到问题。
我目前有这个数据库架构:
shop_id | birthday | year | month |
--------+----------+------+--------
567 | 1998-10-10 | 2014 | 10 |
567 | 1996-10-10 | 2014 | 10 |
567 | 1985-10-10 | 2014 | 10 |
234 | 1990-10-10 | 2014 | 10 |
123 | 1970-01-10 | 2014 | 10 |
123 | 1974-01-10 | 2014 | 11 |
我想得到这样的东西:
shop_id | year | month | 18 < age < 25 | 26 < age < 35
--------+------+-------+---------------+-------------
567 | 2014 | 10 | 2 | 1
234 | 2014 | 10 | 1 | 0
123 | 2014 | 10 | 0 | 0
在第一个查询中,它不管理一个商店没有客户的情况。没有怎么取0?
如何同时查询多个日期范围?
【问题讨论】:
-
在选择列表中有 case 表达式,每个年龄段都有一个。例如。
, count(case when ... then 1 end) as 18_age_25, count(case when ....
标签: sql postgresql date count date-range