简体   繁体   English

获取具有2个条件的Max(date)或最新日期,或者通过group by或subquery

[英]Get Max(date) or latest date with 2 conditions or group by or subquery

I only have basic SQL skills. 我只有基本的SQL技能。 I'm working in SQL in Navicat. 我正在Navicat中使用SQL。 I've looked through the threads of people who were also trying to get latest date, but not yet been able to apply it to my situation. 我浏览了也想获取最新日期的人的线索,但还不能将其应用于我的情况。

I am trying to get the latest date for each name, for each chemical. 我正在尝试获取每种化学品的每种名称的最新日期。 I think of it this way: "Within each chemical, look at data for each name, choose the most recent one." 我这样想:“在每种化学药品中,查看每种名称的数据,然后选择最新的一种。”

I have tried using max(date(date)) but it needs to be nested or subqueried within chemical. 我尝试使用max(date(date))但需要在化学药品中嵌套或子查询。

I also tried ranking by date(date) DESC , then using LIMIT 1 . 我还尝试按date(date) DESC排名,然后使用LIMIT 1 But I was not able to nest this within chemical either. 但是我也无法将其嵌套在化学物质中。

When I try to write it as a subquery, I keep getting an error on the ( . I've switched it up so that I am beginning the subquery a number of different ways, but the error returns near that area always. 当我尝试将其写为子查询时,我总是在(上遇到错误。我已将其切换为以多种方式开始子查询,但错误总是在该区域附近返回。

Here is what the data looks like: 1 Here is one of my failed queries: 数据如下所示: 1这是我失败的查询之一:

SELECT
   WELL_NAME,
   CHEMICAL,
   RESULT,
   APPROX_LAT,
   APPROX_LONG,
   DATE

FROM
   data_all
ORDER BY
   CHEMICAL ASC,
   date( date ) DESC (
SELECT
   WELL_NAME,
   CHEMICAL,
   APPROX_LAT,
   APPROX_LONG,
   DATE 
FROM
   data_all 
WHERE
   WELL_NAME = WELL_NAME 
   AND CHEMICAL = CHEMICAL 
   AND APPROX_LAT = APPROX_LAT 
   AND APPROX_LONG = APPROX_LONG,

LIMIT 2 
)

If someone does have a response, it would be great if it is in as lay language as possible. 如果某人确实有回应,那么使用尽可能外行的语言就很好。 I've only had one coding class. 我只有一个编码课。 Thanks very much. 非常感谢。

Maybe something like this? 也许是这样的吗?

SELECT WELL_NAME, CHEMICAL, MAX(DATE)
FROM data_all
GROUP BY WELL_NAME, CHEMICAL

If you want all information, then use the ANSI-standard ROW_NUMBER() : 如果需要所有信息,请使用ANSI标准的ROW_NUMBER()

SELECT da.*
FROM (SELECT da.*
             ROW_NUMBER() OVER (PARTITION BY chemical, name ORDER BY date DESC) as senum
      FROM data_all da
     ) da
WHERE seqnum = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM