简体   繁体   English

MySQL的。 选择没有1天

[英]MySQL. Select without 1 day

Base: name, rate, dt. 基数:名称,费率,dt。 Every day cost is inserted, I need to know the maximum cost without the first day. 插入每天的费用,我需要知道没有第一天的最高费用。 The first day of all products is different. 所有产品的第一天都不一样。

With all dates 与所有日期

SELECT `name`, MAX(rate) AS max
FROM `base`
GROUP BY `name`

This is similar to what I want, but not working. 这类似于我想要的,但是没有用。

SELECT `name`, MAX(rate) AS max, MIN(dt) AS min_dt
FROM `base`
WHERE `dt` > `min_dt`
GROUP BY `name`

Eample base 基地

skirt, 6, 2018-10-10 00:00:00 
skirt, 7, 2018-10-11 00:00:00 
cap, 7, 2018-10-11 00:00:00 
skirt, 8, 2018-10-12 00:00:00 
cap, 6, 2018-10-12 00:00:00 

Need 需要

skirt, 8
cap, 6

One approach is to use an inline view to get the min_dt for each name. 一种方法是使用内联视图获取每个名称的min_dt。 Then we can join and exclude the minimum date rows 然后,我们可以加入和排除最小日期行

Something like this: 像这样:

SELECT b.name
     , MAX(b.rate) AS `max`
  FROM ( SELECT d.name 
              , MIN(d.dt) AS min_dt
           FROM `base` d
          GROUP
             BY d.name
       ) m
  JOIN `base` b
    ON b.dt   > m.min_dt
   AND b.name = m.name 
 GROUP
    BY b.name

There are other query patterns that will achieve an equivalent result. 还有其他查询模式可以达到相同的结果。 My preference would to avoid a correlated subquery, but something like this would also return the specified result: 我的偏好是避免相关的子查询,但是类似的事情也会返回指定的结果:

SELECT b.name
     , MAX(b.rate) AS `max`
  FROM `base` b
 WHERE b.dt > ( SELECT MIN(d.dt) 
                  FROM `base` d
                 WHERE d.name = b.name 
              )
 GROUP
    BY b.name

(With both of these query forms, if there is only row in base for a given name , the query will not return a row for that name .) (对于这两种查询形式,如果给定name base仅存在一行,则该查询将不返回该name的行。)

You should try to exclude the min dt using subqueries: 您应该尝试使用子查询排除min dt:

SELECT name, MAX(rate) AS max
FROM (SELECT name, rate, dt
      FROM   base B
      WHERE dt NOT IN (SELECT MIN(dt) FROM base WHERE name=B.name ))  as A 
GROUP BY name

Fiddle here 在这里摆弄

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

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