【问题标题】:Multiple columns return in CASE Statement SQLCASE 语句 SQL 中返回多列
【发布时间】:2021-12-29 22:36:27
【问题描述】:

我有两个表,根据 TABLE1 中一个字段的总和,我必须从 TABLE2 返回不同的数据集:

我正在尝试通过 Case 语句来实现这一点,但收到一条错误消息,说 subselect must have only one field.

有没有更好的方法来做到这一点?只是当 table1 中的列的总和为 0 时,不要从 table2 中选择任何内容

表 1:

表 2:

我的 SQL:

SELECT 
   CASE 
   WHEN SUM(transaction_unit_failed) > 0 
   THEN (
         SELECT sale_event_nr, business_unit, transaction_nr, transaction_unit_failed_number
        FROM TABLE2
        )
   WHEN SUM(transaction_unit_failed) = 0 
   THEN (
         SELECT sale_event_nr, business_unit, transaction_nr, transaction_unit_failed_number
        FROM TABLE2
        WHERE 1 = 2
 
        )
FROM TABLE1 

【问题讨论】:

  • 请避免发布images 的数据,我们无法使用图像中的数据,示例数据在您的问题中应该是consumable text,最好是create 和 insert 语句,或者DB<>Fiddle

标签: sql case


【解决方案1】:
select * from table2
where exists (
    select 1
    from table1
    having sum(transaction_unit_failed) > 0
);

同样:

select * from table2
where (
    select sum(transaction_unit_failed)
    from table1
) > 0;

https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=3f68d250bc9a3235767b86626092799e

如果有令人信服的理由,您当然可以将其写为连接。这将消除使用* 仅返回一个表中的列的便利。

select *
from table2 inner join (
    select sum(transaction_unit_failed) as stuf
    from table1
) on stuf > 0;

【讨论】:

    【解决方案2】:
     SELECT sale_event_nr, business_unit, transaction_nr, transaction_unit_failed_number
       FROM TABLE2
      WHERE (SELECT SUM(transaction_unit_failed) > 0 
                         FROM TABLE1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多