简体   繁体   中英

SQL, select rows based on time (column), time occurs when another column has a certain value

the situation I've got is an engine with a temperature sensor and an engine speed sensor

I can select off times when my engine gets too hot

SELECT global_times AS times
FROM myTable AS A
WHERE ser_num LIKE 'XXXX' --user changes this
                     AND chan_nm IN ('temp_oil')
                     AND  global_times BETWEEN TIMESTAMP '2016-01-14 00:00:01'   AND TIMESTAMP '2016-01-14 00:59:59' --just working with a day at a time
                     AND EVNT_VAL>=90; 

So, basically, event_value corresponds to temperature when chan_nm is "temp_oil"

but it corresponds to rpms when chan_nm is "engine_speed"

This code takes this table:

SER_NUM global_times    EVNT_VAL    CHAN_NM
'XXXX'  00:00:01.01     700 ENGSPD
'XXXX'  00:00:01.01     87  temp_oil
'XXXX'  00:00:02.01     701 ENGSPD
'XXXX'  00:00:02.01     88  temp_oil
'XXXX'  00:00:03.01     702 ENGSPD
'XXXX'  00:00:03.01     89  temp_oil
'XXXX'  00:00:04.01     703 ENGSPD
'XXXX'  00:00:04.01     90  temp_oil
'XXXX'  00:00:05.01     704 ENGSPD
'XXXX'  00:00:05.01     91  temp_oil
'XXXX'  00:00:06.01     704 ENGSPD
'XXXX'  00:00:06.01     92  temp_oil

and returns

global_times
00:00:04.01
00:00:05.01
00:00:06.01

what I'd like to do is get all the columns that correspond to that time, particularly the rows that correspond to the engine speed

I've tried using joins, but can't figure out how to right/left/union it against a table

I've also tried doing

select * from my_table where global_time in (XXXX)

Where I replace XXX by copy/pasting the previous code

If I understand you correctly you want both temp_oil and ENGSPD rows where temperature is high. You can do that in a single query using a group-count:

SELECT *
FROM myTable AS A
WHERE ser_num LIKE 'XXXX' --user changes this
   AND chan_nm IN ('temp_oil', `ENGSPD`)
   AND global_times BETWEEN TIMESTAMP '2016-01-14 00:00:01'
                       AND TIMESTAMP '2016-01-14 00:59:59' --just working with a day at a time
QUALIFY
   MAX(CASE WHEN chan_nm = 'temp_oil' THEN EVNT_VAL END)
   OVER (PARTITION BY global_times) >=90; 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM