首先,我的表:
mysql> desc invoice;
+-------------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| date | timestamp | YES | | NULL | |
| sent | timestamp | YES | | NULL | |
| due_date | timestamp | YES | | NULL | |
| amount | float | YES | | NULL | |
| amount_due | float | YES | | NULL | |
| status | enum('unpaid','paid') | YES | | NULL | |
| customer_id | int(11) | NO | MUL | NULL | |
+-------------+-----------------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)
任何人都可以帮我提出一个将返回的查询,每行:
当天(所以按due_date分组) 当天的起始余额(这将是前一天的结束余额) 流入(当天的POSITIVE交易总数) 流出(当天的负面交易总数) 期末余额(已应用所有流入和流出交易后的当天结束余额)
基本上每天我都想知道存入了多少钱,提取了多少钱,当天的余额开始以及结束余额。
我还应该指定当天,我想按“due_date”对行进行分组,并使用“amount”列作为所有事务的基础(忽略amount_due)。
有什么想法吗?
我可以开始制作另一个只包含此信息的表格,但也许有人可以提出一个可以通过实际数据执行此操作的漂亮查询。
答案 0 :(得分:0)
您需要从发票表中拆分交易,如下所示:
TABLE invoice (
id int autoincrement,
due_date date,
customer_id int,
sent_date date
);
TABLE transaction (
id int autoincrement primary key
transaction_date date,
amount double,
transaction_type enum ("charge", "payment"),
customer_id int
);
完成创建交易表后,您可以轻松获得所需内容:
SELECT SUM(amount), transaction_type, transaction_date, customer_id FROM transaction GROUP BY customer_id, transaction_date, transaction_type
答案 1 :(得分:0)
这是我的看法。基本上你通过
加入发票表todaydata.due_date=DATE_ADD(yesterdaydata.due_date,DAY,-1)
所以你可以访问昨天的amount_due字段(我做了一个左连接,所以如果你要求在你的表中的第一天,你仍然会得到一个记录)
其余的非常简单。我不确定今天的期末余额是昨天+流入+流出的总和,还是它只是todaydata.amount_due的总和,所以我把两者都包括在内。
SELECT
todaydata.due_date,
SUM(case when yesterdaydata.amount_due is null then 0 else yesterdaydata.amount_due end )) AS StartingBalance,
SUM(CASE when todaydata.amount > 0 THEN todaydata.amount ELSE 0 END) AS INFLOW,
SUM(CASE when todaydata.amount < 0 THEN todaydata.amount ELSE 0 END) AS OUTFLOW,
SUM(yesterday.amount_due) AS StartingBalance +
SUM(CASE where todaydata.amount > 0 THEN todaydata.amount ELSE 0 END) +
SUM(CASE where todaydata.amount < 0 THEN todaydata.amount ELSE 0 END) AS CalculatedEndingBalance,
SUM(todaydata.amount_due) AS OtherEndingBalance
FROM invoice [todaydata]
LEFT JOIN invoice [yesterdaydata] ON todaydata.due_date=DATE_ADD(yesterdaydata.due_date,DAY,-1)
GROUP BY todaydata.due_date
我没有能力对mysql数据库进行测试,所以让我知道任何语法错误,我会纠正。