I have a rather complex SQL query that I am looking for a little help with.
I have two tables: a history table and a details table.
The history table contains the following columns.
Event Date(ev_date)
Event Code(ev_code)
Machine ID(mc_id)
The Details table contains the following columns:
Machine ID(mc_id),
Location ID(lo_id)
Machine Name(mc_name)
I need a query that returns the count of the number of events from the history table between a given date range of a given group of machines given by Location ID.
So, kinda in sudo code:
SELECT COUNT(*)
FROM history
WHERE ev_date (BETWEEN start_date AND end_date) AND ev_code = 1 AND ????
(mc_id must have certain lo_id from details table).
Does this make sense?
Thanks
SELECT COUNT(*)
FROM history h
WHERE h.ev_date BETWEEN @start_date AND @end_date
AND ev_code = 1
AND EXISTS(SELECT NULL
FROM details d
WHERE h.mc_id = d.mc_id
AND d.lo_id = @LocationID);
Assuming you have a one-to-one mapping between history
and details
on mc_id
:
SELECT COUNT(*)
FROM history h
JOIN details d USING mc_id
WHERE h.ev_code = 1
AND h.ev_date between start_date and end_date
AND d.lo_id IN (?, ?, ?, ...)
Alternatively ON h.mc_id = d.mc_id
instead of USING mc_id
.
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.