0

我相信您可以从这个问题中看出,我对 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

4 回答 4

2
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))
    )  
于 2013-09-04T20:26:24.973 回答
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
于 2013-09-04T20:29:09.270 回答
0

做一个 case 语句,并把它放在你的 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
于 2013-09-04T20:43:25.310 回答
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))
)  
于 2013-09-04T21:01:06.820 回答