Mysql根据多案例取记录

标签 mysql database

我确实有merchant_credit_history表,我在其中存储商家信用、借记卡和交易类型。

我想根据交易类型对贷方或借方求和。

记录

enter image description here

我尝试过这个:

选择 SUM(ABS(借方)) 作为 dealer_credit 来自merchant_credits_history WHERE transaction_type='premium_debit' 和merchant_id='x'

联盟

选择 SUM(ABS(credit)) 作为 dealer_margin_earned 来自merchant_credits_history WHERE transaction_type='margin_credit' 和merchant_id='x'

输出为

enter image description here

如果我能有更好的查询以及单独的键值对中的值,我将不胜感激

最佳答案

SELECT 
    SUM(CASE(WHEN transaction_type='premium_debit') THEN debit ELSE 0)) as dealer_credit, 
    SUM(CASE(WHEN transaction_type='margin_credit') THEN credit ELSE 0)) as dealer_margin_earned 
    FROM merchant_credits_history 
    WHERE merchant_id='x';

因此,您可以获得每个merchant_id 的一对贷方、借方值。

关于Mysql根据多案例取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806429/

相关文章:

sql-server - 没有关系/有关系的数据库设计,我应该使用外键吗?

mysql - 如何将阿拉伯语转储 SQL 文件导入到 phpmyadmin 而不会出现问题?

php - 从 SQL 日期时间元素中减去 php 系统时间

mysql - SQL 查询的正确方法

数据库设计 - 为用户存储点的方法

mysql - 用户在表格中的排名位置?

php - "use"命令因 PostgreSQL 中的语法错误而失败(从 MySQL 转换)

java - Mysql 正在保存从 Java 应用程序输入提供的 1 天前的日期

php - MySQL WordPress 查询 : Select posts by meta value but also include category

java - 将数据从 Cursor 绑定(bind)到 Spinner Android