计算每周计划

时间:2015-11-13 21:16:11

标签: sql sql-server

我有一个Schedule表,周一到周日有一个Worker ID列。如果contains值大于0,则表示Worker计划在当天工作。

如何有效地计算工人在日期范围内工作的天数?目前我正在构建一个日期表并将其与Schedule表交叉连接,然后为每个日期生成1或0。然后我总结了价值以获得总数。

http://sqlfiddle.com/#!3/a3292a/7

这似乎有效,但由于交叉连接,它相对较慢。有更好/更快的方式吗?

1 个答案:

答案 0 :(得分:1)

您可以在WorkSchedule上尝试UNPIVOT并加入DateName上的DateValue查询。然后您只需将值与值相加

;WITH 
L0 AS (SELECT 1 AS c UNION ALL SELECT 1),
L1 AS (SELECT 1 AS c FROM L0 A CROSS JOIN L0 B),
L2 AS (SELECT 1 AS c FROM L1 A CROSS JOIN L1 B),
L3 AS (SELECT 1 AS c FROM L2 A CROSS JOIN L2 B),
L4 AS (SELECT 1 AS c FROM L3 A CROSS JOIN L3 B),
Nums AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS i FROM L4),
Schedule AS (
    SELECT *
    FROM    [WorkerSchedule]
    UNPIVOT (
        Working
        FOR [WorkDay] IN ([Sunday], [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday])
    ) u
)
SELECT  s.WorkerId, SUM(s.Working) ScheduledDays
FROM    Schedule s
INNER JOIN (SELECT DATENAME(weekday, DATEADD(DAY, i - 1, @StartDate)) AS DateValue
            FROM Nums 
            WHERE i <= 1 + DATEDIFF(DAY, @StartDate, @EndDate)) d ON s.[WorkDay] = d.DateValue
WHERE s.Working = 1
GROUP BY s.WorkerId