gpt4 book ai didi

sql - 给定开始日期和结束日期,以一周为间隔获取所有日期

转载 作者:行者123 更新时间:2023-12-04 05:50:43 26 4
gpt4 key购买 nike

我有一个事件记录数据库,我需要找到每个客户的所有事件,并从每个客户的最后一条记录到第一个记录以一周的时间间隔将它们分组。

FirstEvent                  LastEvent               Client
==
2011-01-01 06:55:21.000 |2011-04-30 21:46:09.000 |Client1
2011-01-01 06:20:00.000 |2011-02-23 12:43:55.000 |Client2
2011-01-03 08:34:33.000 |2011-04-30 09:00:39.000 |Client3
2011-01-01 02:14:45.000 |2011-04-30 15:31:41.000 |Client4
2011-01-01 08:08:12.000 |2011-02-21 09:41:28.000 |Client5
2011-02-01 11:29:28.000 |2011-04-29 09:13:25.000 |Client6

现在我必须计算每个客户的记录并像这样分组
Client     From                    To                        Records
==
Client1 |2011-04-30 21:46:09.000 |2011-04-23 21:46:09.000 |200
Client1 |2011-04-16 21:46:09.000 |2011-04-09 21:46:09.000 |400
...Until the the first date
Client1 |2011-01-08 06:55:21.000 |2011-01-01 06:55:21.000 |250
Client2 |2011-02-23 12:43:55.000 |2011-02-16 12:43:55.000 |50
...The same for each user

我希望有人能帮我找到输出这个的方法。

最佳答案

好的,我认为这正是您想要的:

SELECT CONVERT(datetime, '2011-01-01 06:55:21.000', 120) AS event, 'client1' AS Client
INTO #EVENTS
UNION ALL SELECT '2011-01-08 06:55:20.000', 'client1'
UNION ALL SELECT '2011-04-30 21:46:09.000', 'client1'


;WITH E AS (
SELECT
Client,
MIN(event) AS FirstEvent
FROM #EVENTS
GROUP BY Client
)
,B AS (
SELECT
E.Client,
E.FirstEvent,
COUNT(*) AS Records,
DATEDIFF(DAY, 0, c.event - E.FirstEvent) / 7 AS [weeks]
FROM #EVENTS c
JOIN E ON E.Client = c.Client
GROUP BY E.Client, E.FirstEvent, DATEDIFF(DAY, 0, c.event - E.FirstEvent) / 7
)
SELECT
Client,
DATEADD(WEEK, weeks, FirstEvent) AS [From],
DATEADD(WEEK, weeks + 1, FirstEvent) AS [To],
Records
FROM B
ORDER BY Client, weeks;

DROP TABLE #EVENTS

但是,如果某周没有记录,它将忽略该行,而不是返回包含 Records 值为 0 的行:

编辑:

如果你想知道我为什么使用 DAY而不是 WEEK我的 DATEDIFF ,这是为了避免问题是星期日还是星期一是一周的第一天。

关于sql - 给定开始日期和结束日期,以一周为间隔获取所有日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10087605/

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