我有日期范围的表格,如下所示:
DATE DATE2
14.03.2013 17.03.2013
13.04.2013 02.05.2013
我必须创建一个过程,它返回等于两个日期范围的日期计数,一个在表格中,另一个在日期范围内。
例如,我在表中的日期范围如此14.03.2013 - 17.03.2013和另一个,在此过程中声明如此02.03.2013 - 16.03.2013,所以在这种情况下,日计数将是3,因为,两个日期范围的日期都在2013年3月14日至2013年3月16日之间。
答案 0 :(得分:1)
假设您的表名为daterange,并且您在过程中定义了参数@ param1和param2,那么这些行上的某些内容应该有效:
set @param1 := cast('2013-03-14' as date);
set @param2 := cast('2013-03-16' as date);
select
datediff(least(date2,@param2),@param1)+1
from daterange where @param1 between date1 and date2
请参阅sqlfiddle
中的示例答案 1 :(得分:0)
您应该能够将此T-SQL功能调整为MySQL
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_RPT_OverlappingDateRangesDays]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_RPT_OverlappingDateRangesDays]
GO
-- ======================================================================================================================
-- Author: Stefan Steiger
-- ALTER date: 11.06.2015
-- Alter date: 11.06.2015
-- Description: Calculate the number of overlapping days in two date-ranges
-- http://stackoverflow.com/questions/20836429/how-to-gets-the-number-of-overlapping-days-between-2-ranges
-- ======================================================================================================================
-- DECLARE @firstStart datetime
-- DECLARE @firstEnd datetime
-- DECLARE @secondStart datetime
-- DECLARE @secondEnd datetime
-- SET @firstStart = '01.01.2015'
-- SET @firstEnd = '31.01.2015'
-- SET @secondStart = '15.01.2014'
-- SET @secondEnd = '15.02.2015'
-- SELECT dbo.fu_RPT_OverlappingDateRangesDays( @firstStart, @firstEnd, @secondStart, @secondEnd )
CREATE FUNCTION [dbo].[fu_RPT_OverlappingDateRangesDays]
(
@firstStart datetime
,@firstEnd datetime
,@secondStart datetime
,@secondEnd datetime
)
RETURNS integer
AS
BEGIN
DECLARE @maxStart datetime
DECLARE @minEnd datetime
DECLARE @interval int
IF @firstStart IS NULL OR @firstEnd IS NULL OR @secondStart IS NULL OR @secondEnd IS NULL
-- RETURN 0
RETURN NULL
IF @firstEnd < @firstStart
RETURN 0
IF @secondEnd < @secondStart
RETURN 0
SET @maxStart = @secondStart
SET @minEnd = @secondEnd
IF @firstStart > @secondStart
SET @maxStart = @firstStart
IF @firstEnd < @secondEnd
SET @minEnd = @firstEnd
-- PRINT @maxStart
-- PRINT @minEnd
--SET @interval = DATEDIFF(DAY, @maxStart, @minEnd) + 1
SET @interval = {fn timestampdiff(SQL_TSI_DAY, @maxStart, @minEnd)} + 1
IF @interval < 0
SET @interval = 0
-- PRINT @interval
RETURN @interval
END
GO