2013-02-26 60 views
3

我發現基本上使用不同的where子句計數的選擇語句。我的問題是,如何將結果合併到一個聲明中,以便這些計數可以成爲列?SQL嵌套查詢可能嗎?

  1. SELECT COUNT(*),如從表1 C1其中城市= 'NYC'
  2. SELECT COUNT(*),如從表1 C2其中城市= '波士頓'
  3. SELECT COUNT(*)作爲從C3表1,其中城市= '科幻'
+0

可能重複(http://stackoverflow.com/q/8788133/) – outis 2013-02-26 22:06:44

回答

5
SELECT 
    COUNT(CASE WHEN city = 'nyc' THEN 1 END) AS Nyc, 
    COUNT(CASE WHEN city = 'boston' THEN 1 END) AS Boston, 
    COUNT(CASE WHEN city = 'sf' THEN 1 END) AS Sf 
FROM table 
+0

謝謝邁克爾。如果where語句有多個條件,比如city ='nyc'和gender ='male',會怎麼樣? – Yang 2013-02-26 22:03:49

+0

如果您有多個條件,最好使用基於行的結果和group by。 – EkoostikMartin 2013-02-26 22:11:41

+1

@Yang如果你有多個條件,你可以將它們添加到你的'case' ...'當city ='nyc'AND gender ='male'THEN 1 END)AS nycMale' – 2013-02-26 22:15:55

2

使用sum()filtering only required cities

select sum(case when city = 'nyc' then 1 end) c1, 
     sum(case when city = 'boston' then 1 end) c2, 
     sum(case when city = 'sf' then 1 end) c3 
from table1 
where city in ('nyc','boston','sf') 
+0

Thanks,sum()工作 – Yang 2013-02-26 22:09:44

+0

沒問題,你可以添加更多的條件,例如(當城市='nyc'和性別='男性'然後1結束的情況下)等等...... – Kaf 2013-02-26 22:15:15

2
select count(CASE WHEN city = 'nyc' THEN 1 END) as c1, 
     count(CASE WHEN city = 'boston' THEN 1 END) as c2,  
     count(CASE WHEN city = 'sf' THEN 1 END) as c3 
from table1 

演示上SQLFiddle

而且在SQLServer2005的+,甲骨文可以使用PIVOT操作

SELECT * 
FROM table1 
PIVOT (
COUNT(city) FOR city IN ([nyc], [boston], [sf]) 
) p 

演示上SQLFiddle

+1

這個數據透視表在Oracle [demo]中幾乎是一樣的, (http://sqlfiddle.com/#!4/05497/13) – 2013-02-26 22:45:33

+0

@Conrad Frix感謝您的澄清和演示! – 2013-02-26 22:52:35

1

的完整性)

select 
    (select count(*) as c1 from table1 where city = 'nyc') as c1, 
    (select count(*) as c2 from table1 where city = 'boston') as c2, 
    (select count(*) as c3 from table1 where city = 'sf') as c3 
2

你可以給GROUP BY機會,

SELECT city, gender, count(*) 
WHERE gender = "male" 
GROUP BY city, gender; 
的[計數在MySQL表爲不同列的記錄取決於列的不同值]