gpt4 book ai didi

sql-server - 从 SQL Server 2012 中的列表中返回缺少的日期

转载 作者:行者123 更新时间:2023-12-01 13:50:00 25 4
gpt4 key购买 nike

考虑过滤器:

  • 开始:14/09/2015(星期一)
  • 结束:2015 年 9 月 20 日(星期日)

我从 14/09 到 20/09 的查询得到了这个结果:

╔════════════╦══════════╦══════════════╦═══════════╗
║ Date ║ Employee ║ EmployeeType ║ Type ║
╠════════════╬══════════╬══════════════╬═══════════╣
║ 14/09/2015 ║ John ║ Permanent ║ Timesheet ║
║ 14/09/2015 ║ Silva ║ Permanent ║ Timesheet ║
║ 16/09/2015 ║ John ║ Permanent ║ Timesheet ║
║ 17/09/2015 ║ Airn ║ Casual ║ Timesheet ║
╚════════════╩══════════╩══════════════╩═══════════╝

如果员工是“Permanent”并且缺失的日期是“Monday to Friday”,我需要返回所有缺失的日期,如下所示:

╔════════════╦══════════╦══════════════╦═══════════╗
║ Date ║ Employee ║ EmployeeType ║ Type ║
╠════════════╬══════════╬══════════════╬═══════════╣
║ 14/09/2015 ║ John ║ Permanent ║ Timesheet ║
║ 14/09/2015 ║ Silva ║ Permanent ║ Timesheet ║
║ 15/09/2015 ║ John ║ Permanent ║ Missing ║
║ 15/09/2015 ║ Silva ║ Permanent ║ Missing ║
║ 16/09/2015 ║ John ║ Permanent ║ Timesheet ║
║ 16/09/2015 ║ Silva ║ Permanent ║ Missing ║
║ 17/09/2015 ║ John ║ Permanent ║ Missing ║
║ 17/09/2015 ║ Airn ║ Casual ║ Timesheet ║
║ 17/09/2015 ║ Silva ║ Permanent ║ Missing ║
║ 18/09/2015 ║ John ║ Permanent ║ Missing ║
║ 18/09/2015 ║ Silva ║ Permanent ║ Missing ║
╚════════════╩══════════╩══════════════╩═══════════╝

我不太了解SQL Server 2012 中的LEAD 命令。

最佳答案

您可以使用 Tally Table@start@endCROSS JOIN 构建日期与您的表以获得缺失的日期。

SQL Fiddle

DECLARE @start  DATE = '20150914',
@end DATE = '20150920'

;WITH E1(N) AS(
SELECT 1 FROM(VALUES
(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)
)t(N)
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b),
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b),
Tally(N) AS(
SELECT TOP(DATEDIFF(DAY, @start, @end))
ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
FROM E4
),
CteDates(dt) AS(
SELECT DATEADD(DAY, N-1, @start) FROM Tally
),
CteEmployee AS(
SELECT DISTINCT Employee, EmployeeType
FROM yourTable
WHERE EmployeeType = 'Permanent'
)
SELECT
Date = d.dt,
e.Employee,
e.EmployeeType,
Type = ISNULL(yt.Type, 'Missing')
FROM CteEmployee e
CROSS JOIN CteDates d
LEFT JOIN yourTable yt
ON e.Employee = yt.Employee
AND d.dt = yt.Date
WHERE
((DATEPART(dw, d.dt) + @@DATEFIRST) % 7) NOT IN (0, 1)

UNION ALL

SELECT * FROM yourTable WHERE EmployeeType = 'Casual'
ORDER BY Date, e.Employee

WHERE 子句

((DATEPART(dw, d.dt) + @@DATEFIRST) % 7) NOT IN (0, 1)

不考虑 @@DATEFIRST 的周末。

关于sql-server - 从 SQL Server 2012 中的列表中返回缺少的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620301/

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