2015-08-16 60 views
2

我想獲得一個嵌套case語句來工作,在階段中工作,但現在我嵌套了另一個case語句,它抱怨語法。我看了很多例子,看不出我出錯的地方。使用嵌套Case語句的SQL行到列

我希望實現的是每個PolicyTransactionId(在where子句中設置)的行,每個帳戶代碼都作爲列。這對我來說很合適,因爲錯誤在於添加嵌套條目來查看借記/貸記條目,並在適當的時候將數字轉爲負數。

嘗試到目前爲止附加。

http://sqlfiddle.com/#!6/8db47/3

CREATE TABLE [dbo].[PolicyTransactionSplits](
    [PolicyTransactionSplitId] [int] NOT NULL, 
    [PolicyTransactionId] [int] NOT NULL, 
    [AccountCode] [int] NOT NULL, 
    [AccountDesc] [nvarchar](max) NULL, 
    [TransactionType] [nvarchar](max) NULL, 
    [Amount] [decimal](18, 2) NOT NULL, 
    [Adjusted] [bit] NOT NULL DEFAULT ((0)) 
) 
; 



INSERT INTO PolicyTransactionSplits 
    ([PolicyTransactionSplitId], [PolicyTransactionId], [AccountCode], [AccountDesc], [TransactionType], [Amount], [Adjusted]) 
VALUES 
(1551,1096,1000,'Total Transaction Premium','Debit',50,0), 
(1552,1096,1010,'Total Net Premium','Debit',50,0) 
; 

...

select 
    max(case when AccountCode = 1000 then case when TransactionType = 'Debit' then Amount end else case when AccountCode = 1000 then case when TransactionType = 'Credit' then Amount*-1 end) [Total Transaction Premium] 
    max(case when AccountCode = 1000 then case when TransactionType = 'Debit' then Amount end else case when AccountCode = 1000 then case when TransactionType = 'Credit' then Amount*-1 end) [Total Transaction Premium] 
from PolicyTransactionSplits 
where PolicyTransactionId = 10 
+0

你很小心看起來像一個故意嘗試創建不可讀的代碼。使用適當的發明,用括號分開邏輯語句,然後你會自己發現問題。 – Amit

+0

解決在http://sqlfiddle.com/#!6/8db47/17 –

回答

2

你不需要巢case聲明:

select max(case when AccountCode = 1000 and TransactionType = 'Debit' 
       then amount 
       when AccountCode = 1000 and TransactionType = 'Credit' 
       then Amount * -1 
      end) as [Total Transaction Premium], 
     max(case when AccountCode = 1000 and TransactionType = 'Debit' 
       then Amount 
       when AccountCode = 1000 and TransactionType = 'Credit' 
       then Amount * -1 
      end) as [Total Transaction Premium] 
from PolicyTransactionSplits 
where PolicyTransactionId = 10; 

你爲什麼都在重複着同樣的邏輯,我不清楚。也許你只是想要這個:

select max(case when TransactionType = 'Debit' 
       then amount 
       when TransactionType = 'Credit' 
       then Amount * -1 
      end) as [Total Transaction Premium] 
from PolicyTransactionSplits 
where PolicyTransactionId = 10 and AccountCode = 1000; 
+0

謝謝Gordon,頂端正是我所需要的(完全有道理,但無法到達那裏)。重複邏輯是複製/粘貼錯誤。每筆交易在不同的賬戶代碼/賬戶下有20多行。我只是試圖簡化它來得到答案,而不是給我整個程序。 –

1

你,因爲你錯過了2個end語句,並在第一行的最後一個逗號得到一個語法錯誤,但你沒有按邏輯也沒什麼意義,因爲它是這樣的:

case when AccountCode = 1000 then 
    case when TransactionType = 'Debit' then Amount end 
else 
    case when AccountCode = 1000 then 
    case when TransactionType = 'Credit' then Amount*-1 end 
    end 
end 

Yo你將永遠不會進入第二部分,因爲AccountCode = 1000是兩種情況下的標準。也許你在找這個?

case when AccountCode = 1000 then 
    case when TransactionType = 'Debit' then Amount 
     when TransactionType = 'Credit' then Amount*-1 
    end 
end