用于跳过周末日的条件SQL日期参数

时间:2018-05-23 18:19:53

标签: sql-server tsql date conditional

SQL新手,我完全迷失了。尝试编写一个查询来拉开新帐户,在前一天开放,这可以很容易地在周二到周五。但是星期一它正在拉着星期天,而我所尝试的一切都是错误的。

这是我最接近的,但在最后一行仍然是错误的。我想我正在尝试应用excel vba类型的逻辑,它只是不喜欢我。有人可以看一看吗?

谢谢!

SELECT
    PortfolioCode as "Account", 
    f.reportheading1 as "Name", 
    d.portfoliostatus as "Status", 
    e.investmentstrategy as "Strategy",
    e.brokersource as "Broker", 
    e.referringfirm as "RefBy", 
    e.custodian as "Bank",
    e.manager as "Manager", 
    e.administrator as "APM", 
    d.initialvalue as "Open Value", 
    b.StartDate as "Start Date", 
    e.percentcash as "Cash%", 
    e.targetmvequity as "Eqt Trgt", 
    e.targetmvfixed as "FI Trgt", 
    e.munistrategy as "Muni Strat", 
    e.nationalmuni as "Nat. Muni", 
    e.statemunistrategy as "State Strat.", 
    e.residency as "Residency"
FROM
    AdvPortfolioBaseExt as A
INNER JOIN
    AdvPortfoliobase AS B ON A.PortfolioBaseID = b.PortfolioBaseID
INNER JOIN
    advportfolio AS C ON A.PortfolioBaseID = c.PortfolioID
INNER JOIN
    advapp.vportfolio AS D ON A.PortfolioBaseID = D.PortfolioID
INNER JOIN
    advportfoliobaseext AS E ON A.portfoliobaseid = e.portfoliobaseID
INNER JOIN
    advapp.vportfoliobase AS F ON a.PortfolioBaseID = f.PortfolioBaseID
WHERE 
    c.portfoliostatus <> 'Closed'
    AND IIF(DATEPART(dw, GETDATE()) = 2, b.startdate > GETDATE() - 3, b.startdate > GETDATE()-1)

1 个答案:

答案 0 :(得分:0)

DATEPART(dw)取决于服务器设置DATEFIRST的值。所以,我避免它...

WHERE
    b.startdate
    >=
    getdate() - CASE DATENAME(dw, getdate()) WHEN 'Sunday' THEN 2
                                             WHEN 'Monday' THEN 3
                                                           ELSE 1 END

此外,您的错误是因为IIF()的返回值不能是逻辑比较的结果。它必须返回SQL Server 中存在的类型的标量fvalue(它没有布尔类型)

这是有效的......

WHERE s.startdate >= IIF(x = y, a, b)

这是无效的......

WHERE IIF(x = y, s.startdate >= a, s.startdate >= b)


所以,你写的可能是......

WHERE
  s.startDate > IIF(datepart(dw,getdate()) = 2, getdate()-3, getdate()-1)

但是,如果在周日执行那就错了......