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
4

3 回答 3

3

在 case 语句的 THEN 部分中不能有多个字段。您可以使用相同的逻辑来构建多个案例语句:

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

等等。

于 2012-09-17T19:33:31.907 回答
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
于 2012-09-17T19:35:52.070 回答
1

案例确实存在。它记录在这里

不过,我认为您的格式可能有点偏离。尝试:

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

我尚未对其进行测试,但这只是我快速查看文档后对格式的看法。

祝你好运!

编辑:看起来像 Lance Ninja'd 我。他的代码更完整,但(部分)证实了我的想法。

于 2012-09-17T19:58:24.393 回答