id model datetime driver distance
---|-----|------------|--------|---------
1 | S | 04/03/2009 | john | 399
2 | X | 04/03/2009 | juliet | 244
3 | 3 | 04/03/2009 | borat | 555
4 | 3 | 03/03/2009 | john | 300
5 | X | 03/03/2009 | juliet | 200
6 | X | 03/03/2009 | borat | 500
7 | S | 24/12/2008 | borat | 600
8 | X | 01/01/2009 | borat | 700
model all_trips driver distance
-----|------------|--------|---------
3 | 2 | borat | 555
X | 4 | borat | 1200
S | 2 | borat | 600
SELECT
model AS model, driver AS driver
SUM(distance) as total_distance
FROM my_table
WHERE driver = 'borat'
GROUP BY model
model driver total_distance
-----|--------|--------
3 | borat | 555
X | borat | 1200
S | borat | 600
我需要帮助才能获得all_trips
列,其中all_trips指的是每个模型未过滤的记录数(即没有过滤器WHERE driver = 'borat'
)
答案 0 :(得分:1)
你快到了。只需加入每个模型的计数。
select m.model,t.cnt as all_trips,m.distance,m.driver
from (SELECT model,driver,SUM(distance) as distance
FROM my_table
WHERE driver = 'borat'
GROUP BY model,driver) m
JOIN (select model,count(*) as cnt from my_table group by model) t on t.model=m.model