【问题标题】:SQL using the WHERE clause for the first column onlySQL 仅对第一列使用 WHERE 子句
【发布时间】:2020-06-11 01:53:35
【问题描述】:

我有一个带有列的表格:

customer_id, 
customer_name,
transaction_number, 
transaction_date,
transaction_type,
transaction_value,
transaction_approved. 

我正在尝试生成列所在的列表

customer_id,
customer_name,
total transaction value

transaction_type 为贷方且于 2020 年完成,transaction_type 为 2019 年借方或现金的总交易额。

但是,此列表仅包括 customer_id 在 2020 年使用信用进行了至少一笔交易。基本上,我将如何使用 where 子句获取 customer_id 的条件,然后获取其余的仅基于customer_ids 的列表?

它会返回

  • customer_id 至少有一笔交易是在 2019 年使用信用进行的
  • 然后它旁边的其他列将返回该customer_id 的值

【问题讨论】:

  • 我不清楚。请添加示例输入和输出数据。
  • 另外请向我们展示您目前编写的代码
  • 您是否有一个列出现有customer_ids 的表格?

标签: sql where-clause case-when


【解决方案1】:

我从上面的描述中了解到,用户需要在 2020 年有交易类型贷方的客户,但他想要 2019 年的金额总和,以及交易类型借方和现金的金额。如果不是这样,请更新问题

select 
    customer_id, customer_name,
    sum(coalesce(transaction_value,0)) as total_transaction_value 
from 
    table_T 
where 
    customer_id in (select distinct customer_id from table_T 
                    where transaction_type = 'credit'  
                      and transaction_date >= '2020-01-01')
    and transaction_date >= '2019-01-01'  
    and transaction_date < '2020-01-01' 
    and transaction_type in ('debit', 'cash')
group by  
    customer_id, customer_name

未提及数据库,您可能需要相应地解析日期字段

【讨论】:

    【解决方案2】:

    这样的事情应该可以解决问题:

    select customer_id, customer_name, sum(effective_value)
        from (
            select customer_id, customer_name,
                    case
                        when transaction_type in ('debit', 'cash')
                                and '2019' <= transaction_date
                                and transaction_date < '2020'
                            then transaction_value
                        else 0
                    END effective_value
                from transactions as T
        ) as T
        group by customer_id, customer_name;
    

    您必须调整 transaction_date 比较以满足您的数据库语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-15
      • 1970-01-01
      • 2017-04-29
      • 2022-06-15
      • 1970-01-01
      • 2010-12-25
      • 2011-05-04
      • 1970-01-01
      相关资源
      最近更新 更多