如何使 mysql 从 MAX(value) 而不是 value 查询 select 数据?

How to make mysql query select data from MAX(value) and not value?

我正在尝试 return 每个名称的最新日期的价格数据。

SELECT MAX(Date) AS max_date, Date, Price, Name 
from STOCK_DATA_TRANSPOSED 
group by Name

下面的输出是上面查询的输出。正如我们所见,价格数据是 return 按日期而不是 max_date。

max_date                    Date        Price   Name    
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    1COV.DE 
2021-04-21 00:00:00 2019-12-31 00:00:00 73.41   AAPL    
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ABB.ST  
2021-04-21 00:00:00 2019-12-31 00:00:00 88.54   ABBV    
2021-04-21 00:00:00 2019-12-31 00:00:00 86.86   ABT 
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AC.PA   
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ACA.PA  
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ACCD    
2021-04-21 00:00:00 2019-12-31 00:00:00 210.57  ACN 
2021-04-21 00:00:00 2019-12-31 00:00:00 329.81  ADBE    
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ADE.OL  
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ADS.DE  
2021-04-21 00:00:00 2019-12-31 00:00:00 7.64    AGLE    
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AI.PA   
2021-04-21 00:00:00 2019-12-31 00:00:00 51.33   AIG 
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AIR.PA  
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AKRBP.OL    
2021-04-21 00:00:00 2019-12-31 00:00:00 1.75    AKTX    
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ALFA.ST 
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ALIV-SDB.ST 
2021-04-21 00:00:00 2019-12-31 00:00:00 112.45  ALL 
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    ALV.DE  
2021-04-21 00:00:00 2019-12-31 00:00:00 NULL    AMBU-B.CO   
2021-04-21 00:00:00 2019-12-31 00:00:00 241.07  AMGN    
2021-04-21 00:00:00 2019-12-31 00:00:00 229.82  AMT 

如何 return 基于 max_date 按名称分组的价格数据?

试试这个:

SELECT sdt1.Date, sdt1.Price, sdt1.Name
FROM STOCK_DATA_TRANSPOSED AS sdt1
WHERE (sdt1.Date, sdt1.Name) IN
(
    SELECT MAX(sdt2.Date), sdt2.Name
    FROM STOCK_DATA_TRANSPOSED AS sdt2
    GROUP BY sdt2.Name
);

通过这种方式,您可以从 STOCK_DATA_TRANSPOSED 获取信息,其中 Date 是来自每个 NameMAX(Date)。 您可以在 DBFiddle.

中看到结果