案例提取多列

时间:2012-09-17 19:26:24

标签: sql-server-2005

我想知道是否有像Case这样的东西,我可以在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

3 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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

我还没有对它进行过测试,但这只是我对文档格式的看法。

祝你好运!

编辑:看起来像兰斯忍者我。他的代码更完整,但确认(部分)我认为是这样的。