MYSQL使用一个命令组合两个GROUP BY结果

时间:2014-10-16 03:51:35

标签: mysql

例如,我的水果来自不同的国家,并且有不同的品牌(注意国家和品牌是独立的。)

+-------+-------+---------+-------+
| name  | stock | Country | brand |
+-------+-------+---------+-------+
| apple |    40 | USA     | Sun   |
| apple |    38 | UK      | Sun   |
| apple |    33 | CN      | Green |
| apple |    29 | UK      | Air   |
| apple |    15 | USA     | Green |
+-------+-------+---------+-------+

通常如果我们使用此命令

SELECT name, Country, sum(stock)
FROM table
GROUP BY Country

它将给出以下结果

+-------+---------+------------+
| name  | Country | sum(stock) |
+-------+---------+------------+
| apple | CN      |         33 |
| apple | UK      |         67 |
| apple | USA     |         55 |
+-------+---------+------------+

但我想要的是......

+-------+----------+-------+
| name  | category | stock |
+-------+----------+-------+
| apple | USA      |    55 |
| apple | UK       |    67 |
| apple | CN       |    33 |
| apple | Sun      |    78 |
| apple | Green    |    48 |
| apple | Air      |    29 |
+-------+----------+-------+

对于某些结果,该命令必须是一步命令,这意味着只有一个命令才能直接输出上述结果一次。

2 个答案:

答案 0 :(得分:0)

尝试阅读工会或离开加入

我认为你需要制作

SELECT name, Country as category, sum(stock)
into #temptable1 FROM table 
GROUP BY Country

SELECT name, brand as category, sum(stock)
into #temptable2 FROM table 
GROUP BY brand

然后将两个临时表连接在一起 这可以使用存储过程来完成

或简单地直接联合而不制作临时表

SELECT name, Country as category, sum(stock)
into #temptable1 FROM table 
GROUP BY Country
UNION
SELECT name, brand as category, sum(stock)
into #temptable2 FROM table 
GROUP BY brand

答案 1 :(得分:0)

我建议使用子查询来执行此操作:

select name, category, sum(stock)
from (select name, brand as category, stock, 1 as ordering
      from table
      union all
      select name, country, stock, 0 ordering
      from table
     ) t
group by name, category, ordering
order by ordering, name;

请注意使用ordering列确保结果的显示顺序与所需结果的顺序相同。此外,在brandcountry具有相同名称的情况下,这将保留两行。如果您希望将ordering合并,则可以从group by中移除{{1}}。