有可能重构这个SQL吗?

时间:2013-08-15 10:55:12

标签: sql sql-server refactoring

我有以下代码,但是我不想多次引用表@test及其基本where子句,我尝试用ROWCOUNT重构它,但无法解决它。

select * 
from @test2
where userid = @userid
    and (
        ExpiryDate > getdate() 
            or 
        not exists(select * from @test2 
                       where userid = @userid 
                         and ExpiryDate > Getdate() 
                         and Status = 40)
        )

这是我用于测试的数据:

declare @test2 table(ID int, ExpiryDate datetime, userid int, siteid int, Status int)
insert into @test2 (ID, ExpiryDate, userid, siteid, Status)
--not expired/status=40 and not status=40 entries
select 1, '2013-08-16', 1, 1, 40
union
select 2, '2013-08-16', 1, 1, 10
union
--not expired/status=40 and status=40 entries
select 3, '2013-08-16', 2, 2, 40 
union
select 4, '2013-08-16', 2, 2, 40
union
--expired/status=40 and not status=40 entries
select 5, '2013-08-13', 3, 3, 40
union
select 6, '2013-08-16', 3, 3, 10
union
--expired/status=40 and status=40 entries
select 7, '2013-08-13', 4, 4, 40
union
select 8, '2013-08-16', 4, 4, 40
union
--not expired/status=40 single entry
select 9, '2013-08-16', 5, 5, 40
union
--expired/status=40 single entry
select 10, '2013-08-13', 6, 6, 40


/* scenarios:
not expired/status=40 and not status=40 entries - sees both     - userid = 1
not expired/status=40 and status=40 entries     - sees both     - userid = 2
expired/status=40 and not status=40 entries     - sees both     - userid = 3
expired/status=40 and status=40 entries         - sees single   - userid = 4
not expired/status=40 single entry                  - sees single   - userid = 5
expired/status=40 single entry                      - sees single   - userid = 6
*/

我甚至不确定是否有可能重构这一点。任何有任何想法如何改善这一点的人都会非常感激。

由于

约翰

1 个答案:

答案 0 :(得分:1)

请尝试以下操作:

;with cte as (
    select ID, ExpiryDate, userid, siteid, Status,
        notExp = case when ExpiryDate > getdate() then 1 end,
        notExp_st40 = sum(case when ExpiryDate > getdate() and Status = 40 then 1 end) over()
    from @test2 
    where userid = @userid
)
select ID, ExpiryDate, userid, siteid, Status
from cte
where notExp=1 or notExp_st40 is NULL