[英]SQL combine multiple records of one table into multiple columns of another table
I am working in SQL and have a destination table:我正在使用 SQL 并且有一个目标表:
Event ID (key) | Road | total count | motorcycles | cars | trucks | bus
And I have a record like table:我有一个类似表的记录:
[Event ID | mode of transport | count
1 | bus | 3
1 | cars | 20
1 | trucks | 2
1 | motorcycles | 5
2 | bus | 1
2 | cars | 12
2 | motorcycles | 1][1]
(combination of Event ID and mode of transport combination is unique) (Event ID和交通方式组合的组合是唯一的)
How do I combine the data from the second table into the first easily as result:我如何轻松地将第二个表中的数据合并到第一个表中:
Event ID (key) | Road | total count | motorcycles | cars | trucks | bus
1 | ... | ... | 5 | 20 | 2 | 3
2 | ... | ... | 1 | 12 | | 1
I am looking for a way that can incorporate the record data from the second table in one SQL structure / statement.我正在寻找一种可以将第二个表中的记录数据合并到一个 SQL 结构/语句中的方法。 Thank you!谢谢!
You can use conditional aggregation:您可以使用条件聚合:
select eventid, road,
sum(count) as total_count,
sum(case when mode = 'motorcycles' then count end) as cnt_motorcycles,
sum(case when mode = 'car' then count end) as cnt_car,
sum(case when mode = 'bus' then count end) as cnt_bus,
sum(case when mode = 'truck' then count end) as cnt_truck
from t
group by eventid, road;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.