The table below is a subset of a table from a db I have access to:
CREATE TABLE trips(trip_id INT, foot BOOLEAN, bike BOOLEAN, bus BOOLEAN,
car BOOLEAN, metro BOOLEAN, motorcycle BOOLEAN, train BOOLEAN,
other BOOLEAN)
-- sample values
INSERT INTO trips (trip_id, foot, bike, bus, car, metro,
motorcycle, train, other)
VALUES(19,true,false,false,false,false,false,false,false),
(20,false,false,false,false,false,false,false,false),
(56,true,false,true,false,false,false,false,false),
(65,true,false,false,true,false,false,false,false),
(77,false,false,false,true,false,false,false,false)
Then for example, I want to produce the following statistics above mode of trip in the table.
- number trips by foot only
- number of trips by bus only
- number of trips by car only etc.., then
- number of trips by foot AND car
- trips by foot AND bus
- total trips for which all modes are FALSE.
I produce this db<>fiddle, but not sure how to filter this stats.
3
Answers
Do logic operation
fiddle
You can construct your queries following the template below
Foot only
Foot + car only
The same in a single query using a conditional aggregation
Normalize your data by flipping it over to
jsonb
, and one query can get you all mixes of modes:fiddle