如何根据查询中的最新日期获取最高价格

时间:2019-04-11 13:09:01

标签: mysql sql

示例记录:

|name  |price |source|lastest_update|
|name A| 20.00|att   |04/10/2019 00:00:00|
|name A| 30.00|att   |04/11/2019 02:00:00|
|name A| 50.00|sprint|04/10/2019 01:00:00|
|name A| 40.00|sprint|04/11/2019 21:00:00|

基本上,如果我们使用“按名称分组”分组,价格将是记录中的第一个,则是20美元,但我想根据lastest_update(日期)获得最高价格。结果将是:

|name  |att_price|sprint_price|
|name A|  30.00  |  40.00     |

我的查询

SELECT 
MAX(WHEN source = 'att' THEN price ELSE 0 END) as att_price,
MAX(WHEN source = 'sprint' THEN price ELSE 0 END) as sprint_price
FROM table GROUP BY name;

非常感谢您。

2 个答案:

答案 0 :(得分:0)

我想您可以对LIMIT使用简单的相关查询:

SELECT name
     , (SELECT price FROM t AS x WHERE name = t.name AND source = 'att'    ORDER BY lastest_update DESC LIMIT 1) AS att_price
     , (SELECT price FROM t AS x WHERE name = t.name AND source = 'sprint' ORDER BY lastest_update DESC LIMIT 1) AS sprint_price
FROM t
GROUP BY name

或者可能是双GROUP BY

SELECT t.name
     , MAX(CASE WHEN t.lastest_update = a.att_date    THEN price END) AS att_price
     , MAX(CASE WHEN t.lastest_update = a.sprint_date THEN price END) AS sprint_price
FROM t
JOIN (
    SELECT name
         , MAX(CASE WHEN source = 'att'    THEN lastest_update END) AS att_date
         , MAX(CASE WHEN source = 'sprint' THEN lastest_update END) AS sprint_date
    FROM t
    GROUP BY name
) AS a ON t.name = a.name
GROUP BY t.name

答案 1 :(得分:0)

从时间戳列date中提取latest_update,然后应用max()获取最新日期。现在,您只需添加一个where条件即可过滤仅具有此最大日期的行。

select name,
MAX(case WHEN source = 'att' THEN price ELSE 0 END) as att_price,
MAX(case WHEN source = 'sprint' THEN price ELSE 0 END) as sprint_price
FROM test 
where date(latest_update) = (select max(date(latest_update)) from test)
GROUP BY name;

演示: https://www.db-fiddle.com/f/43Uy7ocCKQRqJSaYHGcyRq/0

更新

由于您需要根据单独的来源source列为每个latest_update进行分组,因此可以使用以下SQL:

select t1.name,
    max(
        case 
            when t1.source = 'att' then t1.price
            else 0
        end
      ) as att_price,
     max(
        case 
            when t1.source = 'sprint' then t1.price
            else 0
        end
      ) as sprint_price
from test t1
      inner join (
        select name,source,max(latest_update) as latest_update
        from test
        group by name,source) t2
      on t1.name = t2.name and t1.source = t2.source
      and t1.latest_update  = t2.latest_update
group by t1.name;

演示: https://www.db-fiddle.com/f/qwBxizWooVG7AMwqKjewP/0