SQL Distinct Group by

时间:2013-03-25 13:44:33

标签: sql select group-by

SQL:按国家/地区分组算,非常简单,但我迷路了 我有我的Table1

Country    | Optin    | 
--------------------------
USA        | 1        |
USA        | 1        |      
GERMANY    | 0        |      
USA        | 1        |          
GERMANY    | 1        |         
JAPON      | 1        |  

我想要返回此表,我只想按国家/地区计算optin part = 1

Country    | Optin    | 
--------------------------
USA        | 3        |
GERMANY    | 1        |
JAPON      | 1        |  


SELECT *
FROM Table1
WHERE Optin = 1
GROUP BY Country

2 个答案:

答案 0 :(得分:0)

  

我只想按国家/地区计算optin part = 1

COUNT使用SUM(或optin,因为所有GROUP BY country返回= 1):

SELECT Country, COUNT(optin) 
FROM table1
WHERE optin = 1
GROUP BY country;

SQL Fiddle Demo

答案 1 :(得分:0)

SELECT  Country, SUM(CASE WHEN Optin = 1 THEN 1 ELSE 0 END) totalOptin
FROM    TableName
GROUP   BY Country