1

我有以下代码,但不想多次引用表 @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
*/

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

谢谢

约翰

4

1 回答 1

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
于 2013-08-15T12:48:23.107 回答