SQL 查询列中行的差异
我正在努力为以下任务编写查询:
X Y X Y Seq Difference
--------- ------------------------------
20 35 20 35 1 35 (45 - 0)
21 45 ------> 21 45 1 45 (35-0)
21 52 21 52 2 7 (52-45)
22 66 22 66 1 66 (66-0)
22 68 22 68 2 2 (68-66)
22 77 22 77 3 9 (77 - 68)
左侧的表给出了 X 列的排序位置。右边的表是我试图用两个额外的列 Seq 和 Difference 生成的表。 Seq 计算 X 中唯一成员的数量并分配一个顺序值(在上面的示例中,有一个 20 、两个 21 和三个 22 )。差异列获取每个 UNIQUE X 的连续行的差异。
非常感谢您的帮助。
谢谢
I am struggling to write a query for the following task:
X Y X Y Seq Difference
--------- ------------------------------
20 35 20 35 1 35 (45 - 0)
21 45 ------> 21 45 1 45 (35-0)
21 52 21 52 2 7 (52-45)
22 66 22 66 1 66 (66-0)
22 68 22 68 2 2 (68-66)
22 77 22 77 3 9 (77 - 68)
The table on the left is given where column X is sorted. The table on the right is what I am trying to generate with two extra clumns Seq and Difference. Seq counts the number of unique members in X and assigns a sequential value (in the example above there are one 20 , two 21s and three 22s) . The difference column takes the differences of consecutive rows of each UNIQUE X.
Your help is much much appreciated.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无法通过简单的查询来完成此操作,因为每一行无法访问其他行的内容,但您可以轻松使用游标并使用此数据构建临时表。像这样的东西
Can't do this with a simple query as each row cannot access the contents of the others, but you could easily use a cursor and build a temp table with this data. Something like
您还可以使用子查询。它还在内存中生成一个可在最终结果集中使用的临时表。
You could also use a subquery. It generates a temporary table in memory as well that can be used in the final result set.
像这样的东西应该有效:
Something like this should work: