以下查询的作用是选择给定月份中每天的最小,最高,开始和最后价格。
我想选择相同的但是整个月,就像显示给定月份的整体表现而不是每天。
小提琴:http://sqlfiddle.com/#!9/ca4867/10
SELECT maxminprice.metal_id,
maxminprice.metal_price_datetime_IST,
maxminprice.max_price,
maxminprice.min_price,
firstlastprice.first_price,
firstlastprice.last_price
FROM (SELECT metal_id,
DATE(metal_price_datetime) metal_price_datetime_IST,
MAX(metal_price) max_price,
MIN(metal_price) min_price
FROM metal_prices
GROUP BY metal_id,
DATE(metal_price_datetime)
ORDER BY metal_id,
DATE(metal_price_datetime_IST)) maxminprice
INNER JOIN (SELECT mp.metal_id,
day_range.metal_price_datetimefl,
SUM(CASE
WHEN TIME(mp.metal_price_datetime_IST) = first_time
THEN
mp.metal_price
ELSE NULL
END) first_price,
SUM(CASE
WHEN TIME(mp.metal_price_datetime_IST) = last_time
THEN
mp.metal_price
ELSE NULL
END) last_price
FROM metal_prices mp
INNER JOIN (SELECT metal_id,
DATE(metal_price_datetime_IST)
metal_price_datetimefl,
MAX(TIME(metal_price_datetime_IST))
last_time,
MIN(TIME(metal_price_datetime_IST))
first_time
FROM metal_prices
GROUP BY metal_id,
DATE(metal_price_datetime_IST))
day_range
ON mp.metal_id = day_range.metal_id
AND DATE(mp.metal_price_datetime_IST) =
day_range.metal_price_datetimefl
AND TIME(mp.metal_price_datetime_IST) IN
( last_time, first_time )
GROUP BY mp.metal_id,
day_range.metal_price_datetimefl) firstlastprice
ON maxminprice.metal_id = firstlastprice.metal_id
AND maxminprice.metal_price_datetime_IST =
firstlastprice.metal_price_datetimefl
AND maxminprice.metal_price_datetime_IST BETWEEN '2018-02-01' AND LAST_DAY('2018-02-01')
ORDER BY metal_id, metal_price_datetime_IST DESC