POSTGRESQL - 分组查询的策略

时间:2013-09-06 04:45:02

标签: sql postgresql

我有这个问题:

SELECT 
 u.creationtime::date as date,
 d.driver_statuses_city_id as id,
 u.usersid as applied
FROM 
users u 
JOIN 
driver_status d 
ON 
u.usersid = d.driver_id
WHERE 
(u.role = 'partner' or u.role = 'driver')
AND d.driver_statuses_city_id in 
(SELECT id FROM driver_statuses_city
WHERE city_id in ({{city_ids}}))
and u.creationtime::date > '2013-09-01'

哪个输出:

date          id      applied
2013-09-03   1121     2443122
2013-09-03   1122     2737622
2013-09-03   1123     2754122
2013-09-03   1122     2733422
etc           etc       etc

我想按日期将每个ID组合在一起。所以我的输出看起来更像是:

date                id                count(applied)
2013-09-03          1121                  1
2013-09-03          1122                  2
2013-09-03          1123                  1

但我不确定如何最好地展示这些。我最倾向于使用某种“案例”功能吗?

1 个答案:

答案 0 :(得分:1)

我没有完整的表格结构,但根据我的结论,它应该是这样的:

SELECT 
 u.creationtime::date as date,
 d.driver_statuses_city_id as id,
 count(u.usersid) as applied
FROM 
users u 
JOIN 
driver_status d 
ON 
u.usersid = d.driver_id
WHERE 
(u.role = 'partner' or u.role = 'driver')
AND d.driver_statuses_city_id in 
(SELECT id FROM driver_statuses_city
WHERE city_id in ({{city_ids}}))
and u.creationtime::date > '2013-09-01'
group by date, id