【问题标题】:How to use CASE Statement for Multiple Select Statements in SQL如何在 SQL 中对多选语句使用 CASE 语句
【发布时间】:2017-09-26 10:51:29
【问题描述】:

我有 3 个名为 VendorCustomersReceivePayment 的表。在我的ReceivePayment 表中,我有名为PaymentTypeAccountID 的列。我想要的只是在ReceivePayment 表中使用AccountID 从供应商或客户表中选择数据,但我必须应用条件从客户表或供应商表中选择数据,条件将基于@987654335 的PaymentType 列@ 桌子。比如如果我在PaymentType 列中有“销售”,那么它应该从客户表中选择数据,或者如果我在 PaymentType 列中有“购买”,那么它应该从供应商表中选择数据。

我正在使用 case 语句,但我不知道如何在 case 语句的 THEN 子句中使用 Select 语句。

我正在尝试使用此代码

    SELECT CASE ReceivePayment.PaymentType

    WHEN  'Sale' THEN SELECT Name FROM Vendor WHERE VendorID = ReceivePayment.AccountID
    WHEN  'Purchase' THEN SELECT Name FROM Customers WHERE CustID = ReceivePayment.AccountID
END
FROM ReceivePayment

【问题讨论】:

  • 请编辑您的问题以添加sample data 和基于该数据的预期输出。以Formatted text 和严格的no screen shots 提供它们。 请勿在 cmets 中发布代码或其他信息。请确保您拥有minimal, complete and verifiable example
  • (1) 用您正在使用的数据库标记您的问题。 (2) 显示您尝试过的查询(可能简化以关注您遇到问题的点)。正如所写,这个问题对其他人来说毫无意义。

标签: sql database select case


【解决方案1】:

你很接近:

SELECT (CASE rp.PaymentType
            WHEN  'Sale'
            THEN (SELECT v.Name FROM Vendor v WHERE v.VendorID = rp.AccountID)
            WHEN  'Purchase'
            THEN (SELECT c.Name FROM Customers c WHERE c.CustID = rp.AccountID)
        END)
FROM ReceivePayment rp;

您只需要在子查询周围加上括号。注意:您需要确保子查询只返回 0 或 1 行,否则会报错。

请注意,我还添加了表别名来简化查询。

【讨论】:

  • 感谢@Gordon Linoof,我不确定我的选择语句周围是否缺少大括号:)
【解决方案2】:

您可以尝试使用条件连接和COALESCE 类似这样的东西:

SELECT COALESCE(v.Name, C.Name, '') AS Name
FROM ReceivePayment AS rp
LEFT JOIN Vendor AS v ON rp.AccountID = v.VendorID AND rp.PaymentType = 'Sale'
LEFT JOIN Customers AS c ON rp.AccountID = c.CustID AND rp.PaymentType = 'Purchase'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    相关资源
    最近更新 更多