I am working on a query that would provide maximum values per record over the past month, 6 months, and 9 months.
There is a one-to-many relationship between the table containing the records and the one containing the values.
There are about 1200 records to get these values for.
I've tried this a couple different ways.
First, I tried a case statement:
select table1.recordID,
max(case when table2.date_val > dateadd(d,-30,getdate()) then table2.value end) as val30,
max(case when table2.date_val > dateadd(d,-90, getdate()) then table2.value end) as val90,
max(case when table2.date_val > dateadd(d,-180, getdate()) then table2.value end) as val180
from table1 inner join table2 on table1.recordID = table2.recordID
This takes 43 seconds to pull just the Top 5.
I've also tried joining seperate subqueries:
select table1.recordID, q30.val30, q90.val90, q180.val180
from table1 inner join
(select recordID, max(value) from table2 where date_val > dateadd(d,-30,getdate()
group by recordID) q30
on table1.recordID = q30.recordID
etc...
and that's shorter, but still takes way too long (almost 2 minutes for everything).
When the subqueries are run individually (not joined, but with a where clause like: table2.recordID IN(select distinct recordID from table1)
they all run in 15-20 seconds. Much better, but I have 3 seperate data sets.
Any ideas??
There is a one-to-many relationship between the table containing the records and the one containing the values.
There are about 1200 records to get these values for.
I've tried this a couple different ways.
First, I tried a case statement:
select table1.recordID,
max(case when table2.date_val > dateadd(d,-30,getdate()) then table2.value end) as val30,
max(case when table2.date_val > dateadd(d,-90, getdate()) then table2.value end) as val90,
max(case when table2.date_val > dateadd(d,-180, getdate()) then table2.value end) as val180
from table1 inner join table2 on table1.recordID = table2.recordID
This takes 43 seconds to pull just the Top 5.
I've also tried joining seperate subqueries:
select table1.recordID, q30.val30, q90.val90, q180.val180
from table1 inner join
(select recordID, max(value) from table2 where date_val > dateadd(d,-30,getdate()
group by recordID) q30
on table1.recordID = q30.recordID
etc...
and that's shorter, but still takes way too long (almost 2 minutes for everything).
When the subqueries are run individually (not joined, but with a where clause like: table2.recordID IN(select distinct recordID from table1)
they all run in 15-20 seconds. Much better, but I have 3 seperate data sets.
Any ideas??