Goo*_*bot 3 mysql select update group-by
我想计算两列,但需要在一行中获取第一列的结果。
SELECT country, COUNT(*)
FROM table1
GROUP BY country, type
Run Code Online (Sandbox Code Playgroud)
这个查询给了我
country type COUNT(*)
Canada first 22
Canada second 42
Canada third 15
Australia second 23
Australia third 18
Run Code Online (Sandbox Code Playgroud)
但我需要得到
country type_first type_second type_third
Canada 22 42 15
Australia 23 18 0
Run Code Online (Sandbox Code Playgroud)
因为我想用这些值更新另一个表,并且使用这个行结构,我可以根据上述查询逐行更新国家/地区表。
UPDATE country SET first=x, second=x, third=x
Run Code Online (Sandbox Code Playgroud)
注意:type
列ENUM
具有预定义的值。
看起来你想要这样的东西:
SELECT country
, sum(case when type = 'first' then 1 else 0 end) as type_first
, sum(case when type = 'second' then 1 else 0 end) as type_second
, sum(case when type = 'third' then 1 else 0 end) as type_third
FROM table1
GROUP BY country
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10833 次 |
最近记录: |