This is probably super simple – but i am tearing my hair out.
database is using cPanel (MariaDB 10.1.28)
Heres the scenario
- 1 Table Called “WARNINGS”
-
1 column called “WARNING_REASON” (VARCHAR)
warning_reason contains various “reasons” -
1 column called “WARNING_LEVEL” (VARCHAR)
This contains either “VERBAL”, “LEVEL 1” or “LEVEL 2”
I need to output this data in php on a 5 column table
- Warning Reason
- Total number of rows in table grouped by warning_reason
- Total of rows that match “VERBAL” grouped by warning_reason
- Total of rows that match “LEVEL 1” grouped by warning_reason
- Total of rows that match “LEVEL 2” grouped by warning_reason
2
Answers
You can use subqueries to accomplish this:
You can use conditional aggregation:
This is shorter and probably faster than running multiple subselects.
Note that in MySQL boolean expression like
warning_level = 'VERBAL'
return either1
or0
(orNULL
ifwarning_level is NULL
).If you want a standard compliant query you can change the line to
or
or
since NULL is the default value for ELSE you can also skip it
The following also works in MySQL, but I’m not sure if other systems will evaluate it the same way: