2014-11-14 49 views
1

在MySQL或MSSQL中,我需要生成一個結果集,該結果集將返回最近三個月按月份分組的qheader。所以我有questionsec表模式生成過去幾個月並加入無關數據

+-----------+ 
|questionsec| 
+-----------+ 
|qid (PK) | 
|qheader | 
+-----------+ 

(select * from questionsec) 

我得到:

+-------+------+ 
|qid| qheader | 
+---|----------+ 
| 1 | QH1  | 
| 2 | QH2  | 
+---+----------+ 

什麼是我需要編寫生成以下結果集查詢:

+-------+---------+ 
|month | qheader | 
+-------|---------+ 
|2014-09| QH1  | 
|2014-09| QH2  | 
|2014-10| QH1  | 
|2014-10| QH2  | 
|2014-11| QH1  | 
|2014-11| QH2  | 
+-------+---------+ 

我知道以下情形將產生(在MySQL)過去三個月,但不知道如何加入到每個月份行每qheaderquestionsec

SELECT DATE_FORMAT(now()- INTERVAL 1 MONTH,'%Y-%m') as month 
UNION ALL SELECT DATE_FORMAT(now()- INTERVAL 2 MONTH,'%Y-%m') 
UNION ALL SELECT DATE_FORMAT(now()- INTERVAL 3 MONTH,'%Y-%m') 
+0

您的解決方案中會更容易,更靈活的使用[數字表](https://www.simple-talk.com/sql/database-administration/creative-solutions-by-using-a-number-table/)。如果您不確定如何解決您的問題,請閱讀並提出任何問題。 – Mike 2014-11-14 23:45:19

+0

你有沒有日期欄? – lookslikeanevo 2014-11-14 23:46:59

回答

1
CREATE TABLE questionsec(qid INT NOT NULL,qheader CHAR(3)); 

INSERT INTO questionsec VALUES (1,'QH1'),(2,'QH2'); 

SELECT qheader,month FROM questionsec x JOIN (SELECT '2014-09' month UNION SELECT '2014-10' UNION SELECT '2014-11')y; 
+---------+---------+ 
| qheader | month | 
+---------+---------+ 
| QH1  | 2014-09 | 
| QH2  | 2014-09 | 
| QH1  | 2014-10 | 
| QH2  | 2014-10 | 
| QH1  | 2014-11 | 
| QH2  | 2014-11 | 
+---------+---------+ 
+0

到現在爲止,我不知道straberries可以寫出好的SQL – user2070775 2014-11-15 00:01:20

+0

哦,這不好;-) – Strawberry 2014-11-15 00:22:12

相關問題