SQL:过滤具有多个条件的查询

时间:2013-09-04 20:20:07

标签: sql sql-server

我相信你能从这个问题中分辨出来,我很新,不熟悉SQL。经过一段时间(以及这个精彩网站的一些帮助),我能够创建一个几乎完全列出我想要的查询:

Select p1.user.Office, 
p1.user.Loc_No, 
p1.user.Name, 
p1.user.Code, 
p1.user.Default_Freq, 
(Select distinct MAX(p2.pay.Paycheck_PayDate) 
from p2.pay
where p1.user.Client_TAS_CL_UNIQUE = p2.pay.CL_UniqueID) as Last_Paycheck

from
PR.client 

where 
p1.user.Client_End_Date is null
and p1.user.Client_Region = 'Z'
and p1.user.Client_Office <> 'ZF'
and substring(p1.user. Code,2,1) <> '0'

现在我只需要使用以下逻辑稍微过滤一下:

如果Default_Freq ='W',则仅输出Last_Paycheck客户端超过当前日期7天或更多天

如果Default_Freq ='B',则仅输出Last_Paycheck客户端超过当前日期14天或更多天

等等,

我知道这是可能的,但我不知道语法应该如何开始。我相信我需要在Where子句中使用Case语句?任何帮助都会一如既往地受到高度赞赏!

4 个答案:

答案 0 :(得分:1)

SELECT

X.p1.user.Office, 
X.p1.user.Loc_No, 
X.p1.user.Name, 
X.p1.user.Code, 
X.Default_Freq, 
X.Last_Paycheck

FROM

(Select 
p1.user.Office, 
p1.user.Loc_No, 
p1.user.Name, 
p1.user.Code, 
p1.user.Default_Freq AS Default_Freq, 
(Select distinct MAX(p2.pay.Paycheck_PayDate) 
from p2.pay
where p1.user.Client_TAS_CL_UNIQUE = p2.pay.CL_UniqueID) as Last_Paycheck

from
PR.client 

where 
p1.user.Client_End_Date is null
and p1.user.Client_Region = 'Z'
and p1.user.Client_Office <> 'ZF'
and substring(p1.user. Code,2,1) <> '0') X
WHERE (
      (X.Default_Freq = 'W' AND (DATEDIFF ( d , X.Last_Paycheck , @currentDate) >= 7))
      OR (X.Default_Freq = 'B' AND (DATEDIFF ( d , X.Last_Paycheck , @currentDate) >= 14))
    )  

答案 1 :(得分:0)

将当前查询用作派生表或CTE(SQL Server 2005+存在CTE)。然后你就可以做到:

;WITH CTE AS
(
    --- Your current query here
)
SELECT *
FROM CTE
WHERE (Default_Freq = 'W' AND DATEDIFF(DAY,Last_Paycheck,GETDATE()) >= 7)
OR (Default_Freq = 'B' AND DATEDIFF(DAY,Last_Paycheck,GETDATE()) >= 14)
OR () -- keep going

答案 2 :(得分:0)

制作一个案例陈述,并将其放在你的where子句中。

即。 (脱离我的头顶):

CASE 
  WHEN (Default_Freq = 'W' AND DATEDIFF(DAY,Last_Paycheck,GETDATE()) >= 7) THEN 1
  WHEN (Default_Freq = 'B' AND DATEDIFF(DAY,Last_Paycheck,GETDATE()) >= 14) THEN 1
ELSE 0 END = 1

答案 3 :(得分:0)

使用内部查询尝试此操作:

select * from (
  Select 
    p1.user.Office, 
    p1.user.Loc_No, 
    p1.user.Name, 
    p1.user.Code, 
    p1.user.Default_Freq, 
    (Select distinct MAX(p2.pay.Paycheck_PayDate) 
     from p2.pay
     where p1.user.Client_TAS_CL_UNIQUE = p2.pay.CL_UniqueID) as Last_Paycheck
  from PR.client 
  where p1.user.Client_End_Date is null
    and p1.user.Client_Region = 'Z'
    and p1.user.Client_Office <> 'ZF'
    and substring(p1.user. Code,2,1) <> '0') t
where (
     (Default_Freq = 'W' AND (DATEDIFF ( d , Last_Paycheck , @currentDate) <= 7))
  OR (Default_Freq = 'B' AND (DATEDIFF ( d , Last_Paycheck , @currentDate) <= 14))
)