How to handle multiple associated log messages? - sql

I have a service that calculates a bunch of things for a project. A user can trigger this calculation multiple times a day. Every calculation generates a few interesting metrics (let's call them A, B, C).
I report these metrics to a log service with individual log messages. The log messages look like this:
date | calculationID1 | projectID1 | metricA | valueA
date | calculationID1 | projectID1 | metricB | valueB
date | calculationID1 | projectID1 | metricC | valueC
date | calculationID2 | projectID2 | metricA | valueA
date | calculationID2 | projectID2 | metricB | valueB
date | calculationID2 | projectID2 | metricC | valueC
date | calculationID3 | projectID1 | metricA | valueA
date | calculationID3 | projectID1 | metricB | valueB
date | calculationID3 | projectID1 | metricC | valueC
In this example the project with ID 1 was run two times on this particular day. In my analytics backend I have a Hive cluster to analyze this data and I want to generate a table with the last reported metrics for every project for a given day day:
date | calculationID3 | projectID1 | valueA | valueB | valueC
date | calculationID2 | projectID2 | valueA | valueB | valueC
Apparently this calculation is really costly as I do a lot of joins. My company has a strict logging format and that's why I created one value per log message. Should I create one log message containing all metrics instead to ease the reporting?
Can anyone point me to best practices for these kind of problems?

If we use DB, supporting PIVOT clause in SQL, then we can gather data from log report using the following query.
The same results can be fetched without PIVOT, but another way requires a lot of copy-paste and juggling, and since you are "pragmatic with implementation", I suppose we don't need to speak about those dirty things.
To see what's happening in the query you can do 3 steps:
run the query without PIVOT (just remove the PIVOT keyword and the rest of the code)
then run it as is
compare results of the first and the second step, recognising how the rows are transposing to the columns
WITH
data_table (stamp, calculation_ID, project_ID, metric_name, metric_value) as ( select
timestamp '2015-01-01 00:00:01', 'calc_ID_1', 'project_WHITE', 'metric_A', 11 from dual union all select
timestamp '2015-01-01 00:00:02', 'calc_ID_1', 'project_WHITE', 'metric_B', 21 from dual union all select
timestamp '2015-01-01 00:00:03', 'calc_ID_1', 'project_WHITE', 'metric_C', 31 from dual union all select
timestamp '2015-01-01 00:01:04', 'calc_ID_2', 'project_WHITE', 'metric_A', 12 from dual union all select
timestamp '2015-01-01 00:01:05', 'calc_ID_2', 'project_WHITE', 'metric_B', 22 from dual union all select
timestamp '2015-01-01 00:01:06', 'calc_ID_2', 'project_WHITE', 'metric_C', 32 from dual union all select
timestamp '2015-01-01 00:00:11', 'calc_ID_3', 'project_BLACK', 'metric_A', 41 from dual union all select
timestamp '2015-01-01 00:00:12', 'calc_ID_3', 'project_BLACK', 'metric_B', 51 from dual union all select
timestamp '2015-01-01 00:00:13', 'calc_ID_3', 'project_BLACK', 'metric_C', 61 from dual union all select
timestamp '2015-01-01 00:01:14', 'calc_ID_4', 'project_BLACK', 'metric_A', 42 from dual union all select
timestamp '2015-01-01 00:01:15', 'calc_ID_4', 'project_BLACK', 'metric_B', 52 from dual union all select
timestamp '2015-01-01 00:01:16', 'calc_ID_4', 'project_BLACK', 'metric_C', 62 from dual
)
SELECT *
FROM (
select trunc(stamp) AS day,
calculation_id,
project_id,
metric_name,
metric_value
from (
select t.*,
rank() OVER (PARTITION BY project_ID, metric_name, trunc(stamp) ORDER BY stamp DESC) calculation_rank
from data_table t
-- take only the last log row for (project_ID, metric_name) for every given day
) where calculation_rank = 1
)
PIVOT (
-- aggregate function is required here,
-- and SUM can be replaced with something more relevant to custom logic
SUM(metric_value)
FOR
metric_name IN ('metric_A' AS "Metric A",
'metric_B' AS "Metric B",
'metric_C' AS "Metric C")
);
Results:
DAY | CALCULATION_ID | PROJECT_ID | Metric A | Metric B | Metric C
------------------------------------------------------------------------------
2015-01-01 | calc_ID_4 | project_BLACK | 42 | 52 | 62
2015-01-01 | calc_ID_2 | project_WHITE | 12 | 22 | 32
In this query calculation_ID is redundant (I use it only to make example clearer for code reader). But you still can apply this info to check integrity of logging data format, exploring if equal calculation_ID corresponds to the metrics involved in the same group/time-period.

Related

Question: Joining two data sets with date conditions

I'm pretty new with SQL, and I'm struggling to figure out a seemingly simple task.
Here's the situation:
I'm working with two data sets
Data Set A, which is the most accurate but only refreshes every quarter
Data Set B, which has all the date, including the most recent data, but is overall less accurate
My goal is to combine both data sets where I would have Data Set A for all data up to the most recent quarter and Data Set B for anything after (i.e., all recent data not captured in Data Set A)
For example:
Data Set A captures anything from Q1 2020 (January to March)
Let's say we are April 15th
Data Set B captures anything from Q1 2020 to the most current date, April 15th
My goal is to use Data Set A for all data from January to March 2020 (Q1) and then Data Set B for all data from April 1 to 15
Any thoughts or advice on how to do this? Potentially a join function along with a date one?
Any help would be much appreciated.
Thanks in advance for the help.
I hope I got your question right.
I put in some sample data that might match your description: a date and an amount. To keep it simple, one row per any month. You can extract the quarter from a date, and keep that as an additional column, and then filter by that down the line.
WITH
-- some sample data: date and amount ...
indata(dt,amount) AS (
SELECT DATE '2020-01-15', 234.45
UNION ALL SELECT DATE '2020-02-15', 344.45
UNION ALL SELECT DATE '2020-03-15', 345.45
UNION ALL SELECT DATE '2020-04-15', 346.45
UNION ALL SELECT DATE '2020-05-15', 347.45
UNION ALL SELECT DATE '2020-06-15', 348.45
UNION ALL SELECT DATE '2020-07-15', 349.45
UNION ALL SELECT DATE '2020-08-15', 350.45
UNION ALL SELECT DATE '2020-09-15', 351.45
UNION ALL SELECT DATE '2020-10-15', 352.45
UNION ALL SELECT DATE '2020-11-15', 353.45
UNION ALL SELECT DATE '2020-12-15', 354.45
)
-- real query starts here ...
SELECT
EXTRACT(QUARTER FROM dt) AS the_quarter
, CAST(
TIMESTAMPADD(
QUARTER
, CAST(EXTRACT(QUARTER FROM dt) AS INTEGER)-1
, TRUNC(dt,'YEAR')
)
AS DATE
) AS qtr_start
, *
FROM indata;
-- out the_quarter | qtr_start | dt | amount
-- out -------------+------------+------------+--------
-- out 1 | 2020-01-01 | 2020-01-15 | 234.45
-- out 1 | 2020-01-01 | 2020-02-15 | 344.45
-- out 1 | 2020-01-01 | 2020-03-15 | 345.45
-- out 2 | 2020-04-01 | 2020-04-15 | 346.45
-- out 2 | 2020-04-01 | 2020-05-15 | 347.45
-- out 2 | 2020-04-01 | 2020-06-15 | 348.45
-- out 3 | 2020-07-01 | 2020-07-15 | 349.45
-- out 3 | 2020-07-01 | 2020-08-15 | 350.45
-- out 3 | 2020-07-01 | 2020-09-15 | 351.45
-- out 4 | 2020-10-01 | 2020-10-15 | 352.45
-- out 4 | 2020-10-01 | 2020-11-15 | 353.45
-- out 4 | 2020-10-01 | 2020-12-15 | 354.45
If you filter by quarter, you can group your data by that column ...

Oracle SQL Join Data Sequentially

I am trying to track the usage of material with my SQL. There is no way in our database to link when a part is used to the order it originally came from. A part simply ends up in a bin after an order arrives, and then usage of parts basically just creates a record for the number of parts used at a time of transaction. I am attempting to, as best I can, link usage to an order number by summing over the data and sequentially assigning it to order numbers.
My sub queries have gotten me this far. Each order number is received on a date. I then join the usage table records based on the USEDATE needing to be equal to or greater than the RECEIVEDATE of the order. The data produced by this is as such:
| ORDERNUM | PARTNUM | RECEIVEDATE | ORDERQTY | USEQTY | USEDATE |
|----------|----------|-------------------------|-----------|---------|------------------------|
| 4412 | E1125 | 10/26/2016 1:32:25 PM | 1 | 1 | 11/18/2016 1:40:55 PM |
| 4412 | E1125 | 10/26/2016 1:32:25 PM | 1 | 3 | 12/26/2016 2:19:32 PM |
| 4412 | E1125 | 10/26/2016 1:32:25 PM | 1 | 1 | 1/3/2017 8:31:21 AM |
| 4111 | E1125 | 10/28/2016 2:54:13 PM | 1 | 1 | 11/18/2016 1:40:55 PM |
| 4111 | E1125 | 10/28/2016 2:54:13 PM | 1 | 3 | 12/26/2016 2:19:32 PM |
| 4111 | E1125 | 10/28/2016 2:54:13 PM | 1 | 1 | 1/3/2017 8:31:21 AM |
| 0393 | E1125 | 12/22/2016 11:52:04 AM | 3 | 3 | 12/26/2016 2:19:32 PM |
| 0393 | E1125 | 12/22/2016 11:52:04 AM | 3 | 1 | 1/3/2017 8:31:21 AM |
| 7812 | E1125 | 12/27/2016 10:56:01 AM | 1 | 1 | 1/3/2017 8:31:21 AM |
| 1191 | E1125 | 1/5/2017 1:12:01 PM | 2 | 0 | null |
The query for the above section looks as such:
SELECT
B.*,
NVL(B2.QTY, ‘0’) USEQTY
B2.USEDATE USEDATE
FROM <<Sub Query B>>
LEFT JOIN USETABLE B2 ON B.PARTNUM = B2.PARTNUM AND B2.USEDATE >= B.RECEIVEDATE
My ultimate goal here is to join USEQTY records sequentially until they have filled enough ORDERQTY’s. I also need to add an ORDERUSE column that represents what QTY from the USEQTY column was actually applied to that record. Not really sure how to word this any better so here is example of what I need to happen based on the table above:
| ORDERNUM | PARTNUM | RECEIVEDATE | ORDERQTY | USEQTY | USEDATE | ORDERUSE |
|----------|----------|-------------------------|-----------|---------|------------------------|-----------|
| 4412 | E1125 | 10/26/2016 1:32:25 PM | 1 | 1 | 11/18/2016 1:40:55 PM | 1 |
| 4111 | E1125 | 10/28/2016 2:54:13 PM | 1 | 3 | 12/26/2016 2:19:32 PM | 1 |
| 0393 | E1125 | 12/22/2016 11:52:04 AM | 3 | 2 | 12/26/2016 2:19:32 PM | 2 |
| 0393 | E1125 | 12/22/2016 11:52:04 AM | 3 | 1 | 1/3/2017 8:31:21 AM | 1 |
| 7812 | E1125 | 12/27/2016 10:56:01 AM | 1 | 0 | null | 0 |
| 1191 | E1125 | 1/5/2017 1:12:01 PM | 2 | 0 | null | 0 |
If I can get the query to pull the information like above, I will then be able to group the records together and sum the ORDERUSE column which would get me the information I need to know what orders have been used and which have not been fully used. So in the example above, if I were to sum the ORDERUSE column for each of the ORDERNUMs, orders 4412, 4111, 0393 would all show full usage. Orders 7812, 1191 would show not being fully used.
If i am reading this correctly you want to determine how many parts have been used. In your example it looks like you have 5 usages and with 5 orders coming to a total of 8 parts with the following orders having been used.
4412 - one part - one used
4111 - one part - one used
7812 - one part - one used
0393 - three
parts - two used
After a bit of hacking away I came up with the following SQL. Not sure if this works outside of your sample data since thats the only thing I used to test and I am no expert.
WITH data
AS (SELECT *
FROM (SELECT *
FROM sub_b1
join (SELECT ROWNUM rn
FROM dual
CONNECT BY LEVEL < 15) a
ON a.rn <= sub_b1.orderqty
ORDER BY receivedate)
WHERE ROWNUM <= (SELECT SUM(useqty)
FROM sub_b2))
SELECT sub_b1.ordernum,
partnum,
receivedate,
orderqty,
usage
FROM sub_b1
join (SELECT ordernum,
Max(rn) AS usage
FROM data
GROUP BY ordernum) b
ON sub_b1.ordernum = b.ordernum
You are looking for "FIFO" inventory accounting.
The proper data model should have two tables, one for "received" parts and the other for "delivered" or "used". Each table should show an order number, a part number and quantity (received or used) for that order, and a timestamp or date-time. I model both in CTE's in my query below, but in your business they should be two separate table. Also, a trigger or similar should enforce the constraint that a part cannot be used until it is available in stock (that is: for each part id, the total quantity used since inception, at any point in time, should not exceed the total quantity received since inception, also at the same point in time). I assume that the two input tables do, in fact, satisfy this condition, and I don't check it in the solution.
The output shows a timeline of quantity used, by timestamp, matching "received" and "delivered" (used) quantities for each part_id. In the sample data I illustrate a single part_id, but the query will work with multiple part_id's, and orders (both for received and for delivered or used) that include multiple parts (part id's) with different quantities.
with
received ( order_id, part_id, ts, qty ) as (
select '0030', '11A4', timestamp '2015-03-18 15:00:33', 20 from dual union all
select '0032', '11A4', timestamp '2015-03-22 15:00:33', 13 from dual union all
select '0034', '11A4', timestamp '2015-03-24 10:00:33', 18 from dual union all
select '0036', '11A4', timestamp '2015-04-01 15:00:33', 25 from dual
),
delivered ( order_id, part_id, ts, qty ) as (
select '1200', '11A4', timestamp '2015-03-18 16:30:00', 14 from dual union all
select '1210', '11A4', timestamp '2015-03-23 10:30:00', 8 from dual union all
select '1220', '11A4', timestamp '2015-03-23 11:30:00', 7 from dual union all
select '1230', '11A4', timestamp '2015-03-23 11:30:00', 4 from dual union all
select '1240', '11A4', timestamp '2015-03-26 15:00:33', 1 from dual union all
select '1250', '11A4', timestamp '2015-03-26 16:45:11', 3 from dual union all
select '1260', '11A4', timestamp '2015-03-27 10:00:33', 2 from dual union all
select '1270', '11A4', timestamp '2015-04-03 15:00:33', 16 from dual
),
(end of test data; the SQL query begins below - just add the word WITH at the top)
-- with
combined ( part_id, rec_ord, rec_ts, rec_sum, del_ord, del_ts, del_sum) as (
select part_id, order_id, ts,
sum(qty) over (partition by part_id order by ts, order_id),
null, cast(null as date), cast(null as number)
from received
union all
select part_id, null, cast(null as date), cast(null as number),
order_id, ts,
sum(qty) over (partition by part_id order by ts, order_id)
from delivered
),
prep ( part_id, rec_ord, del_ord, del_ts, qty_sum ) as (
select part_id, rec_ord, del_ord, del_ts, coalesce(rec_sum, del_sum)
from combined
)
select part_id,
last_value(rec_ord ignore nulls) over (partition by part_id
order by qty_sum desc) as rec_ord,
last_value(del_ord ignore nulls) over (partition by part_id
order by qty_sum desc) as del_ord,
last_value(del_ts ignore nulls) over (partition by part_id
order by qty_sum desc) as used_date,
qty_sum - lag(qty_sum, 1, 0) over (partition by part_id
order by qty_sum, del_ts) as used_qty
from prep
order by qty_sum
;
Output:
PART_ID REC_ORD DEL_ORD USED_DATE USED_QTY
------- ------- ------- ----------------------------------- ----------
11A4 0030 1200 18-MAR-15 04.30.00.000000000 PM 14
11A4 0030 1210 23-MAR-15 10.30.00.000000000 AM 6
11A4 0032 1210 23-MAR-15 10.30.00.000000000 AM 2
11A4 0032 1220 23-MAR-15 11.30.00.000000000 AM 7
11A4 0032 1230 23-MAR-15 11.30.00.000000000 AM 4
11A4 0032 1230 23-MAR-15 11.30.00.000000000 AM 0
11A4 0034 1240 26-MAR-15 03.00.33.000000000 PM 1
11A4 0034 1250 26-MAR-15 04.45.11.000000000 PM 3
11A4 0034 1260 27-MAR-15 10.00.33.000000000 AM 2
11A4 0034 1270 03-APR-15 03.00.33.000000000 PM 12
11A4 0036 1270 03-APR-15 03.00.33.000000000 PM 4
11A4 0036 21
12 rows selected.
Notes: (1) One needs to be careful if at one moment the cumulative used quantity exactly matches cumulative received quantity. All rows must be include in all the intermediate results, otherwise there will be bad data in the output; but this may result (as you can see in the output above) in a few rows with a "used quantity" of 0. Depending on how this output is consumed (for further processing, for reporting, etc.) these rows may be left as they are, or they may be discarded in a further outer-query with the condition where used_qty > 0.
(2) The last row shows a quantity of 21 with no used_date and no del_ord. This is, in fact, the "current" quantity in stock for that part_id as of the last date in both tables - available for future use. Again, if this is not needed, it can be removed in an outer query. There may be one or more rows like this at the end of the table.

