2012-09-17 35 views
0

我想知道是否有類似的情況下,我可以在SQL中獲取SQL Server 2005中使用1個表達式獲取多列。我是SQL中的一名新手。希望它不是太容易,我錯過了它。先謝謝你!!提取多列的案例

Select RD.RepDailyInfoID, RD.TypeofDayID 
Case WHEN RD.TypeofDayID = 1 
THEN 
    isnull(cast(S.AmountSold as numeric(10,2)), 0) as AmountSold, 
    isnull(cast(S.S_AmountCollected as numeric(10,2)), 0) as AmountCollected, 
    S.S_PaymentMethod as PaymentMethod 

When RD.TypeofDayID = 9 
THEN 
    isnull(cast(U.AmountUpgraded as numeric(10,2)), 0) as AmountUpgraded, 
    isnull(cast(U.U_UpgradedCollected as numeric(10,2)), 0) + isnull(cast(U.RenewalCollected as numeric(10,2)), 0) as AmountCollected, 
    U.U_PaymentMethod as PaymentMethod 
END 
from RepDailyInfo RD 
left outer join SellingInfo S on S.RepDailyInfoID = RD.RepDailyInfoID 
left outer join UpgradingInfo U on U.RepDailyInfoID = RD.RepDailyInfoID 
where RepID = @RepID 
+0

只需將您的案例邏輯複製+粘貼到每列 – EplusL

回答

3

在case語句的THEN部分中不能有多個字段。你可以使用相同的邏輯來構建多個case語句:

Case WHEN RD.TypeofDayID = 1 THEN isnull(cast(S.AmountSold as numeric(10,2)), 0) END as AmountSold, 
Case WHEN RD.TypeofDayID = 1 THEN isnull(cast(S.S_AmountCollected as numeric(10,2)), 0) END as AmountCollected 

1

這不是測試,但應該讓你開始。你必須爲每個領域提供一個案例。

select RD.RepDailyInfoID, RD.TypeofDayID 
    , AmountSold = case when RD.TypeofDayID = 1 THEN isnull(cast(S.AmountSold as numeric(10,2)), 0) else 0 end 
    , AmountUpgraded = case when RD.TypeofDatID = 9 THEN isnull(cast(U.AmountUpgraded as numeric(10,2)), 0) else 0 end 
    , AmountCollected = case when RD.TypeofDayID = 1 then isnull(cast(S.S_AmountCollected as numeric(10,2)), 0) else 
       when RD.TypeofDayID = 9 then isnull(cast(U.U_UpgradedCollected as numeric(10,2)), 0) + isnull(cast(U.RenewalCollected as numeric(10,2)), 0) end 
    , PaymentMethod = case when RD.TypeofDayID = 1 then S.S_PaymentMethod else 
       when RD.TypeofDayID = 9 then U.U_PaymentMethod end 
from RepDailyInfo RD 
left outer join SellingInfo S on S.RepDailyInfoID = RD.RepDailyInfoID 
left outer join UpgradingInfo U on U.RepDailyInfoID = RD.RepDailyInfoID 
where RepID = @RepID 
1

事實確實存在。它記錄在here

雖然我認爲你的格式可能有點偏離。嘗試:

SELECT RD.RepDailyInfoID, AmountSold = 
    CASE RD.TypeofDayID 
    WHEN '1' THEN isnull(cast(S.AmountSold as numeric(10,2)), 0) 
    END 
FROM RepDailyInfo RD 
left outer join SellingInfo S on S.RepDailyInfoID = RD.RepDailyInfoID 
left outer join UpgradingInfo U on U.RepDailyInfoID = RD.RepDailyInfoID 
WHERE RepID = @RepID 

我還沒有測試過,但這只是我從快速瀏覽文檔的格式。

祝你好運!

編輯:看起來像蘭斯Ninja'd我。他的代碼更完整,但(部分)證實了我的想法。