如何使用MySQL获取最近日期?

4

我该如何使用MySQL获取最近的日期?我尝试了max函数但是没有得到我想要的结果。我的表格看起来像这样:

+---------+---------+-----------------------+--------+------------+---------+
| Name    | idStore | Name                  | idItem | date       | price   |
+---------+---------+-----------------------+--------+------------+---------+
| walmart |       1 | Red Delicious Apples  |      1 | 2011-10-22 | 0.98000 |
| walmart |       1 | Red Delicious Apples  |      1 | 2011-10-28 | 0.98000 |
| walmart |       1 | Red Delicious Apples  |      1 | 2011-10-28 | 0.98000 |
| walmart |       1 | Red Delicious Apples  |      1 | 2011-11-22 | 0.98000 |
| walmart |       1 | Honeycrisp Apples     |      2 | 2011-10-22 | 1.98000 |
| walmart |       1 | Sonya Apples          |      3 | 2011-10-22 | 2.88000 |
| walmart |       1 | Gold Delicious Apples |      4 | 2011-10-22 | 0.98000 |
| walmart |       1 | Sweet Tango Apples    |      5 | 2011-10-22 | 2.48000 |
| walmart |       1 | Granny Smith Apples   |      6 | 2011-10-22 | 1.28000 |
| walmart |       1 | Fugi Apples           |      7 | 2011-10-22 | 1.38000 |
+---------+---------+-----------------------+--------+------------+---------+

我想获取这个表格:

+---------+---------+-----------------------+--------+------------+---------+
| Name    | idStore | Name                  | idItem | date       | price   |
+---------+---------+-----------------------+--------+------------+---------+
| walmart |       1 | Red Delicious Apples  |      1 | 2011-11-22 | 0.98000 |
| walmart |       1 | Honeycrisp Apples     |      2 | 2011-10-22 | 1.98000 |
| walmart |       1 | Sonya Apples          |      3 | 2011-10-22 | 2.88000 |
| walmart |       1 | Gold Delicious Apples |      4 | 2011-10-22 | 0.98000 |
| walmart |       1 | Sweet Tango Apples    |      5 | 2011-10-22 | 2.48000 |
| walmart |       1 | Granny Smith Apples   |      6 | 2011-10-22 | 1.28000 |
| walmart |       1 | Fugi Apples           |      7 | 2011-10-22 | 1.38000 |
+---------+---------+-----------------------+--------+------------+---------+

我在解决这个问题时遇到了困难。谢谢!


1
你并不是唯一一个在这方面遇到困难的人。我建议你提供一些你已经尝试过的代码,以便我们能够看出其中为何不能实现预期效果。 - kasimir
5个回答

3
您可以使用“group by”:
select NameStore, idStore, Name, idItem, max(date) date, price
from table
group by NameStore, idStore, Name, idItem, price

2

注意:如果他真的只想要最近的日期和适用于该日期的价格,而不管早期日期可能适用的其他价格,则此方法将无效。 - Erwin Smout

1

-1
将以下内容放在末尾:ORDER BY date DESC 这样就像这样:
SELECT * FROM `tablename` ORDER BY `date` DESC

在上述的SQL语句中使用DISTINCT(Name)GROUP BY Name,可以使一个项目仅出现一次。


1
但他也想只看到每个idItem的一行。提示:GROUP BY? - Konerak
然后请查看此链接以获取唯一值。 - abhinav
-1 排序不符合他的需求;这仍然会保留重复的日期。 - Eljakim
1
“如何使用MySQL获取最近的日期?”这是问题,抱歉回答了它。 - Tusk

-1

你需要使用 GROUP BY 子句,用法如下:

SELECT Name, idStore, Name, idItem, date, price 
FROM mytable 
GROUP BY idItem 
ORDER BY date DESC, idItem DESC;

使用 DESC 或 ASC 更改排序方向。您可以通过阅读文档来了解更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接