how to exclude the most recent null field from query result?

I want to design a query to find out is there at least one cat (select count(*) where rownum = 1) that haven't been checked out.
One weird condition is that the result should exclude if the most recent cat that didn't checked out, so that:
TABLE schedule
-------------------------------------
| type | checkin | checkout
-------------------------------------
| cat | 20:10 | (null)
| dog | 19:35 | (null)
| dog | 19:35 | (null)
| cat | 15:31 | (null) ----> exclude this cat in this scenario
| dog | 12:47 | 13:17
| dog | 10:12 | 12:45
| cat | 08:27 | 11:36
should return 1, the first record
| cat | 20:10 | (null)
I kind of create the query like
select * from schedule where type = 'cat' and checkout is null order by checkin desc
however this query does not resolve the exclusion. I can sure handle it in the service layer like java, but just wondering any solution can design in the query and with good performance when there is large amount of data in the table ( checkin and checkout are indexed but not type)
How about this?
Select *
From schedule
Where type='cat' and checkin=(select max(checkin) from schedule where type='cat' and checkout is null);
Assuming the checkin and checkout data type is string (which it shouldn't be, it should be DATE), to_char(checkin, 'hh24:mi') will create a value of the proper data type, DATE, assuming the first day of the current month as the "date" portion. It shouldn't matter to you, since presumably all the hours are from the same date. If in fact checkin/out are in the proper DATE data type, you don't need the to_date() call in order by (in two places).
I left out the checkout column from the output, since you are only looking for the rows with null in that column, so including it would provide no information. I would have left out type as well, but perhaps you'll want to have this for cats AND dogs at some later time...
with
schedule( type, checkin, checkout ) as (
select 'cat', '20:10', null from dual union all
select 'dog', '19:35', null from dual union all
select 'dog', '19:35', null from dual union all
select 'cat', '15:31', null from dual union all
select 'dog', '12:47', '13:17' from dual union all
select 'dog', '10:12', '12:45' from dual union all
select 'cat', '08:27', '11:36' from dual
)
-- end of test data; actual solution (SQL query) begins below this line
select type, checkin
from ( select type, checkin,
row_number() over (order by to_date(checkin, 'hh24:mi')) as rn
from schedule
where type = 'cat' and checkout is null
)
where rn > 1
order by to_date(checkin, 'hh24:mi') -- ORDER BY is optional
;
TYPE CHECKIN
---- -------
cat 20:10

oracle take mean value of one column across different dates

There is one column called Price, and another column called Date_1, which include data from now to about one year later.
I want to find the mean value of Price across different dates. Ex, 2 weeks from now, 1 month from now, 6 months from now...
Can I use Case When function to do it?
Given:
Location_id | Date_1 | Price
------------+-------------+------
L_1 | 20-JUL-2016 | 105
L_1 | 21-JUL-2016 | 117
... | ... | ...
L_1 | 16-MAY-2017 | 103
L_2 | 20-JUL-2016 | 99
L_2 | 21-JUL-2016 | 106
... | ... | ...
L_2 | 16-MAY-2017 | 120
To get:
Location_id | Period | Average_Price
------------+----------+--------------
L_1 | 2 weeks | ...
L_1 | 6 months | ...
L_1 | 1 year | ...
L_2 | 2 weeks | ...
L_2 | 6 months | ...
L_2 | 1 year | ...
Where in "Period", '2 weeks' means 2 weeks from start date (sysdate). And "Average_Price" is the mean value of price across that period.
Thanks! This problem solved. And I cam across an additional one:
There is another table that contains date information :
Location_id | Ex_start_date | Ex_end_date
------------+-----------------+--------------
L_1 | 08-JUN-16 | 30-AUG-16
L_1 | 21-SEP-16 | 25-SEP-16
L_1 | 08-MAY-17 | 12-MAY-17
L_2 | 08-AUG-16 | 21-AUG-16
L_2 | 24-OCT-16 | 29-OCT-16
L_2 | 15-MAR-17 | 19-MAR-17
Beyond "Ex_Start_date" and "Ex_End_date" is 'Non_Ex' period. After I obtain average information of 2 weeks and 6 months period, I would like to I would like to add one more column, to obtain mean price for 'Non_Ex' and 'Ex' conditions as above.
Hopefully, a table as below can be obtained:
Location_id | Period | Ex_Condition | Average_Price
------------+----------------+----------------------------------
L_1 | 2 weeks | Ex period | ...
L_1 | 2 weeks | Non-Ex period | ...
L_1 | 6 months | Ex period | ...
L_1 | 6 months | Non-Ex period | ...
L_2 | 2 weeks | Ex period | ...
L_2 | 2 weeks | Non-Ex period | ...
L_2 | 6 months | Ex period | ...
L_2 | 6 months | Non-Ex period | ...
The average price will return 'null' if there is no dates falling in EX Period or Non-Ex Period.
And how can I make it happen? Thanks!
You could do it like this:
select location_id,
period,
sum(in_period * price) / nullif(sum(in_period), 0) as avg_price
from (select location_id,
price,
period,
case when mydate - days < sysdate then 1 else 0 end in_period
from localprice,
( select '2 weeks' as period, 14 as days from dual
union
select '6 months', 183 from dual
) intervals
) detail
group by location_id,
period
Replace localprice with the name of your table (you did not provide its name in your question).
Replace mydate with the actual name of your date column. I don't expect you called it date, as that is a reserved word and would require you to always quote it -- don't do that: choose another name.
dual is a standard object available in Oracle, which can be used to introduce rows in a query - rows which you don't have in a table somewhere.
Alternatively, you could create a table with all periods that interest you (2 weeks, 4 weeks, ..., together with the number of days they represent) and use that instead of the union select on dual.
Here is an SQL fiddle. Note that it runs on Postgres, because the Oracle instance is not available at this moment. For that reason I created dual explicitly and used current_date instead of sysdate. But for the rest it is the same.
NOT TESTED because OP didn't provide input data in usable format.
You probably want something along the lines of
select location_id, '2 weeks' as period, avg(price) as average_price
from base_table
where price is not null
and
"date" between SYSDATE and SYSDATE + 13
-- or however you want to define the two week interval
group by location_id
union all
select location_id, '6 months' as period, avg(price) as average_price
from base_table
where price is not null
and
"date" between SYSDATE and add_months(SYSDATE, 6) - 1
-- or however you want to define the six month interval
group by location_id
;
Note that date is a reserved Oracle keyword which should not be used as a column name; if you do, you'll have to use double-quotes, match case (upper and lower) exactly, and you may still run into various problems later. Better to only use table and column names that are not reserved words.
This is a re-phrased version of the #trincot answer. It should be faster over a bigger dataset.
Rows which are unwanted are skipped, not zeroed and used. You won't get a result row any more if there no localprice which match the intervals criteria.
It still only scans localprice once unlike the #mathguy answer.
If the real local price has a highly selective index on date then it can be used.
Un-commenting the line in the WHERE clause will help discard lines early i.e. before the intervals table is considered. The ORDERED hint may well be unnecessary in real life but it demonstrates the correct explain plan when using this line with this data.
Use UNION ALL rather that UNION when gluing rows which are going to be unique.
As usual, don't believe any answer until you've proved it in your circumstances.
WITH
localprice AS
( SELECT 'L_1' Location_id, TO_DATE('20-JUN-2016') "DATE", 105 Price FROM DUAL
UNION ALL
SELECT 'L_1' Location_id, TO_DATE('16-MAY-2017') "DATE", 103 Price FROM DUAL
UNION ALL
SELECT 'L_2' Location_id, TO_DATE('20-JUN-2016') "DATE", 99 Price FROM DUAL
UNION ALL
SELECT 'L_2' Location_id, TO_DATE('16-MAY-2017') "DATE", 120 Price FROM DUAL
),
intervals AS
( SELECT '2 weeks' AS period, 14 AS days FROM dual
UNION ALL
SELECT '6 months', 183 FROM dual
)
SELECT /*+ ORDERED */
location_id, period,
AVG(price) AS avg_price
FROM
localprice
CROSS JOIN
intervals
WHERE "DATE" >= SYSDATE - days
-- AND "DATE" >= SYSDATE - (SELECT MAX(days) FROM intervals)
GROUP BY location_id, period

How do I relate a table of events to a table of intervals?

I need to merge two tables based on overlapping time data, and I don't know how to do this in SQL. I have a table of events and times, such as this:
Event_Table
+----------------+-------+
| Event | Time |
+----------------+-------+
| Fire Alarm | 10:00 |
| Smoke Alarm | 13:00 |
| Security Alarm | 16:00 |
+----------------+-------+
I also have a table of time intervals, such as this:
Interval_Table
+--------+-------------+-----------+
| Warden | Shift_Start | Shift_End |
+--------+-------------+-----------+
| Jack | 09:00 | 10:30 |
| John | 14:00 | 20:00 |
+--------+-------------+-----------+
I need to make a table of events which includes which warden was on duty at the time:
Output_Table
+----------------+-------+----------------+
| Event | Time | Warden_On_Duty |
+----------------+-------+----------------+
| Fire Alarm | 10:00 | Jack |
| Smoke Alarm | 13:00 | [null] |
| Security Alarm | 16:00 | John |
+----------------+-------+----------------+
Some Warden shifts might overlap, but that should be ignored; maximum one warden name should be displayed for every event. The tables are very large (~500,000 rows). Any ideas on how this can be achieved with SQL?
Here is one way to do this. Notice how I posted consumable ddl and sample data? You should do this in the future. It makes it a LOT easier to help. Most of time on this was setting up the problem. The query itself was a trivial effort.
if OBJECT_ID('tempdb..#Event') is not null
drop table #Event
create table #Event
(
EventName varchar(20)
, EventTime time
)
insert #Event
select 'Fire Alarm', '10:00' union all
select 'Smoke Alarm', '13:00' union all
select 'Security Alarm', '16:00'
if OBJECT_ID('tempdb..#Shifts') is not null
drop table #Shifts
create table #Shifts
(
Warden varchar(10)
, StartTime time
, EndTime time
)
insert #Shifts
select 'Jack', '09:00', '10:30' union all
select 'John', '14:00', '20:00' union all
select 'overlap', '15:00', '22:00';
with SortedResults as
(
select *
, ROW_NUMBER() over (partition by e.EventName order by s.StartTime) as RowNum
from #Event e
join #Shifts s on s.StartTime <= e.EventTime and s.EndTime >= e.EventTime
)
select *
from SortedResults
where RowNum = 1
Try this:
select
Event,
Time,
(select top 1 Warden from Interval_Table where Time between Shift_Start and Shift_End) as Warden_On_Duty
from Event_Table