T-SQL Select returning results for a period of time
I have tried but i am not able to figure this out. I have a table transactions (transaction_ID, transaction_Person_ID, Transaction_Date etc). What i want is to return all the transaction_person_ID's that have more than 3 transactions per week for the last year. That means i have to check for 1-1-10 to 7-10-10 to see if someone had more than 3 transactions that week, then for 2-1-10 to 8-10-10 etc etc. What i have written so far is this
WITH Dates AS (
SELECT
[Date] = CONVERT(DATETIME,'01/01/2010')
UNION ALL SELECT
[Date] = DATEADD(DAY, 1, [Date])
FROM
Dates
WHERE
Date < '12/31/2010'
)
SELECT transaction_person_开发者_StackOverflow中文版Id FROM transactions
JOIN DATES
ON transactions.transaction_date = dates.date
where transactions.Transaction_Date between dateadd(DAYOFYEAR,-7,dates.date) and dates.date
group by transaction_person_Id
having count(transaction_person_ID) >= 4
OPTION (MAXRECURSION 2000)
Thanks
I haven't got an instance of ms-sql to hand at the moment so I cant test this however it should do what you want once the inevitable syntax errors have been corrected
select
transaction_person_ID
from
(
select
transaction_person_Id,
count(transaction_person_id),
datepart(wk,Transaction_date)
from
transactions
Where
Transaction_date > dateadd(d,-datepart(dy,getdate())+1,getdate())
group by
transaction_person_Id,
datepart(wk,Transaction_date)
having
count(transaction_person_id) >3
) as foo
group by
transaction_person_id
having
count(transaction_person_id) >= datepart(wk,getdate)
Hope that helps!
精彩评论