如何从另一张桌子找出日子

时间:2015-07-02 06:24:39

标签: sql sql-server

DECLARE   @Daystaken TABLE(
Application VARCHAR(20),
StatusId VARCHAR(2),
Flag INT,
Createddate Datetime)

INSERT INTO @Daystaken (CreatedDate)VALUES
('2015-03-06 17:59:59.410'),
('2015-03-02 17:59:59.410')
select DATEDIFF(DD,MIN(CreatedDate),GETDATE())D from @Daystaken

DECLARE   @holiday TABLE(holiday Datetime)

INSERT INTO @holiday (  holiday )VALUES
(   '2014-04-06 17:59:59.410'),
(   '2014-06-06 17:59:59.410'),
(   '2015-05-05 17:59:59.410'),
(   '2015-05-01 17:59:59.410'),
(   '2013-01-06 17:59:59.410'),
(   '2015-02-03 17:59:59.410'),
(   '2011-02-01 17:59:59.410')

我有天数来自DaysTaken表现在我需要从假期表中减去天数。例如,当天的表日有122天 3天假期到现在的日期来自假期表。所以我需要减去结果并显示119天

1 个答案:

答案 0 :(得分:1)

这样做:

DECLARE @minDate AS DATE
SELECT @minDate = MIN(Createddate) FROM @Daystaken;

SELECT DATEDIFF(DAY, @minDate, GETDATE()) - COUNT(*) FROM @holiday
WHERE
    CAST(holiday AS DATE) >= @minDate
    AND CAST(holiday AS DATE) <= CAST(GETDATE() AS DATE)

这是另一个没有使用任何变量并且可以轻松转换为ITVF的那个:

WITH E1(N) AS(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
),
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, @minDate, GETDATE()))
        ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
    FROM E4
),
CteMinDate(minDate) AS(
    SELECT CAST(MIN(CreatedDate) AS DATE) FROM @Daystaken
)
SELECT
    COUNT(*)
FROM Tally t
CROSS JOIN CteMinDate md
WHERE
    DATEADD(DAY, N - 1, md.minDate) <= CAST(GETDATE() AS DATE)
    AND NOT EXISTS(
        SELECT 1
        FROM @holiday
        WHERE  CAST(holiday AS DATE) = DATEADD(DAY, N - 1, md.minDate)
    )