I have the following table, lets call this table_a:
Zone | vehicle_name | vehicle_status |
---|---|---|
A | BusA1 | Start |
A | BusA2 | Start |
A | BusA3 | Stopped |
B | BoatB1 | Ready |
B | BoatB2 | Stopped |
B | BoatB3 | Start |
C | CarC1 | Ready |
C | CarC2 | Ready |
C | CarC3 | Stopped |
I would like to create a new table from the table_a :
Zone | no_of_vehicle | no_of_start | no_of_ready | no_of_stopped |
---|---|---|---|---|
A | 3 | 2 | 0 | 1 |
B | 3 | 1 | 1 | 1 |
C | 3 | 0 | 2 | 1 |
What would be the most efficient way to this?
E.g.
SELECT DISTINCT(ZONE) AS ZONE,
SUM(IF ZONE = 'A' THEN ... IF ZONE = 'B' THEN ...
FROM table_a
2
Answers
This single SQL query achieves the desired result using conditional aggregation and grouping by the ‘Zone’.