我有这种表
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 1 | A1 | 500 | 2016-07-12 |
| 2 | A2 | 540 | 2018-01-21 |
| 3 | A1 | 440 | 2017-01-19 |
| 4 | A2 | 330 | 2016-01-12 |
| 5 | A3 | 333 | 2018-01-22 |
+----+------------+-------+------------+
首先,我想选择最大periods
并使用此查询按company_id
对其进行分组
SELECT salesreport.* FROM salesreport
INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport WHERE periods < 2016-01-01 GROUP BY company_id) AS latest_report
ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods;
它会像这样返回表格
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 2 | A2 | 540 | 2018-01-21 |
| 3 | A1 | 440 | 2017-01-19 |
| 5 | A3 | 333 | 2018-01-22 |
+----+------------+-------+------------+
但是现在我想限制我想要分组的最长时间段,让我说我想periods <= 2017-01-01
那么我期待的是
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 1 | A1 | 500 | 2016-07-12 |
| 4 | A2 | 330 | 2016-01-12 |
+----+------------+-------+------------+
我尝试使用having
和普通where
,但没有一个可以使用
SELECT salesreport.* FROM salesreport
INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport GROUP BY company_id HAVING MAX(periods) < 2017-01-01) AS latest_report
ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods;
SELECT salesreport.* FROM salesreport
INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport WHERE periods < 2017-01-01 GROUP BY company_id ) AS latest_report
ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods;
然后我意识到可能是因为MAX(periods)
但是如果不使用这个聚合,我如何获得groupBy中的最高值?所以,也许有查询专家的人可以提供洞察力来理解和解决这个问题....
更新
感谢@Accountant,他创建了这个来帮助我们查看和找到解决方案,随时在这里进行实验http://sqlfiddle.com/#!9/a7ae29/31
答案 0 :(得分:2)
你错过了将单个qoute放在日期值上。这是基于userid:accountant
的sqlfiddle演示正确:MAX(周期)&lt; &#39; 2017年1月1日&#39;
old:MAX(周期)&lt; 2017年1月1日
答案 1 :(得分:1)
将sub-query
与相关的方法
select * from salesreport s
where periods = (select max(periods) from salesreport
where company_id = s.company_id and periods <= '2017-01-01')
答案 2 :(得分:1)
试试这个,只需获取最大数据,其中句点为&lt;'2017-01-01'
SELECT salesreport.* FROM salesreport
INNER JOIN
(
SELECT company_id, MAX(periods) AS max_periods
FROM salesreport where periods<'2017-01-01'
GROUP BY company_id
) AS latest_report
ON salesreport.company_id = latest_report.company_id
AND salesreport.periods = latest_report.max_periods;
答案 3 :(得分:0)
您不需要比较MAX日期,您只需要比较日期(句点)。同时删除HAVING
子句。
SELECT salesreport.* FROM salesreport INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport WHERE periods < '2017-01-01' GROUP BY company_id) AS latest_report ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods
请试试这个,它应该适合你。