汇总函数不会汇总 - 使用总和函数汇总数据集

发布于 2025-01-30 01:55:50 字数 772 浏览 5 评论 0原文

我是Snowflake的新手,我正在尝试编写一个SQL查询,该查询将根据ref Ref列总结2行。总和函数似乎不起作用,因为我认为我缺少一些东西。

示例数据(交易)

| id   | withdraw| pending|   ref   |  Status  |   date   |
|:---- |:-------:| --- --:| -------:|---------:|---------:|
| 100  | 500     | -500   |1234:234 |Confirmed |2022-05-04 |
| 100  | -500    |  500   |1234:234 |Pending   |2022-05-03 |

我想

| id   | withdraw| pending|   ref   |  Status  |   date   |
|:---- |:-------:| --- --:| -------:|---------:|---------:|
| 100  | 0       |   0    |1234:234 |Confirmed |2022-05-04 |

在这里实现的目标是我到目前为止所做的

select id,
       sum(withdraw),
       sum(pending),
       ref,
       status,
       date,
from transaction
group by id,ref

I am new to snowflake and I am trying to write an SQL query that would sum up 2 rows based on the ref column. The sum function seems to not work as I think im missing something.

sample data (transaction)

| id   | withdraw| pending|   ref   |  Status  |   date   |
|:---- |:-------:| --- --:| -------:|---------:|---------:|
| 100  | 500     | -500   |1234:234 |Confirmed |2022-05-04 |
| 100  | -500    |  500   |1234:234 |Pending   |2022-05-03 |

what I want to achieve

| id   | withdraw| pending|   ref   |  Status  |   date   |
|:---- |:-------:| --- --:| -------:|---------:|---------:|
| 100  | 0       |   0    |1234:234 |Confirmed |2022-05-04 |

here is what I did so far

select id,
       sum(withdraw),
       sum(pending),
       ref,
       status,
       date,
from transaction
group by id,ref

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乄_柒ぐ汐 2025-02-06 01:55:50

如果您想要的是提取的总和,以及最后的状态 and date per iDref然后使用窗口函数:

SELECT DISTINCT 
       id,
       SUM(withdraw) OVER (PARTITION BY id, ref) withdraw,
       SUM(pending) OVER (PARTITION BY id, ref) pending,
       ref,
       FIRST_VALUE(status) OVER (PARTITION BY id, ref ORDER BY date DESC) status,
       MAX(date) OVER (PARTITION BY id, ref) date
FROM transaction;

If what you want is the sum of withdraw and pending and the last status and date per id and ref then use window functions:

SELECT DISTINCT 
       id,
       SUM(withdraw) OVER (PARTITION BY id, ref) withdraw,
       SUM(pending) OVER (PARTITION BY id, ref) pending,
       ref,
       FIRST_VALUE(status) OVER (PARTITION BY id, ref ORDER BY date DESC) status,
       MAX(date) OVER (PARTITION BY id, ref) date
FROM transaction;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文