简体   繁体   English

T-SQL选择一段时间返回结果

[英]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). 我有一个表事务(transaction_ID,transaction_Person_ID,Transaction_Date等)。 What i want is to return all the transaction_person_ID's that have more than 3 transactions per week for the last year. 我想要返回的是过去一年每周有3笔以上交易的所有transaction_person_ID。 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 这意味着我必须检查1-1-10至7-10-10以查看某人一周内是否进行了3次以上交易,然后检查2-1-10至8-10-10等。到目前为止是

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_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 目前我还没有ms-sql实例,因此我无法测试,但是一旦纠正了不可避免的语法错误,它就可以完成您想要的操作

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! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM