MySQL查询仅产生负的每日差异

时间:2019-02-02 12:48:37

标签: php mysql logic

我正在学习mysql,并且很难理解更复杂的输出-主要是逻辑部分...我有一个简单的数据库,其中包含2个具有1个连接的表-设计在这里https://prnt.sc/mfmwji < / p>

我需要创建一个报告,该报告显示过去6个月内仅负状态的每日余额(因此,仅当某人处于负余额时)。

我将查询汇总在一起,当它们为负数时仅显示差异,但是它不会将它们“连接”到它们之前的行...仅显示提现。 我玩过查询,但这是我想出的“最好的”东西。我试图用sum函数包装差异,但这只是对整个东西求和,而不返回每日差异。

SELECT
    T1.name AS Name,
    T2.withdraw - T2.deposit AS Difference,
    DATE_FORMAT(T2.date, '%Y-%m-%d') AS Date
FROM
    users AS T1
INNER JOIN transactions AS T2
ON
    T1.id = T2.user_id
WHERE
    (T2.withdraw - T2.deposit) > 0

查询返回此输出(自从我得到100个结果以来,它只是结果的一部分) http://prntscr.com/mfn0xf

Pearl Champlin的入金和入金,是这样的: http://prntscr.com/mfn15a

我曾尝试检查关于SO的其他问题,但它们通常指向其他问题,并非特定于我的问题。

提前感谢您认为我应该检查的任何信息!

2 个答案:

答案 0 :(得分:2)

您可以使用子查询来检索最新余额。然后,在外部查询中,您可以过滤该余额为负的位置:

select   *
from     (
          select      u.name,
                      t.date,
                      t.deposit - t.withdraw action,
                      ( select sum(deposit - withdraw)
                        from   transactions
                        where  user_id = u.id
                        and    date <= t.date ) as balance
          from        users as u
          inner join  transactions as t
                  on  u.id = t.user_id
         ) balances
where    balance < 0       
order by 1, 2

答案 1 :(得分:1)

这是您的要求。它显示一个用户的报告。我不知道是否有一种方法,使本作在同一时间的所有用户。也许它可以帮助您找到想要的东西。

SELECT
    PreAgg.name,
    (PreAgg.withdraw - PreAgg.deposit) AS Difference,
    @PrevBal := @PrevBal + (PreAgg.withdraw - PreAgg.deposit) AS Balance
FROM
    (SELECT
        T1.name,
        T2.deposit,
        T2.withdraw,
        (T2.withdraw - T2.deposit) AS Difference,
        T1.id
     FROM
        users AS T1
     INNER JOIN transactions AS T2
     ON
        T1.id = T2.user_id
     ORDER BY
        T2.id ) AS PreAgg,
       (SELECT @PrevBal := 0) as InitialVar
WHERE PreAgg.id = 1