我想加入两个表格,并显示年份(日期),总数和车辆类型。 如果year和vehicle_type相同则应合并其总数。这是我的疑问。
select extract(year from ra.roadAccident_date) as 'Year',
c.casualties_death + c.casualties_serious + c.casualties_minor as 'Total',
ra.vehicle_type as 'Types of Vehicle'
from casualties c
join roadAccidents ra
on (c.accident_id = ra.accident_id)
我的结果是
Year Total Types of Vehicle
2014 6 taxi
2014 9 lorry
2014 3 bus
2014 16 bus
2015 7 taxi
2015 5 lorry
2015 7 lorry
2016 2 bus
2016 5 lorry
2016 9 bus
对于2014年,我希望将车型总线合并为一行,总共19行。我尝试了多种group by
方法,但找不到我想要的方法。
答案 0 :(得分:1)
我不明白为什么一个简单的GROUP BY
不起作用:
SELECT
EXTRACT(YEAR FROM ra.roadAccident_date) AS 'Year',
SUM(c.casualties_death + c.casualties_serious + c.casualties_minor) AS 'Total',
ra.vehicle_type AS 'Types of Vehicle'
FROM casualties c
INNER JOIN roadAccidents ra
USING accident_id
GROUP BY ra.vehicle_type, YEAR(ra.roadAccident_date)
答案 1 :(得分:0)
将整个事物(作为子查询)用分组外部包裹,如
Select yr,vtype, sum(total) as tot from
(
select extract(year from ra.roadAccident_date) as yr,
c.casualties_death +c.casualties_serious+c.casualties_minor as total
ra.vehicle_type as vtype
from casualties c
join roadAccidents ra on (c.accident_id = ra.accident_id)
) stats group by yr, vtype