SQL:对连续记录进行分组
一个有点棘手的 SQL 问题(我们运行的是 SQL Server 2000)。
我有下表 StoreCount -
WeekEndDate StoreCount
2010-07-25 359
2010-07-18 359
2010-07-11 358
2010-07-04 358
2010-06-27 358
2010-06-20 358
2010-06-13 358
2010-06-06 359
2010-05-30 360
2010-05-23 360
2010-05-16 360
我想将其转换为以下输出 -
StartDate EndDate StoreCount
2010-07-18 2010-07-25 359
2010-06-13 2010-07-11 358
2010-06-06 2010-06-06 359
2010-05-16 2010-05-30 360
正如您所看到的,我想要对商店计数进行分组,仅当它们按顺序一起运行时。
A slightly tricky SQL question (we are running SQL server 2000).
I have the following table, StoreCount -
WeekEndDate StoreCount
2010-07-25 359
2010-07-18 359
2010-07-11 358
2010-07-04 358
2010-06-27 358
2010-06-20 358
2010-06-13 358
2010-06-06 359
2010-05-30 360
2010-05-23 360
2010-05-16 360
I want to turn this into the following output -
StartDate EndDate StoreCount
2010-07-18 2010-07-25 359
2010-06-13 2010-07-11 358
2010-06-06 2010-06-06 359
2010-05-16 2010-05-30 360
As you can see, I'm wanting to group the store counts, by only as they run in sequence together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这里有一个挑战,只是它可能有 SS2k 中不可用的语法。它实际上是在 Oracle 上编写的,因为我不再有那个版本的 SS。唯一的问题可能是选择的选择...(自从我使用 SS2k 以来已经有一段时间了,所以很难记住当时哪些功能不可用。)
Here's a kick at the can, only it may have syntax not available in SS2k. It was actually written on Oracle as I don't have that version of SS around anymore. The only catch might be the the select of a select...(it's been a while since I've used SS2k, so it's hard to remember what features weren't available back then.)
使用光标。我不知道如何在 sql2k 中使用查询来做到这一点。
Use cursor. I don't know how to do it in sql2k by using query.
好的,这是我的尝试。
Ok, here's my go at it.
我不确定如何解释这一点,但它似乎为给定的小数据集提供了所需的结果。本质上,它检测序列中值发生变化的点。
我没有看过查询计划,可能会很痛苦。
在Sybase服务器上尝试过,因此语法应该与SQL Server 2K兼容。
I'm not sure how to explain this, but it seems to give the desired result for the small dataset given. In essence, it detects the points in the series where the values change.
I haven't looked at the query plan, might be painful.
Tried on a Sybase server, so syntax should be compatible with SQL Server 2K.
尝试这个简单的解决方案:
sqlfiddle
try this simple solution:
sqlfiddle