[英]sql query to get max date of group
我希望從每個WishContent中獲取基於wishContent.wishId的最新日期,因此,如果我有這樣的wishContents:
ID DATE
#1 : 09-03-2016
#1 : 08-03-2016
#1 : 03-04-2016
#2 : 09-02-2016
#2 : 04-01-2016
然后我只想要:
#1 09-03-2016
#2 09-02-2016
SELECT
wish.Status,
wish.Id,
wish.User,
wish.CompletionDate,
wishContent.Content,
wishContent.Title,
wishContent.Country,
wishContent.City,
wishContent.IsAccepted,
wishContent.moderator_Username,
MAX(wishContent.Date) AS max_date
FROM `wish` JOIN wishContent on wish.Id = wishContent.wish_Id
GROUP BY wish.Id where wish.Date
ORDER BY max_date DESC
誰能幫我 ?
我認為您需要額外的聯接才能獲得所需的結果:
SELECT
w.Status,
w.Id,
w.User,
w.CompletionDate,
wc.Content,
wc.Title,
wc.Country,
wc.City,
wc.IsAccepted,
wc.moderator_Username,
wcMax.max_date
FROM wish AS w
JOIN (SELECT wish_Id, MAX(wishContent.Date) AS max_date
FROM wishContent
GROUP BY wish_Id
) AS wcMax ON w.Id = wcMax.wish_Id
JOIN wishContent AS wc on wcMax.wish_Id = wc.wish_Id AND wc.Date = wcMax.max_date
WHERE wish.Date
ORDER BY max_date DESC
嘗試這個
SELECT * FROM (
SELECT
wish.Status,
wish.Id,
wish.User,
wish.CompletionDate,
wishContent.Content,
wishContent.Title,
wishContent.Country,
wishContent.City,
wishContent.IsAccepted,
wishContent.moderator_Username,
MAX(STR_TO_DATE(wishContent.Date,'%d-%m-%Y')) AS max_date
FROM `wish` JOIN wishContent on wish.Id = wishContent.wish_Id
GROUP BY wish.Id
) AS t
ORDER BY t.max_date DESC;
我假設您的日期格式為dd-mm-yyyy。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.