SELECT FDAY AS FDAY , ROW_NUMBER() OVER (ORDER BY FDAY ASC) - 1 AS row_index FROM dbo.T_ENG_WORKCALDATA WHERE FDATESTYLE = '1' AND FDAY >= CONVERT(VARCHAR(10), GETDATE(), 120);这样可以获取工作日的时间差,但是缺少非工作日,如何解决
时间: 2024-01-24 16:01:48 浏览: 54
要计算包括非工作日的时间差,可以在查询中使用一个递归CTE(公共表表达式)。以下是实现步骤:
1. 创建一个递归CTE,其中包含所有日期(包括非工作日)和它们的行索引。这可以通过使用一个日期维度表来实现。
```
WITH date_dim AS (
SELECT date, ROW_NUMBER() OVER (ORDER BY date ASC) - 1 AS row_index
FROM dbo.date_dimension
WHERE date >= CONVERT(VARCHAR(10), GETDATE(), 120)
)
```
2. 在递归CTE中计算每个日期的工作日索引,其中工作日索引是从查询中获取的。
```
, workday_dim AS (
SELECT FDAY AS workday_index
FROM dbo.T_ENG_WORKCALDATA
WHERE FDATESTYLE = '1'
)
, date_workday AS (
SELECT date_dim.*,
ISNULL(workday_dim.workday_index, -1) AS workday_index
FROM date_dim
LEFT JOIN workday_dim
ON date_dim.date = (SELECT MAX(date)
FROM dbo.T_ENG_WORKCALDATA
WHERE FDATESTYLE = '1' AND FDAY <= date_dim.date)
)
```
在这个例子中,我使用了一个外连接来将日期与最接近的工作日匹配。如果日期在工作日表中没有匹配项,则工作日索引将设置为-1。
3. 计算每个日期的工作日时间差,其中工作日时间差是前一个日期的工作日时间差加上当前日期的工作日索引。
```
, date_workday_diff AS (
SELECT date_workday.*,
CASE
WHEN workday_index = -1 THEN NULL
ELSE SUM(CASE WHEN workday_index >= 0 THEN 1 END)
OVER (ORDER BY date ASC)
- workday_index
END AS workday_diff
FROM date_workday
)
```
在这个例子中,我使用了一个窗口函数SUM来计算当前日期之前的工作日数量。如果当前日期不是工作日,则工作日时间差为NULL。
4. 最后,从递归CTE中选择所有日期和它们的工作日时间差。
```
SELECT date, workday_diff
FROM date_workday_diff
```
完整的查询代码如下所示:
```
WITH date_dim AS (
SELECT date, ROW_NUMBER() OVER (ORDER BY date ASC) - 1 AS row_index
FROM dbo.date_dimension
WHERE date >= CONVERT(VARCHAR(10), GETDATE(), 120)
)
, workday_dim AS (
SELECT FDAY AS workday_index
FROM dbo.T_ENG_WORKCALDATA
WHERE FDATESTYLE = '1'
)
, date_workday AS (
SELECT date_dim.*,
ISNULL(workday_dim.workday_index, -1) AS workday_index
FROM date_dim
LEFT JOIN workday_dim
ON date_dim.date = (SELECT MAX(date)
FROM dbo.T_ENG_WORKCALDATA
WHERE FDATESTYLE = '1' AND FDAY <= date_dim.date)
)
, date_workday_diff AS (
SELECT date_workday.*,
CASE
WHEN workday_index = -1 THEN NULL
ELSE SUM(CASE WHEN workday_index >= 0 THEN 1 END)
OVER (ORDER BY date ASC)
- workday_index
END AS workday_diff
FROM date_workday
)
SELECT date, workday_diff
FROM date_workday_diff
```
阅读全文