选择MIN,MAX,AVG和当前(最新插入ID)值

时间:2013-08-22 09:39:42

标签: mysql

我需要获得GROUPed BY值, 但我需要看到的不是随机价格值(当我选择价格时),而是最新价格值(此GROUP中具有最高ID的行的价格)

SELECT ID, price, 
       ROUND(AVG(price)), 
       MIN(price),
       MAX(price),
       ROUND((AVG(price)-MIN(price))/AVG(price) * 100) as differenceinprices 
FROM `m-orbitzone` 
WHERE dep = 'MOW' 
  AND returnornot = 1 
GROUP BY arv, date1, date2 
ORDER BY differenceinprices DESC LIMIT 1000



ID    price <--     ROUND(AVG(price))   MIN(price)  MAX(price)  differenceinprices
122841  834 816 534 834 35
122708  783 790 524 821 34
122754  766 796 529 815 34
28528   810 766 512 810 33
28529   799 765 512 799 33
122603  766 798 534 841 33
122848  766 794 529 810 33
122589  778 765 519 778 32
122591  778 768 519 778 32
122749  766 775 529 814 32
28527   752 749 512 773 32
122744  766 773 529 814 32
122843  766 771 529 802 31

需要'价格'作为此GROUP的最新价格(ID最高的行)

可能需要做SELECT然后再从结果中再做一次SELECT吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

SELECT m.ID, price, 
       ROUND(AVG(price)), 
       MIN(price),
       MAX(price),
       ROUND((AVG(price)-MIN(price))/AVG(price) * 100) as differenceinprices 
FROM `m-orbitzone` m
INNER JOIN (
   SELECT
   ID
   FROM
   `m-orbitzone` m
   WHERE ID = (SELECT MAX(ID) FROM `m-orbitzone` sm WHERE m.arv = sm.arv AND m.date1 = sm.date1 AND m.date2 = sm.date2)
) s ON m.ID = s.ID
WHERE dep = 'MOW' 
  AND returnornot = 1 
GROUP BY arv, date1, date2 
ORDER BY differenceinprices DESC LIMIT 1000

关于该主题的好读物是this manual entry