我具有以下结构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 |
我需要更正查询什么?
答案 0 :(得分:1)
由于您的姓名不是唯一的,因此需要在联接time
子句中添加on
,以便使用name
和time
获得唯一的值。
下面的查询应该可以正常工作,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
答案 1 :(得分:0)
您在这里:
select
d.name, d.min_cost, d.max_cost,
o.cost as open,
c.cost as close,
d.d as date
from (
select
name,
min(cost) as min_cost,
max(cost) as max_cost,
min(time) as open_time,
max(time) as close_time,
date(time) as d
from providers
group by name, date(time)
) d
join providers o on o.name = d.name and o.time = d.open_time
join providers c on c.name = d.name and c.time = d.close_time
order by d.d, d.name
结果:
name min_cost max_cost 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.4 2015-12-03
请注意,由于开盘价为97.7
,因此最后一行的预期结果有些错误。