gpt4 book ai didi

SQL Server 2008、临时表、游标

转载 作者:行者123 更新时间:2023-12-02 19:11:27 27 4
gpt4 key购买 nike

我已经为此工作了一段时间了。我想知道如何获得这张 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

看起来像这个表:

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

最佳答案

;WITH    CTE
AS ( SELECT * ,
DATEDIFF(DAY, 0, open_dt) - ROW_NUMBER() OVER
( PARTITION BY ops_hrs ORDER BY open_dt ) AS Grp
FROM @x
)
SELECT
MIN(open_dt) AS min_date ,
MAX(open_dt) AS max_date ,
ops_hrs
FROM CTE
GROUP BY ops_hrs ,
Grp
ORDER BY min_date

关于SQL Server 2008、临时表、游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7099598/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com