我有一个名为myTable的表,如下所示:
id, myDate, name, group
1, 2012-04-09, john, subGroup-A
2, 2012-04-10, marc, subGroup-B
对于以'subGroup'开头的子组,我想检索带有maxDate的记录及其附带的名称。所以我正在做以下查询:
SELECT max(myDate) AS maxDate, name FROM myTable WHERE group LIKE "subGroup%";
我希望此查询能够将此返回给我:
maxDate, name
2012-04-10, marc
但相反它却让我回答:
maxDate, name
2012-04-10, john
所以基本上正确地采用了maxDate,但名称不是与该日期对应的名称。我真的不明白。希望有人能帮助我理解。提前感谢您的回复。干杯。马克
答案 0 :(得分:2)
你可以参考这篇文章I need a sql query to group by name but return other fields based on the most recent entry MSSQL有两种解决方案,一种是通用的。
主要规则:永远不要包括SELECT
列出未包含在GROUP BY
子句中或具有聚合函数的列。
答案 1 :(得分:2)
您的查询是:
SELECT max(myDate) AS maxDate, name FROM myTable WHERE group LIKE "subGroup%";
我认为您需要以下内容:
SELECT MAX(myDate) AS maxDate, name
FROM myTable
GROUP BY NAME
HAVING group LIKE "subGroup%"
或
SELECT myDate AS maxDate, name
FROM myTable
WHERE group LIKE "subGroup%" AND myDate = (SELECT MAX(myDate) FROM myTable)