I'm trying to select the 1st and last row(row 7) from 7 rows pulled from MySQL table. Looking at nesting a query is really confusing me to be honest. Using >
select location, value1, reading_time from sensordata
where id in
(
SELECT min(id)
FROM sensordata
WHERE id >= 0
and date(`reading_time`) >= '2013-04-01'
group by date(`reading_time`)
)
ORDER BY `sensordata`.`reading_time` DESC
LIMIT 7
This is working fine to pull the 7 days data I need(i want to use it to pull the last 7 days whenever the code is run) and displays the info I need to work with. But, I then want to subtract the last(most recent) entry from the earlier entry(row 7) to show usage over the last 7 days. This value, from column 'value1', is the only info I need and would like to display this, either by assigning a string to it or some other means.
When running the query i get this response in phpmyadmin(sorry its in text)>
location ..value1 ...reading_time
Kero Tank 802.46 2021-07-02 00:28:17 <<<<<<<< A
Kero Tank 802.46 2021-07-01 00:28:17
Kero Tank 802.46 2021-06-30 00:28:17
Kero Tank 811.48 2021-06-29 00:28:18
Kero Tank 811.48 2021-06-28 00:28:17
Kero Tank 811.48 2021-06-27 00:27:51
Kero Tank 811.48 2021-06-26 00:27:47 <<<<<<<< B
I want the result of BA for value1
using PHPMyAdmin
I am thinking window functions:
select distinct id, value1_last - value1_first
from (select sd.*,
first_value(value1) over (partition by id order by reading_time) as value1_first,
first_value(value1) over (partition by id order by reading_time desc) as value1_last
from sensor_data sd
where sd.id <> 0 and
sd.reading_time >= '2013-04-01'
) sd;
Note: The subquery is not strictly necessary. I wrote it that way because I suspect there might be other columns that you want as well, so you really want aggregation rather than select distinct
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.