2013-12-11 59 views
1

編輯:使查詢更簡單,同樣的問題。使用變量不工作的案例陳述

我基本上有兩個陳述,選擇一個人是否使用給定的帳戶ID和申請期限已故。

當向聯合賬戶持有人輸入一個賬戶時,兩個查詢(pr和jo)返回值以及case語句中顯示的正確指標。

當第二個查詢沒有返回任何值(因爲沒有聯合賬戶持有人被指示存活或死亡),那麼case語句似乎不起作用並且不返回任何值。

爲什麼會發生這種情況,我怎麼才能讓case語句仍然返回一個值,即使第二個表不會返回一個值?

謝謝!

SELECT 
CASE 
      WHEN pr.fintPriDeceased=0 and (jo.fintJointDeceased=0 or jo.fintJointDeceased='') 
      THEN 0 
      ELSE 1 
      END AS fintDeceased 
FROM 

(SELECT a.FLNGCUSTOMERKEY as flngPrimaryCustomerKey, 
     a.flngAccountKey as flngPrimaryAccountKey, 
     CASE 
      WHEN ci.fdtmCease<>'12-31-9999' 
      THEN 1 
      ELSE 0 
      END AS fintPriDeceased 
FROM tblAccount a, 
     tblPeriod p, 
     tblCustomerInfo ci 
WHERE a.flngAccountKey = @plngAccountKey and 
     p.fdtmFilingPeriod = @pdtmFilingPeriod and 
     a.flngAccountKey = p.flngAccountKey and 
     a.FLNGCUSTOMERKEY = ci.flngCustomerKey) pr 

(SELECT a.FLNGCUSTOMERKEY as flngJointCustomerKey, 
     p.FLNGACCOUNTKEY as flngJointAccountKey, 
     CASE 
      WHEN ci.fdtmCease<>'12-31-9999' 
      THEN 1 
      ELSE 0 
      END AS fintJointDeceased 
FROM tblAccount a, 
     tblPeriod p, 
     tblCustomerInfo ci 
WHERE p.FLNGJOINTACCOUNTKEY = @plngAccountKey and 
     p.fdtmFilingPeriod  = @pdtmFilingPeriod and 
     a.flngAccountKey  = p.flngAccountKey and 
     a.FLNGCUSTOMERKEY  = ci.flngCustomerKey) jo 
+1

是這個sql服務器? –

+0

-1:這個查詢很混亂,我不驚訝它不起作用。對不起,但我相信這是無法解決的。 – rsenna

+0

p.FLNGJOINTACCOUNTKEY引用的列的數據類型是什麼? – poke

回答

0

由於您最後的評論說,「公關總是被填充,聯辦有時不是」 ...
這意味着你需要一個LEFT OUTER JOIN(可選連接)兩者之間...
要求使你的JOIN明確:你必須有一個ON條款,明確說明哪些列被等同/比較。

然後,您還需要在您的CASE聲明中檢查IS NULL,因爲沒有找到聯合帳戶時。

SELECT 
CASE 
      WHEN pr.fintPriDeceased=0 
      and  (jo.fintJointDeceased IS NULL 
        OR jo.fintJointDeceased=0) 
      THEN 0 
      ELSE 1 
      END AS fintDeceased 

FROM 
(SELECT a.FLNGCUSTOMERKEY as flngPrimaryCustomerKey, 
     a.flngAccountKey as flngPrimaryAccountKey, 
     CASE 
      WHEN ci.fdtmCease<>'12-31-9999' 
      THEN 1 
      ELSE 0 
      END AS fintPriDeceased 
FROM tblAccount a, 
     tblPeriod p, 
     tblCustomerInfo ci 
WHERE a.flngAccountKey = @plngAccountKey and 
     p.fdtmFilingPeriod = @pdtmFilingPeriod and 
     a.flngAccountKey = p.flngAccountKey and 
     a.FLNGCUSTOMERKEY = ci.flngCustomerKey) pr 

LEFT OUTER JOIN 
(SELECT a.FLNGCUSTOMERKEY as flngJointCustomerKey, 
     p.FLNGACCOUNTKEY as flngJointAccountKey, 
     CASE 
      WHEN ci.fdtmCease<>'12-31-9999' 
      THEN 1 
      ELSE 0 
      END AS fintJointDeceased 
FROM tblAccount a, 
     tblPeriod p, 
     tblCustomerInfo ci 
WHERE p.FLNGJOINTACCOUNTKEY = @plngAccountKey and 
     p.fdtmFilingPeriod  = @pdtmFilingPeriod and 
     a.flngAccountKey  = p.flngAccountKey and 
     a.FLNGCUSTOMERKEY  = ci.flngCustomerKey) jo 
ON pr.flngPrimaryCustomerKey = jo.flngJointCustomerKey 
AND pr.flngPrimaryAccountKey = jo.flngJointAccountKey 

(您可能需要改變這種ON條款,在LEFT OUTER底部上方加入...我不知道,如果你都和customerkey一般accountkey匹配,在2個選擇之間。)

希望有幫助!