[英]Get only the records with most recent date to every code
我有這樣的桌子
+------+-------+-----------+-------------+
| code | price | perct_off | date_review |
+------+-------+-----------+-------------+
| 0001 | 1500 | 40 | 2017-12-30 |
| 0001 | 1500 | 40 | 2018-02-15 |
| 0001 | 2000 | 25 | 2018-07-31 |
| 0002 | 3000 | 45 | 2018-03-20 |
| 0002 | 5000 | 20 | 2018-08-01 |
| 0003 | 3000 | 40 | 2018-01-16 |
+------+-------+-----------+-------------+
而且我只希望每個代碼的記錄都有最大日期。 Iutput必須為:
+------+-------+-----------+-------------+
| code | price | perct_off | date_review |
+------+-------+-----------+-------------+
| 0001 | 2000 | 25 | 2018-07-31 |
| 0002 | 5000 | 20 | 2018-08-01 |
| 0003 | 3000 | 40 | 2018-01-16 |
+------+-------+-----------+-------------+
當我嘗試:
SELECT DISTINCT
(code), price, perct_off, MAX(date_review)
FROM `table01`
GROUP BY code
我有這個輸出
+-------+--------+------------+-------------------+
| code | price | perct_off | max(date_review) |
+-------+--------+------------+-------------------+
| 0001 | 1500 | 40 | 2018-07-31 |
| 0002 | 3000 | 45 | 2018-08-01 |
| 0003 | 3000 | 40 | 2018-01-16 |
+-------+--------+------------+-------------------+
如何獲得嚴格的輸出?
提前致謝。
做到這一點的一種典型方法是加入子查詢,該子查詢查找每個code
最新日期:
SELECT t1.*
FROM table01 t1
INNER JOIN
(
SELECT code, MAX(date_review) AS max_date_review
FROM table01
GROUP BY code
) t2
ON t1.code = t2.code AND t1.date_review = t2.max_date_review;
優化的解決方案:
SELECT
t1.code,
t1.price,
t1.perct_off,
t1.date_review
FROM t t1
LEFT JOIN t t2 ON
t1.code = t2.code
AND t1.date_review < t2.date_review
WHERE t2.date_review IS NULL;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.