产生过去几个月并加入不相关的数据

时间:2014-11-14 23:41:26

标签: mysql sql sql-server mysqli

在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中),但不确定如何在qheader

中找到questionsec每个月的每一行
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')

1 个答案:

答案 0 :(得分: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 |
 +---------+---------+