在不同条件下执行两次求和
我需要在不同条件下执行两次求和:
- 第一个求和:必须返回每个 date1 和 id 的值之和(按 date1 和 id 分组)。
- Second Sum:必须返回每个 date1 和 id 的值之和(按 date1 和 id 分组),没有与最小的 date2 对应的值。
ID | 值 | Date1 | Date2 |
---|---|---|---|
01 | 01 | 2022-02-15 | 2022-02-15 |
01 | 01 | 2022-02-15 | 2022-02-19 |
01 | 03 | 2022-02-15 | 2022-02-17 |
01 | 02 | 2022-02-16 | 2022-02-20 |
01 | 01 | 2022-02-16 | 2022-02-22 |
01 | 04 | 2022-02-16 | 2022-02-28 |
预期结果:
ID | Date1 | SUM1 | SUM2 |
---|---|---|---|
01 | 2022-02-15 | 05 | 04 |
01 | 2022-02-16 | 07 | 05 |
在sum2中,对于data1=2022-02-15,删除了data2=2022-02-15对应的值,因为它是分组中data2的最小值。
在 sum2 中,对于 data1 = 2022-02-16,对应于 data2=2022-02-20 的值被删除,因为它是分组中 data2 的最小值。
关于如何获得这个结果有什么建议吗?
I need to perform two Sums with different conditions:
- First Sum: Must return the sum of values for each date1 and id (Group by date1 and id).
- Second Sum: Must return the sum of values for each date1 and id (Group by date1 and id), without the value corresponding to the smallest date2 .
ID | Value | Date1 | Date2 |
---|---|---|---|
01 | 01 | 2022-02-15 | 2022-02-15 |
01 | 01 | 2022-02-15 | 2022-02-19 |
01 | 03 | 2022-02-15 | 2022-02-17 |
01 | 02 | 2022-02-16 | 2022-02-20 |
01 | 01 | 2022-02-16 | 2022-02-22 |
01 | 04 | 2022-02-16 | 2022-02-28 |
Expected outcome:
ID | Date1 | SUM1 | SUM2 |
---|---|---|---|
01 | 2022-02-15 | 05 | 04 |
01 | 2022-02-16 | 07 | 05 |
In sum2, for data1=2022-02-15, the value corresponding to data2=2022-02-15 was removed, as it is the smallest value of data2 in the grouping.
In sum2 , for data1 = 2022-02-16, the value corresponding to data2=2022-02-20 was removed, as it is the smallest value of data2 in the grouping.
Any suggestions on how to get this result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
partition by
并不总是能与group by
配合良好,因此您可以使用 CTE 来实现结果:这里是db_fiddle。
我在这里使用了
min
,但这是任意的,任何其他都可以:max
、avg
等。Since
partition by
does not always play well withgroup by
, you can use CTE to achieve the result:Here is the db_fiddle.
I've used
min
here, but that is arbitraty and any other would work:max
,avg
etc.您可以尝试在子查询中使用
LEAD
窗口函数,它将获取每个Date1
的下一个值(这将忽略每个Date1
的最小值)。然后对
value
列进行sum
LEAD
窗口函数列。sqlfiddle
You can try to use
LEAD
window function in subquery which will get the next value perDate1
(that will ignore the smallest perDate1
).Then do
sum
onvalue
column &LEAD
window function column.sqlfiddle