【发布时间】:2021-09-07 10:26:01
【问题描述】:
我有这张表,我想在其中获取 balance 列的总和,但每个项目都应该具有来自 date 列的唯一值。
我正在尝试查找balance 列中所有相同且具有相同date 的行,然后找到balance 列的总和。
具有唯一日期的样本数据:
| balance | date |
|---|---|
| 700 | 2021-07-03 |
| 700 | 2021-09-03 |
| 300 | 2021-09-04 |
| 500 | 2021-09-05 |
使用的查询如下:
select distinct a.balance, a.date from table a where a.date between (some date) and (some other date)
我试过了:
select sum(a.balance), a.date from table a where a.date between (some date) and (some other date) group by a.date
但balance 列显示了该列中所有值的总和,但显示了不同的日期,如下所示。
| balance | date |
|---|---|
| 893938 | 2021-07-03 |
| 858585 | 2021-09-03 |
| 728366 | 2021-09-04 |
| 665322 | 2021-09-05 |
【问题讨论】:
-
(1) MySQL Oracle。请正确标记。 (2)。你的
GROUP BY应该做正确的事。 (3) 也许您的样本数据实际上并不能说明您想要做什么。858585来自哪里? -
858585 是余额列中日期为 2021-09-03 的所有值的总和。我将编辑我的问题。
-
显示测试用例的实际原始数据。您可能有 100 行包含某个日期的 700 余额。尝试以下操作以更好地理解数据:
select a.balance, a.date, COUNT(*) AS n from table a where <some criteria> GROUP BY a.balance, a.date; -
如果您只需要
SUM中的DISTINCT每个日期的余额,您可以:SELECT a.date, SUM(DISTINCT balance) AS dbal FROM tbl a ... GROUP BY a.date;我不知道您为什么要这样做。但这就是它可以做到的方式。 -
在
SUM余额之前,您应该非常小心,您通常会将交易金额相加,但是不是余额....