2014-02-09 107 views
0

我在这里有一个复杂的查询,我在这里嵌套子查询的情况。我无法获得正确的结构。这里是我的代码:使用Subquery Sql语句的嵌套Case语句的正确结构是什么?

select 
    AccountNo, 
    Case when Datepart (month,TranDate) = 1 Then 
    Case ISNULL(RemainingBalance,'NULLVALUE') 
    When 'NULLVALUE' Then 
    (select top 1 RemainingBalance From tempAccountBalance 
    where DATEPART (YEAR,TranDate)[email protected] 
    order by TranDate desc) 
    else 
    MIN(Case when Datepart (month,TranDate) <= 3 Then 
    RemainingBalance END) End Q1 
FROM tempAccountBalance 
WHERE Datepart (year,TranDate) = @FiscalYear and [email protected] 
Group By AccountNo 

我得到它说的错误,Msg 102, Level 15, State 1, Line 11 Incorrect syntax near 'Q1'.

+1

正确缩进或许会更明显地突出了缺失的“END”......你有三个单词“CASE”,只有两个单词“END” - 因此其中一个不会终止。 –

回答

4

如果您缩进代码,你会发现错误像这样更容易(下)。但请注意,您的查询仍存在分组问题 - 您需要将TranDateRemainingBalance添加到GROUP BY,或者在其上使用聚合。我已经采取了以下猜测没有你查询的任何理解:

select 
    AccountNo, 
    Case 
     when Datepart(month,TranDate) = 1 
      Then 
       Case ISNULL(Min(RemainingBalance), 'NULLVALUE') -- Added Min 
        When 'NULLVALUE' 
        Then (select top 1 RemainingBalance From tempAccountBalance 
         where DATEPART (YEAR,TranDate)[email protected] 
         order by TranDate desc) 
        else 
         MIN(
          Case 
           when Datepart (month,TranDate) <= 3 
           Then RemainingBalance 
          END) 
       end -- Missing 
    End Q1 
FROM tempAccountBalance 
WHERE Datepart(year,TranDate) = @FiscalYear and [email protected] 
Group By AccountNo, Datepart(month,TranDate); -- Added to Group By 
+0

非常感谢。它实际上工作。我将重新编辑我的问题以添加一些后续步骤。 –

3

您需要的Q1之前END

select 
AccountNo, 
Case when Datepart (month,TranDate) = 1 Then 
Case ISNULL(RemainingBalance,'NULLVALUE') 
When 'NULLVALUE' Then 
(select top 1 RemainingBalance From tempAccountBalance 
where DATEPART (YEAR,TranDate)[email protected] 
order by TranDate desc) 
else 
MIN(Case when Datepart (month,TranDate) <= 3 Then 
RemainingBalance END) End End Q1 
FROM tempAccountBalance 
WHERE Datepart (year,TranDate) = @FiscalYear and [email protected] 
Group By AccountNo 
0

我想指出的是,你不需要嵌套case报表的查询:

select AccountNo, 
     (Case when Datepart(month, TranDate) = 1 and 
        RemainingBalance is null 
      Then (select top 1 RemainingBalance 
        From tempAccountBalance 
        where DATEPART(YEAR, TranDate) = @FiscalYear-1 
        order by TranDate desc 
       ) 
      when Datepart(month, TranDate) = 1 
      then MIN(Case when Datepart(month, TranDate) <= 3 Then RemainingBalance END) 
     End) as Q1 
FROM tempAccountBalance 
WHERE Datepart(year,TranDate) = @FiscalYear and [email protected] 
Group By AccountNo;