2011-11-16 61 views
2

有沒有辦法將兩個日期之間的記錄分組?MySQL集團之間的日期

例如,我的表有看起來像這樣的記錄:

rid  stamp     uid 
25  2005-07-05 14:10:29  25 
1175 2005-08-12 15:47:35  29 
290  2005-11-22 16:38:53  42 
30  2005-12-01 10:48:12  47 
30  2006-01-02 17:34:28  52 
30  2006-02-06 22:11:35  57 
30  2006-04-17 15:10:19  59 
1195 2006-05-08 21:55:56  62 
100  2006-06-30 15:51:04  94 
45  2006-07-03 21:14:37  24 

我想寫一個查詢,將在今年的February - AugustSeptember - January之間之間返回記錄計數,所以我回來的是:

July 2005 - January 2006:  3 
February 2006 - August 2006: 5 

回答

6

您可以在任何-almost-組要。如果您可以在列中顯示某些內容以顯示您想要的內容,則可以對其進行分組。因此,對於只有兩個時期你可以簡單地組上,如果:

SELECT * FROM table 
GROUP BY if(stamp between "2005-07-01" and "2006-02-01", 0, 1) 

如果您需要的時間更長的時間(多年)範圍過來,你可以使用PERIOD_DIFF來區分:

SELECT * FROM table 
GROUP BY floor(period_diff(DATE_FORMAT(stamp, "%Y%m"), "200507")/6) 

它會爲您提供在日期和年月格式的開始期間之間傳遞的6個月的塊數。

0

如果只有一個組,那麼你可以使用「group by with having clause」。我不認爲有一種語法可以在一個語句中指定多個不同的分組,然後將它們分開。這是最簡單的替代解決方案,我能想到的,將工作:

select "July 2005 - January 2006" AS "Date", count(date) as "results" 
from MYTABLE 
where date >= '2005-07-01' AND date <= '2006-01-31' 

union 

select "February 2006 - August 2006" AS "Date", count(date) as "results" 
from MYTABLE 
where date >= '2006-02-01' AND date <= '2006-08-31'; 
2

在其他人的輕微組合中...... 您可以擴展特定範圍的案例結構。團隊尊重「序號」第1列的位置,因此您不必在group by子句中複製相同的案例條件。此外,由於它會按字母順序排列結果,因此我在Order中輸入了相同的上下文。您可以通過任何您想要的順序進行訂購......即使您希望首先列出當前最新的日期活動,也可以相反。

SELECT 
     case when stamp between "2005-07-01" and "2006-02-01" 
       then "July 2005 - January 2006 " 
      when stamp between "2006-02-01" and "2006-08-01" 
       then "February 2006 - August 2006" 
      else "After August 2006   " 
     end as GroupColumn, 
     count(*) as TotalPerGroup 
    from 
     table 
    where 
     date >= '2005-07-01' 
    group by 
     1 
    order by 
     case when stamp between "2005-07-01" and "2006-02-01" 
       then 1 
      when stamp between "2006-02-01" and "2006-08-01" 
       then 2 
      else 3 
     end 
+0

非常感謝。這真的很有幫助。 –