mysql - 如何获得正确的最小值和最大值

标签 mysql sql

我有以下结构http://sqlfiddle.com/#!9/f8341c 从这些记录中,我的预期输出如下

Name|MinCost |MaxCost | Open | Close | Date
ABC |13.6    | 15.3   | 14.1 | 14.2  | 2015-12-02
DEF |93.2    | 96.3   | 93.7 | 95.4  | 2015-12-02 
ABC |15.1    | 15.6   | 15.1 | 15.2  | 2015-12-03
DEF |97.2    | 97.7   | 97.7 | 97.7  | 2015-12-03

现在我已经做到了

SELECT t1.name as 'Name',t1.min as 'MinCost',t1.max as 'MaxCost',t2.open ,t3.close,t1.times as 'Date'
  FROM(
        select name, max(cost) as 'max',min(cost) as 'min', date(time) as 'times'  
        from providers 
        group by  times,name 
        order by times
   ) AS t1
   JOIN (
     select name,cost as 'open',  time  
     from providers 
     where TIME(time) = '00:00:00'   
     group by time,name
     order by time
   ) as t2 on t1.name=t2.name
   JOIN (
       select name,cost as 'close', time  
       from providers 
       where TIME(time) = '23:59:59'   
       group by time,name
       order by time
   ) as t3 on t2.name=t3.name 
   GROUP BY t1.times,t1.name
   ORDER BY t1.times,t1.name

这给了我以下输出

| Name | MinCost | MaxCost | open | close |       Date |
|------|---------|---------|------|-------|------------|
|  ABC |    13.6 |    15.3 | 14.1 |  14.2 | 2015-12-02 |
|  DEF |    93.2 |    96.3 | 97.7 |  95.4 | 2015-12-02 |
|  ABC |    15.1 |    15.6 | 14.1 |  14.2 | 2015-12-03 |
|  DEF |    97.2 |    97.7 | 97.7 |  95.4 | 2015-12-03 |

我需要什么来更正查询?

最佳答案

因为你的名字不是唯一的,你需要在 join on 子句中添加 time 这样你就可以用 name 得到一个唯一的值和时间

下面的查询应该有效,Demo on your fiddle得到预期的输出

  SELECT t1.name as 'Name',t1.min as 'MinCost',t1.max as 'MaxCost',t2.open ,t3.close,t1.times as 'Date'
  FROM(
        select name, max(cost) as 'max',min(cost) as 'min', date(time) as 'times'  
        from providers 
        group by  times,name 
        order by times
   ) AS t1
   JOIN (
     select name,cost as 'open',  date(time) as 'times' 
     from providers 
     where TIME(time) = '00:00:00'   
     group by time,name
     order by time
   ) as t2 on t1.name=t2.name and t1.times = t2.times
   JOIN (
       select name,cost as 'close', date(time) as 'times' 
       from providers 
       where TIME(time) = '23:59:59'   
       group by time,name
       order by time
   ) as t3 on t2.name=t3.name  and t2.times = t3.times
   GROUP BY t1.times,t1.name
   ORDER BY t1.times,t1.name

关于mysql - 如何获得正确的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55503231/

相关文章:

MySQL 在内存中存储索引(用于读取)

MYSQL RANK OVER 获取最新排名

java - ALTER TABLE CREATE CONSTRAINT IF NOT EXIST 可能吗?

sql - SQL 中的这个嵌套 WHILE 循环有什么问题

mysql - MySQL-从版本控制数据库获取最新版本的文件内容

mysql - 加载数据 infile 以 "_"分隔单词

mysql - 将多行转换为列

mysql - 简单的 UPDATE 查询在 InnoDB 中比 MyISAM 花费更多时间

mysql - ExpressJS - Node 应用程序关闭后端口未释放

mysql - 按特定 ID 删除一行,该行不存在于另一个表列 ID 中