2012-03-19 36 views
1

我有一個表,在不同的國家不同的值,例如:選擇總價值,以及它的一個子集

 
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 

正如你所看到的,我獲得了意大利的價值和總價值。什麼樣的查詢會產生像上面那樣的類似表的行?

回答

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> 

這裏是提出查詢執行:

現在

,如果你想運行鍼對在同一時間的所有行該查詢,試試這個包羅萬象的查詢:

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> 

試一試 !!!

+0

謝謝!我也提出了一個類似的問題,但用數值(*)而不是總值...你可以看看嗎? :) http://stackoverflow.com/questions/9775328/counting-with-conditions – luqita 2012-03-19 17:59:04