Reputation: 747
I have table like:
Bike_orders
ID | model_id | order_date | male_or_female_bike
5 | 099 | 2014-04-08 | M
12 | 099 | 2014-04-08 | F
19 | 012 | 2014-02-12 | NULL
40 | 123 | 2014-04-08 | F
33 | 040 | 2014-04-08 | NULL
Where column 'male_or_female_bike':
M or NULL = male bike
F = female bike
(For now please ignore column 'model id' - it is just to inform that I need it to create join with another table)
Desirable result:
order_date | count_male | count_female
2014-04-08 | 2 | 2 |
2014-02-12 | 1 | 0 |
I would like to know: how many F/M bikes was sold on each day. Like I'd need to "divide" male_or_female_bike by date.
I could only figure ir out this way:
select id,
(
select male_or_female_bike
from bike_orders o2
where o2.male_or_female_bike = 1
and o2.id = o.id
) as F,
(
select male_or_female_bike
from bike_orders o3
where o3.id = o.id
and (male_or_female_bike = 0 or male_or_female_bike is null)
) as M
from bike_orders o
where /*some other condition here*/
GROUP BY date
But it is not effective. Does any dedicated MySQL exist for this purpose? Is there any other better / faster way ?
Upvotes: 0
Views: 195
Reputation: 33935
SELECT order_date
, COALESCE(SUM(COALESCE(gender,'M')='M'),0) M
, COALESCE(SUM(gender='F'),0) F
FROM my_table
GROUP
BY order_date;
Upvotes: 1
Reputation: 18737
You can simply do this:
SELECT order_date,
SUM(CASE WHEN male_or_female_bike IS NULL THEN 1 WHEN male_or_female_bike='M' THEN 1 ELSE 0 END) as MaleCount,
SUM(CASE WHEN male_or_female_bike ='F' THEN 1 ELSE 0 END) as FemaleCount
FROM Bike_orders
GROUP BY order_date
ORDER BY order_date DESC
Result:
ORDER_DATE MALECOUNT FEMALECOUNT
April, 08 2014 00:00:00+0000 2 2
February, 12 2014 00:00:00+0000 1 0
Upvotes: 2