SQL Server 2008、临时表、游标
我已经在这方面工作了一段时间了。我想知道如何获得此表:
id open_dt ops_hrs
1 10/31/2011 7:00AM - 5:30PM
2 11/1/2011 7:00AM - 5:00PM
3 11/2/2011 7:00AM - 5:00PM
4 11/3/2011 7:00AM - 5:00PM
5 11/6/2011 7:00AM - 7:00PM
6 11/8/2011 7:00AM - 5:00PM
看起来像此表:
max_date min_date ops_hrs
10/31/2011 10/31/2011 7:00AM - 5:30PM
11/1/2011 11/3/2011 7:00AM - 5:00PM
11/6/2011 11/6/2011 7:00AM - 7:00PM
11/8/2011 11/8/2011 7:00AM - 5:00PM
我尝试使用游标,但没有必要。另外,它必须分组。一旦连续几天结束,就会出现新的分组。任何帮助将不胜感激。
该查询将生成上述示例数据
;
WITH pdog (id, open_dt,ops_hrs) AS
(
SELECT 1, CAST('10/31/2011' AS datetime), '7:00AM - 5:30PM'
UNION ALL SELECT 2, CAST('11/1/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 3, CAST('11/2/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 4, CAST('11/3/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 5, CAST('11/6/2011' AS datetime),'7:00AM - 7:00PM'
UNION ALL SELECT 6, CAST('11/8/2011' AS datetime),'7:00AM - 5:00PM'
)
SELECT * FROM pdog
I've been working at this for a while. I was wondering how I could get this table:
id open_dt ops_hrs
1 10/31/2011 7:00AM - 5:30PM
2 11/1/2011 7:00AM - 5:00PM
3 11/2/2011 7:00AM - 5:00PM
4 11/3/2011 7:00AM - 5:00PM
5 11/6/2011 7:00AM - 7:00PM
6 11/8/2011 7:00AM - 5:00PM
to look like this table:
max_date min_date ops_hrs
10/31/2011 10/31/2011 7:00AM - 5:30PM
11/1/2011 11/3/2011 7:00AM - 5:00PM
11/6/2011 11/6/2011 7:00AM - 7:00PM
11/8/2011 11/8/2011 7:00AM - 5:00PM
I tried using a cursor but it is not necessary. Also, it has to be grouped. As soon as consecutive days break a new grouping occurs. Any help would be appreciated.
This query will generate the above sample data
;
WITH pdog (id, open_dt,ops_hrs) AS
(
SELECT 1, CAST('10/31/2011' AS datetime), '7:00AM - 5:30PM'
UNION ALL SELECT 2, CAST('11/1/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 3, CAST('11/2/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 4, CAST('11/3/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 5, CAST('11/6/2011' AS datetime),'7:00AM - 7:00PM'
UNION ALL SELECT 6, CAST('11/8/2011' AS datetime),'7:00AM - 5:00PM'
)
SELECT * FROM pdog
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
绝对比 @Martin 的解决方案逻辑更复杂,但我至少应该得到一点,因为他使用了我的 @x 表 - 所以他的解决方案看起来更整洁。 :-)
Definitely slightly more convoluted logic than @Martin's solution, but I should at least get a point because he used my @x table - so his solution looks that much tidier. :-)