I have 2 tables with a foreign key. I have to get the counts of all the records in right table and the threshold value of max ts in right table.
TABLE alarm
column | Datatype |
---|---|
id | PK |
name | varchar |
TABLE alarm_data
column | Datatype |
---|---|
alarm_id | FK |
ts | timestamp |
value | int |
I have to get total count of alarm_data associated with an alarm_id and the value of alarm_data with latest ts.
The expected output is
alarm_id | ts | occurance_count |
---|---|---|
1 | 123456 | 2 |
Queries I have used is
https://www.db-fiddle.com/f/4jyoMCicNSZpjMt4jFYoz5/7351
It is always returning multiple records as I have to add alarm_data.value in group by. It should only return 1 record with value and occurence count.
2
Answers
You can do it using
group by
to getcount()
andmax(ts)
:You could use the
row_number
function to get the value of alarm_data with the latest ts, and the count window function to get the total count of alarm_data associated with an alarm_id.See demo