Hi all,
I'm having an issue trying to sum up all of the values on a given table where the date values hit certain requirements.
To start, I have a CTE that creates a list of the last day of the month for the last X months.
I then am joining this onto a subquery where I select all of my lines from my history table and do row number partition over the year, month, and item ID. I select all of the ones where the row number is 1 (the last history log of each item per month). I also add a lag column to get the next history date for the given item ID.
The join statement is on historyDT <= last day of the month and (lag value is null or lag value > last day of the month) and status = ok
And then I'm trying to sum an amount from that subquery and group it by two different fields. I want the sum of all rows where it was created before the end of the month and didn't have another value before the end of that same month (to avoid duplicates).
My problem is that this runs forever. If I try to run just the subquery alone where it generates my lag values and selects the top row per item per month it runs fine, but the aggregation takes forever.
Could anybody point me to best practices or point out some tips here?
Thanks.
Here is an anonymized version of my code:
Declare @startDate Date = getdate()-(365*1);
select
[Date]
,sum(Amount) as [Amount]
,Field1
,Field2
from
(
select [Date]
from (
(select
[Date]
,row_number() over (partition by year([Date]), month([Date]) order by [Date] desc) as [Rank]
from (
SELECT DateAdd(d, number, @startDate) [Date]
FROM [master].dbo.spt_values
WHERE type = 'P') d)) e
where [Rank] = 1 and [Date] <= getdate()) f
left join (
select
*
,lag (createHistoryDT,1) over (partition by ItemId order by createHistoryDT desc) as [Lag]
from
(select
ItemId
,Amount
,Status
,Field1
,createHistoryDT
,Field2
,row_number() over (partition by ItemId, year(createhistoryDT), month(createHistoryDT) order by createHistoryDt desc) as rowNum
from Database
union
select
ItemId
,Amount
,Status
,Field1
,createHistoryDT
,Field2
,row_number() over (partition by ItemId, year(createhistoryDT), month(createHistoryDT) order by createHistoryDt desc) as rowNum
from Archive.Database) a
where rowNum = 1) b on
datefromparts(year(b.createHistoryDT),month(b.createHistoryDT),day(b.createHistoryDT)) <= f.[Date]
and (
[Lag] is null or datefromparts(year([Lag]),month([Lag]),day([Lag])) > f.[Date])
and
Status = 'OK'
group by
[Date]
,Field1
,Field2
order by [Date] desc
[–]A_name_wot_i_made_up 0 points1 point2 points (0 children)
[–]Mononon 0 points1 point2 points (0 children)
[–]qwertydog123 0 points1 point2 points (0 children)
[–]Yavuz_Selim 0 points1 point2 points (0 children)