suppose I have
SELECT * FROM table t
GROUP BY j
HAVING condition_one OR condition_two OR condition_three
how can I modify the query such that it returns the COUNT of how many rows satisfied the three different conditions in having clause
so ideally the output would have something like:
condition_one: 100
condition_two: 200
condition_three: 300
whereby there are 100 items satisfying condition_one, 200 satisfying condition_two etc
If you use a
havingclause you will actually loose those records. So you can’t use ahavingclause. Apart from that, if you useORs, then you won’t have which condition resulted intrue.So, what you should use is a derived table that holds all grouped values. Once you have that, query that table to get the counts of each of them. However, that solution will give you three columns instead of three rows. Let’s go for that one that is the easier one:
Note that
condition_oneis really a condition, such asage = 23, but conditions in MySQL return0forfalseand1fortrueso you can actuallySUMconditions.Now, if you want to have them in rows, that’s a little bit more complicated because you’ll have to
UNIONeach value independently:Or at least, that’s the best way I can think of right now. Hope this helps!