2012-10-13 306 views
2

我已使用Google搜索,但沒有找到任何相關的信息。我有一個MySQL表是這樣的:MySQL查詢日期範圍

 
+++++++++++++++++++++++++++++++ 
| roomID | date | price | 
+++++++++++++++++++++++++++++++ 
| 1  | 2012-10-10 | 10 | 
| 1  | 2012-10-11 | 10 | 
| 1  | 2012-10-12 | 10 | 
| 1  | 2012-10-13 | 12 | 
| 2  | 2012-10-10 | 15 | 
| 2  | 2012-10-11 | 15 | 
| 2  | 2012-10-12 | 15 | 
| 2  | 2012-10-13 | 16 | 
| 2  | 2012-10-14 | 16 | 
| 2  | 2012-10-15 | 16 | 
+++++++++++++++++++++++++++++++

我需要根據價格和roomID得到時期:

 
++++++++++++++++++++++++++++++++++++++++++++ 
| roomID | from | till | price | 
++++++++++++++++++++++++++++++++++++++++++++ 
| 1 | 2012-10-10 | 2012-10-12 | 10 | 
| 1 | 2012-10-13 | 2012-10-13 | 12 | 
| 2 | 2012-10-10 | 2012-10-12 | 15 | 
| 2 | 2012-10-13 | 2012-10-15 | 16 | 
++++++++++++++++++++++++++++++++++++++++++++

謝謝!

回答

6
select roomid, 
     min(date) as from, 
     max(date) as till, 
     price 
from periods 
group by price 
order by price 
4

您可以嘗試使用下面的查詢:

SELECT roomid, MIN(date) AS `from`, MAX(date) AS `till`, price 
FROM tableName 
GROUP BY price 
ORDER BY price 
+0

+1使用反引號(')了作爲列/表達式名稱的關鍵詞。 –