2016-04-15 88 views
0

我有一個人口表,我想比較兩年的人口。在兩年的比較日期

我的表結構:
ID(自動遞增),式(男人,女人,小孩),人口(1〜10000),日期

我想運行兩個下查詢並顯示到一個表的結果:

QUERY1:

SELECT type,count(population) as count_of_year1 
FROM population 
where date between '2013-01-01' and '2013-01-24' 
GROUP BY type 

QUERY2:

SELECT type, count(population) as count_of_year2 
FROM population 
where date between '2014-01-01' and '2014-01-24' 
GROUP BY type 

我需要此結果:

|類型| 2013年人口| |人口在2014年

如何做到這一點?

回答

0

使用case表達式進行條件計數:

SELECT type, 
     count(case when date between '2013-01-01' and '2013-01-24' then population end) as count_of_year1, 
     count(case when date between '2014-01-01' and '2014-01-24' then population end) as count_of_year2 
FROM population 
GROUP BY type 

如果需要添加此where條款加快速度:

where date between '2013-01-01' and '2013-01-24' 
    or date between '2014-01-01' and '2014-01-24' 
+0

坦克你。我想添加欄以顯示2013年的人口總和。這可能嗎?如何在案例表達式中添加此條件 – vahid

+0

現在,當我再次閱讀您的問題時,我不太確定我是否已經回答了問題...以後可能會返回調整後的查詢!或者這是你要求的嗎? – jarlh

0

由於人口可以有1的值到10000,我承擔你想在這裏SUM()不是COUNT()。

我有各類單獨的表:

  • population_type - ID,標題
  • 人口 - ID,TYPE_ID(參考type.id),人口,日期

然後我更喜歡在這裏使用JOIN:

SELECT pt.title type, 
      COALESCE(y1.total_population,0) population_2013, 
      COALESCE(y2.total_population,0) population_2014 
     FROM population_type pt 
LEFT JOIN (
     SELECT type_id, 
       SUM(population) total_population, 
      FROM population 
     WHERE date >= '2013-01-01' 
      AND date < '2013-01-24' + INTERVAL 1 DAY   
     GROUP BY type 
      ) y1 
     ON y1.type_id = pt.id   
LEFT JOIN (
     SELECT type_id, 
       SUM(population) total_population, 
      FROM population 
     WHERE date >= '2014-01-01' 
      AND date < '2014-01-24' + INTERVAL 1 DAY   
     GROUP BY type 
      ) y2 
     ON y2.type_id = pt.id 

這樣你就只需要每次總結你所需要的東西並且查詢更加模塊化。