我有一个MySql表来控制借记和贷记。它看起来像这样
id | status | type | amount | value | expiration | parent_id | company_id |
---|--------|------ |--------|-------|------------|-----------|------------|
1 | 1 |credit | 46 | 42.00 | 2018-04-01 | 0 | 1 |
2 | 1 |credit | 33 | 194.00| 2017-07-07 | 0 | 1 |
3 | 1 |credit | 49 | 17.00 | 2016-11-11 | 0 | 1 |
4 | 1 |debit | 1 | NULL | NULL | 1 | 1 |
5 | 1 |debit | 1 | NULL | NULL | 1 | 1 |
6 | 1 |debit | 1 | NULL | NULL | 2 | 1 |
7 | 1 |debit | 1 | NULL | NULL | 2 | 1 |
8 | 1 |debit | 1 | NULL | NULL | 2 | 1 |
9 | 1 |debit | 1 | NULL | NULL | 2 | 1 |
10 | 1 |debit | 1 | NULL | NULL | 3 | 1 |
我想要检索现在有多少学分。
对状态= 1且到期时间为>的每个父信用额的状态= 1的所有借方汇总。 NOW()
然后从它的父信用中扣除
在这种情况下,我应该得到类似的东西
总积分=(46 - 2)+(33 - 4)
我到目前为止的地方是
SELECT SUM(amount) as tot_debit
FROM credits
WHERE company_id = 1
AND status = 1
AND type = 'debit'
AND parent_id IN (SELECT id
FROM credits
WHERE company_id = 1
AND status = 1
AND expiration > NOW()
AND type = 'credit')
GROUP BY parent_id
有关如何使其发挥作用的任何想法?
由于
答案 0 :(得分:1)
您可以使用 correlation 来获得预期的结果:
SELECT SUM(amount)
-
COALESCE((SELECT SUM(amount)
FROM credits AS c2
WHERE company_id = 1 AND status = 1 AND
type = 'debit' AND
c2.parent_id = c1.id), 0)
FROM credits AS c1
WHERE company_id = 1 AND status = 1 AND
type = 'credit' AND expiration > NOW();
答案 1 :(得分:0)
您应该使用自我左连接,以便每条记录与其父记录(如果存在)匹配,并过滤掉过期的记录。然后使用条件总和,您可以添加信用额并减去借方。
SELECT SUM(CASE WHEN type = 'credit' THEN amount ELSE amount * -1 END) AS total
FROM credits t1
LEFT JOIN
credits t2
ON t1.parent_id = t2.id AND
t2.expiration > NOW()
WHERE t1.company_id = 1 AND
t1.status = 1 AND
t1.expiration > NOW()
答案 2 :(得分:0)
由于你在一张表(我不推荐的设计)中有信用和借记,这里最快的方法可能是聚合:
select sum(total)
from
(
select
sum(case when type = 'credit' then value else -value end) as total
from mytable
where company_id = 1
and status = 1
group by case when type = 'credit' then id else parent_id end -- group by credit ID
having sum(type = 'credit' and expiration > now()) > 0
) total_per_credit;
HAVING
子句在MySQL中使用true = 1 / false = 0。 (在其他DBMS中,您使用CASE
构造。)