如何将查询作为一行中的值编写?

时间:2012-06-06 07:42:57

标签: mysql sql phpmyadmin

我在MySQL上有两个表(使用phpMyAdmin),如下所示: 表1:

Country    Total Minutes
USA        100
USA        90
Canada     60
Mexico     80
UK         90
France     70
France     10
Germany    10

在表2中,我需要做的是:

Region           Total Minutes
North America    USA+USA+Canada+Mexico Mins
Europe           UK+France+France+Germany Mins

有没有办法让行成为查询的结果?

2 个答案:

答案 0 :(得分:3)

您需要表1中的区域列:

SELECT region, SUM(`Total Minutes`)
FROM timespent
GROUP BY region;

或单独的region <-> country表:

SELECT region, SUM(`Total Minutes`)
FROM myregions r
INNER JOIN timespent t USING (country)
GROUP BY r.region;

区域表如下所示:

region        | country
--------------+--------
North America | USA
North America | Mexico

如果您无法更改数据库中的任何内容,请查看Andomar的解决方案:)

答案 1 :(得分:2)

您可以将国家/地区转换为子查询中的区域。然后外部查询可以group by在区域:

select  Region
,       sum(TotalMinutes) as TotalMinutes
from    (
        select  case country
                when 'USA' then 'North America'
                when 'France' then 'Europe'
                end as Region
        ,       TotalMinutes
        from    YourTable
        ) as SubQueryAlias
group by
        Region
相关问题