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