查询缺失元素
我有一个具有以下结构的表:
timestamp | name | value
0 | john | 5
1 | NULL | 3
8 | NULL | 12
12 | john | 3
33 | NULL | 4
54 | pete | 1
180 | NULL | 4
400 | john | 3
401 | NULL | 4
592 | anna | 2
现在我正在寻找一个查询,它将给出每个名称的值的总和,并将其之间的空值(按时间戳排序)视为第一个非空名称沿着列表向下移动,就好像表如下所示:
timestamp | name | value
0 | john | 5
1 | john | 3
8 | john | 12
12 | john | 3
33 | pete | 4
54 | pete | 1
180 | john | 4
400 | john | 3
401 | anna | 4
592 | anna | 2
我将查询 SUM(value), name from this table group by name
。我思考过,也尝试过,但想不出一个合适的解决办法。我看过递归公用表表达式,并认为答案可能就在那里,但我无法正确理解它们。
这些表只是示例,我事先不知道时间戳值。
有人可以帮我吗?非常感谢您的帮助。
I have a table with the following structure:
timestamp | name | value
0 | john | 5
1 | NULL | 3
8 | NULL | 12
12 | john | 3
33 | NULL | 4
54 | pete | 1
180 | NULL | 4
400 | john | 3
401 | NULL | 4
592 | anna | 2
Now what I am looking for is a query that will give me the sum of the values for each name, and treats the nulls in between (orderd by the timestamp) as the first non-null name down the list, as if the table were as follows:
timestamp | name | value
0 | john | 5
1 | john | 3
8 | john | 12
12 | john | 3
33 | pete | 4
54 | pete | 1
180 | john | 4
400 | john | 3
401 | anna | 4
592 | anna | 2
and I would query SUM(value), name from this table group by name
. I have thought and tried, but I can't come up with a proper solution. I have looked at recursive common table expressions, and think the answer may lie in there, but I haven't been able to properly understand those.
These tables are just examples, and I don't know the timestamp values in advance.
Could someone give me a hand? Help would be very much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
顺便说一句,比任何查询快几个数量级的是首先纠正数据。即,更新名称列以具有正确的值,使其不可为空,然后运行一个简单的 Group By 来获取总计。
额外解决方案
Btw, what would be orders of magnitude faster than any query would be to first correct the data. I.e., update the name column to have the proper value, make it non-nullable and then run a simple Group By to get your totals.
Additional Solution
您不需要 CTE,只需要一个简单的子查询。
并从这里总结
You don't need CTE, just a simple subquery.
And summing from here
我希望我不会因为向您提供这个小小的递归 CTE 查询来解决您的问题而感到尴尬。
I hope I'm not going to be embarassed by offering you this little recursive CTE query of mine as a solution to your problem.