我有以下结构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/