2014-07-17 77 views
0

我試圖根據2個案例選擇產生付款日期。 第一個是確定付款時間表,第二個是確定付款日期/日期。SQL嵌套案例選擇執行日期操作

我也加入了2個表格,第一個包含實際記錄,第二個包含付款時間表。他們都被客戶#加入。

這裏是我的代碼迄今:

Select comp, cust, data.inv, dat, amt, rel.PaymentSchedule, rel.PaymentDay, 
case rel.PaymentSchedule when 'BiMonthly' then 
    case rel.PaymentDay when '1' then DATEADD(MM, 2, dat) end 
    else 
    case rel.PaymentDay when '2' then DATEADD(MM, 2, dat) end 
else if 
    rel.PaymentSchedule when 'Daily' then 
    case rel.PaymentDay when '30' then DATEADD(MM, 1, dat) end 
    else 
    case rel.PaymentDay when '47' then DATEADD(dd, 47, dat) end 

end as PayDate 


from 
(
select b.ASCOMP as comp, b.ASCUST as cust, b.ASINV# as inv, b.ASIDAT as dat, b.ASINAM as amt 
from SOLARSOFT.BNDSYS02.IVPDAT.AROHT a 
right JOIN SOLARSOFT.BNDSYS02.IVPDAT.AROP b 
    on a.ASINV# = b.ASINV# 
where 
    a.ASINV# is null 
) as data 
inner join tbl_payRel rel on cust = rel.Customer# 
where 
    (inv not like 'D%') 
    and (inv not like 'P%') 
and (cust <> 1308) 
and (cust <> 1067) 
and (cust <> 1295) 

order by rel.PaymentSchedule, rel.PaymentDay, cust 

問題: 消息156,級別15,狀態1,行7 關鍵字 '其他' 附近有語法錯誤。 消息4145,級別15,狀態1,行8 在'when'附近預期條件的上下文中指定的非布爾類型表達式。 Msg 156,Level 15,State 1,Line 24 關鍵字'as'附近的語法不正確。

我哪裏出錯了?一直在努力超速駕駛!

我感謝您的幫助!

+1

請告訴我你的問題?查詢可以稍微清理一下(並且不在(1308,1067,1295)中的cust將與where子句中的三行執行相同的操作)。不知道你是否需要子查詢。 – Twelfth

+0

謝謝,忘了添加我收到的錯誤,並且我會根據您的建議更新我的聲明。 –

+0

我想你是混合語言....我不認爲否則如果在案件陳述中有效。實際上,這種情況下的聲明通常很雜亂 – Twelfth

回答

1

關注這個片段:

case rel.PaymentSchedule when 'BiMonthly' then 
case rel.PaymentDay when '1' then DATEADD(MM, 2, dat) end 
else 
case rel.PaymentDay when '2' then DATEADD(MM, 2, dat) end 
else if 
rel.PaymentSchedule when 'Daily' then 
case rel.PaymentDay when '30' then DATEADD(MM, 1, dat) end 
else 
case rel.PaymentDay when '47' then DATEADD(dd, 47, dat) end 

end as PayDate 

只是一對夫婦的意見......前兩個語句計算出相同的,是故意的嗎?爲什麼將這個嵌套爲兩個案例?這可能是一個聲明:

case rel.paymentday 
    when '1' then DATEADD(MM, 2, dat) 
    when '2' then DATEADD(MM, 2, dat) 
    when '30' then DATEADD(MM, 1, dat) 
    when '47' then DATEADD(dd, 47, dat) 
end as PayDate 

你不需要結束每個case語句與結束......它們可以根據需要評估多個案件。我使用微軟這個引用時,我can'ty記得的語法副手: http://msdn.microsoft.com/en-us/library/ms181765.aspx

我要補充...你仍然可以嵌套這個,如果你想..

case rel.PaymentSchedule 
    when 'BiMonthly' then 
    case rel.PaymentDay when 1 then DATEADD(MM, 2, dat) 
         when 2 then DATEADD(MM, 2, dat) 
    end 
    when 'Daily' then 
    case rel.PaymentDay when '30' then DATEADD(MM, 1, dat) 
         when '47' then DATEADD(dd, 47, dat) 
    end 
end 
+1

'BiMonthly'條件僅適用於原始查詢中'WHEN rel.PaymentDay ='1'',這就是爲什麼前兩種情況具有相同的公式:第一種情況適用於'BiMonthly',第二個含蓄地指向'Monthly'(也就是在最後一個查詢中你有'when 2 then * then *') – Serpiton

+0

ty @Serpiton,回答編輯 – Twelfth

+0

感謝一幫人!我會試試這個! –