【问题标题】:SQL Select with multiple column result with conditions带有条件的多列结果的 SQL 选择
【发布时间】:2021-11-02 05:41:59
【问题描述】:

请帮助我处理这个 SQL 选择查询。它可以作为三个 select 语句,但我需要将它变成一个语句

select (loan_amount + origination_fee) column1 from Table
where transaction_type='A'

select (stock_price + broker_fee) column2 from Table
where transaction_type='B'

select (taxable_amount + miscellaneous) column3 from Table
where transaction_type='C'

我试过了:

SELECT   (
            SELECT  (loan_amount + origination_fee)
            FROM    table
            WHERE   transaction_type = 'A'
         ) AS A
        ,(
            SELECT  (stock_price + broker_fee)
            FROM    table
            WHERE   transaction_type = 'B'
         ) AS B
        ,(
            SELECT  (taxable_amount + miscellaneous)
            FROM    table
            WHERE   transaction_type = 'C'
         ) AS C

我收到以下错误:

消息 512,第 16 级,状态 1,第 1 行

子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。

【问题讨论】:

  • 样本数据有助于您的问题。
  • 除了样本数据和想要的结果,还请为您正在使用的数据库添加标签。

标签: sql select subquery


【解决方案1】:
select case when transaction_type='A' then loan_amount + origination_fee end as A,
       case when transaction_type='B' then stock_price + broker_fee end as B,
       case when transaction_type='C' then taxable_amount + miscellaneous end as C 
from your_table

【讨论】:

    【解决方案2】:
    select case when transaction_type='A' then loan_amount + origination_fee else NULL end as A,
           case when transaction_type='B' then stock_price + broker_fee else NULL end as B,
           case when transaction_type='C' then taxable_amount + miscellaneous else NULL end as C 
    from your_table
    where transaction_type in ('A', 'B', 'C');
    

    【讨论】:

      【解决方案3】:

      我不确定你到底想要什么。但是如果你想要一行包含三个值的 sum,那么:

      select sum(case when transaction_type = 'A' then loan_amount + origination_fee end) as A,
             sum(case when transaction_type = 'B' then loan_amount + origination_fee end) as B,
             sum(case when transaction_type = 'C' then loan_amount + origination_fee end) as C
      from t;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-17
        • 2016-02-28
        • 1970-01-01
        • 2015-12-08
        相关资源
        最近更新 更多