选择总值及其子集

时间:2012-03-19 15:50:29

标签: mysql

我有一张表格,其中包含不同国家/地区的不同值,例如:

id| country  | value
===================
1 | Argelia  | 8
2 | USA      | 10
1 | China    | 12
1 | Italy    | 13

我只对一个国家和总数感兴趣,但我无法提出单一查询来执行此操作。 id 1的此查询结果为:

id| value_in_Italy | total
==========================
1 | 13              | 33

如您所见,我获得了意大利的价值和总价值。对于类似的表,什么样的查询会产生如上所述的行?

1 个答案:

答案 0 :(得分:2)

以下是您需要的查询:

select id,SUM(IF(country='Italy',value,0)) italy_value,SUM(value) id_values
from countrydata where id = 1;

以下是您的示例数据:

drop database if exists luqita;
create database luqita;
use luqita
create table countrydata
(
    id int not null,
    country varchar(32),
    value int not null
);
insert into countrydata values
(1,'Argelia',  8 ),(2,'USA'    , 10 ),
(1,'China'  , 12 ),(1,'Italy'  , 13 );
select * from countrydata;

以下是您加载的示例数据:

mysql> drop database if exists luqita;
Query OK, 1 row affected (0.03 sec)

mysql> create database luqita;
Query OK, 1 row affected (0.02 sec)

mysql> use luqita
Database changed
mysql> create table countrydata
    -> (
    ->     id int not null,
    ->     country varchar(32),
    ->     value int not null
    -> );
Query OK, 0 rows affected (0.12 sec)

mysql> insert into countrydata values
    -> (1,'Argelia',  8 ),(2,'USA'    , 10 ),
    -> (1,'China'  , 12 ),(1,'Italy'  , 13 );
Query OK, 4 rows affected (0.05 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from countrydata;
+----+---------+-------+
| id | country | value |
+----+---------+-------+
|  1 | Argelia |     8 |
|  2 | USA     |    10 |
|  1 | China   |    12 |
|  1 | Italy   |    13 |
+----+---------+-------+
4 rows in set (0.00 sec)   

mysql>

以下是执行的建议查询:

mysql> select id,SUM(IF(country='Italy',value,0)) italy_value,SUM(value) id_values
    -> from countrydata where id = 1;
+----+-------------+-----------+
| id | italy_value | id_values |
+----+-------------+-----------+
|  1 |          13 |        33 |
+----+-------------+-----------+
1 row in set (0.00 sec)

mysql>

现在,如果您想同时针对所有行运行此查询,请尝试以下全包查询:

select
    B.id,
    SUM(IF(A.country=B.country,B.value,0)) country_value,
    SUM(IF(A.id=B.id,A.value,0)) id_values
from
    countrydata A,
    countrydata B
group by B.country;

以下是全包查询执行

mysql> select
    ->     B.id,
    ->     SUM(IF(A.country=B.country,B.value,0)) country_value,
    ->     SUM(IF(A.id=B.id,A.value,0)) id_values
    -> from
    ->     countrydata A,
    ->     countrydata B
    -> group by B.country;
+----+---------------+-----------+
| id | country_value | id_values |
+----+---------------+-----------+
|  1 |             8 |        33 |
|  1 |            12 |        33 |
|  1 |            13 |        33 |
|  2 |            10 |        10 |
+----+---------------+-----------+
4 rows in set (0.00 sec)

mysql>

试一试!!!