简体   繁体   English

MySQL的:从结果中的一列中选择值到多列

[英]MySql: select values from one column into multiple columns in the result


I have table like: 我有这样的表:

Bike_orders 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' : 其中“ male_or_female_bike”列:
M or NULL = male bike M或NULL =男性自行车
F = female bike F =女自行车

(For now please ignore column 'model id' - it is just to inform that I need it to create join with another table) (现在请忽略列“模型ID”-只是为了通知我需要它来创建与另一个表的联接)


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. 我想知道:每天售出多少辆F / M自行车。 Like I'd need to "divide" male_or_female_bike by date. 就像我需要按日期“划分” male_or_female_bike。

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? 为此目的是否存在专用的MySQL? Is there any other better / faster way ? 还有其他更好/更快的方法吗?

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

Fiddle Demo 小提琴演示

SELECT order_date
     , COALESCE(SUM(COALESCE(gender,'M')='M'),0) M
     , COALESCE(SUM(gender='F'),0) F 
  FROM my_table 
 GROUP 
    BY order_date;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM