在列表中查找多个变量(多个条件)- SQL

Find multiple variables (multiple conditions) in list - SQL


我必须找到不是 INTERNAL 的交易并计算它们的 EURO_AMOUNT 值的总和。

INTERNAL - Account_to and Account_from belongs to one customer

在这种情况下 结果 应该是:(EURO_AMOUNT) 2 + 3 + 4 + 5 + 7 = 21

那是我的数据库的简化模型。

CREATE TABLE IF NOT EXISTS `transaction_details` (
    `id` int(6) unsigned NOT NULL,
    `euro_amount` int(6) NOT NULL,
    `account_from` varchar(200) NOT NULL,
    `account_to` varchar(200) NOT NULL,
    `customer_id` int(6) NOT NULL,
    PRIMARY KEY (`id`)
) DEFAULT CHARSET = utf8;

CREATE TABLE IF NOT EXISTS `customer` (
    `id` int(6) unsigned NOT NULL,
    `customer_id` int(6) unsigned NOT NULL,
    `account` varchar(200) NOT NULL,
    PRIMARY KEY (`id`)
) DEFAULT CHARSET = utf8;

这就是简化的数据。

INSERT INTO `transaction_details` (`id`,`euro_amount`, `account_from`, `account_to`, `customer_id`)
VALUES 
    ('1','1', 'Account1', 'Account2', '10'), -- Internal
    ('2','2', 'Account3', 'Account4', '11'),
    ('3','3', 'Account1', 'Account3', '12'),
    ('4','4', 'Account1', 'Account4', '13'),
    ('5','5', 'Account1', 'Account3', '10'),
    ('6','6', 'Account15', 'Account1', '10'), -- Internal
    ('7','7', 'Account15', 'Account3', '10'); 

INSERT INTO `customer` (`id`, `customer_id`, `account`)
VALUES 
    ('1', '10', 'Account1'),
    ('2', '11', 'Account3'),
    ('3', '12', 'Account4'),
    ('4', '10', 'Account2'),
    ('5', '10', 'Account15');

从'programming language'的角度来看,我认为一个想法可能或多或少是这样的:

fun getAccountsForCustomer(customer_id): List<Account>
fun main() {
       List<Transaction_Detail> transactions;
       transactions.stream()
                   .filter(transaction -> {
                     if(transaction.account_from IN getAccountsForCustomer(transaction.customer_id) 
                        AND transaction.account_to IN getAccountsForCustomer(transaction.customer_id)) {
                         return 0;
                      } else {
                         return transaction;
                  }
       }).reduce((a,b) -> a+b);
    }

但这是从 'programming language' 的角度而不是 SQL 的角度:/

感谢你们的帮助。

从交易详情开始,您可以加入客户 table 两次(一次用于 account_from,一次用于 account_to)并过滤掉具有相同 [=13] 的客户=].最后一步是聚合:

select sum(td.euro_amount) sum_euro_amount
from transaction_details td
inner join customer c1 on c1.account = td.account_from
inner join customer c2 on c2.account = td.account_to
where c1.customer_id <> c2.customer_id

加入两次以比较客户和聚合:

select sum(td.amount)
from transaction_details td join
     customer cto
     on ct.account = td.account_to
     customer cfrom
     on cfrom.account = td.account_from
where ct.customer_id <> cfrom.customer_id