嵌套案例陈述

时间:2013-09-04 08:44:04

标签: sql-server if-statement case

我正在试图通过查询来说明今天何时属于本财政年度(1月11日 - 31月10日),运行这套案例陈述,但今天是在下一个财政年度运行下一组等...

我已经尝试嵌套CASE语句但没有工作。以下只是解释我想要做的事情。

感谢您的期待!

IF Getdate() Between '2012-11-01 00:00' AND '2013-10-31 23:59' -- is it this year?

THEN
        CASE
         WHEN B.saledate Between '2011-11-01 00:00' AND Getdate()-365 THEN 'Yes'
         WHEN B.saledate Between '2012-11-01 00:00' AND Getdate() THEN 'Yes'
        Else 'No'
        AS 'Financial year to date',
        END

IF Getdate() Between '2013-11-01 00:00' AND '2014-10-31 23:59' -- is it this year yet?
THEN
        CASE
         WHEN B.Created Between '2011-11-01 00:00' AND Getdate()-730 THEN 'Yes'
         WHEN B.Created Between '2012-11-01 00:00' AND Getdate()-365 THEN 'Yes'
         WHEN B.Created Between '2013-11-01 00:00' AND Getdate() THEN 'Yes'
        Else 'No'
        AS 'Financial year to date',
        END

END

2 个答案:

答案 0 :(得分:0)

这样你最终会得到越来越多的代码。

要获得某个会计年度,oyu可以尝试:

DECLARE @DateToCheck AS DATETIME

SET @DateToCheck = '20130101'

SELECT YEAR(DATEADD(mm,-10,@DateToCheck))

因此,如果您的表Transactions具有DateTime字段TransactionDate

SELECT YEAR(DATEADD(mm,-10,TransactionDate))
FROM   Transactions

将为您提供每笔交易的会计年度。

答案 1 :(得分:0)

感谢您的帮助,但这是迄今为止财务年度的关键,而不仅仅是财政年度。

按以下方式解决。它确实意味着每年增加一个新的块,但这就是我现在所处的位置。

CASE
         WHEN 
         Getdate() Between '2012-11-01 00:00' AND '2013-10-31 23:59' AND
         (
         cast(convert(char(11), B.Created, 10) as datetime) Between '2009-11-01 00:00' AND (cast(getdate()-1096 as date)) OR
         cast(convert(char(11), B.Created, 10) as datetime) Between '2010-11-01 00:00' AND (cast(getdate()-731 as date)) OR
         cast(convert(char(11), B.Created, 10) as datetime) Between '2011-11-01 00:00' AND (cast(getdate()-366 as date)) OR
         cast(convert(char(11), B.Created, 10) as datetime) Between '2012-11-01 00:00' AND (cast(getdate() as date))
         )
         THEN 'Yes' 

         WHEN Getdate() Between '2013-11-01 00:00' AND '2014-10-31 23:59' AND
         (
         cast(convert(char(11), B.Created, 10) as datetime) Between '2009-11-01 00:00' AND (cast(getdate()-1461 as date)) OR
         cast(convert(char(11), B.Created, 10) as datetime) Between '2010-11-01 00:00' AND (cast(getdate()-1096 as date)) OR
         cast(convert(char(11), B.Created, 10) as datetime) Between '2011-11-01 00:00' AND (cast(getdate()-731 as date)) OR
         cast(convert(char(11), B.Created, 10) as datetime) Between '2012-11-01 00:00' AND (cast(getdate()-366 as date)) OR
         cast(convert(char(11), B.Created, 10) as datetime) Between '2013-11-01 00:00' AND (cast(getdate() as date))
         )
         THEN 'Yes'

Else 'No'
END
AS 'Financial year to date',