如何在SQL Server中按月计算两个日期之间的天数?

时间:2012-09-16 13:35:19

标签: sql sql-server

我在SQL服务器中有两个日期,两个月重叠我想知道每个月的圈数。 例如:

Start date is : 26-Sep-2012
End Date is : 10-Oct-2012

Sept- 5 days
October - 10 days

以及每个月的日期列表。

3 个答案:

答案 0 :(得分:2)

declare @start datetime;
declare @end datetime;
set @start = '20120926';
set @end = '20121010';

SELECT (DAY(DATEADD (m, 1, DATEADD(d, 1 - DAY(@start), @start))-1)
        - DAY(@start) + 1) AS DaysLeftStart,
        DAY(@end) AS DaysEnd

小提琴:http://sqlfiddle.com/#!3/d41d8/4441/0

答案 1 :(得分:0)

DECLARE @start DATETIME, @end DATETIME;

SELECT @start = '20120926', @end = '20121010';

;WITH c(d) AS
(
  SELECT TOP (DATEDIFF(DAY, @start, @end)+1)
    DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, @start)
    FROM sys.all_columns
) 
SELECT 
  [date] = DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0), 
  [days] = COUNT(*)
FROM c GROUP BY DATEDIFF(MONTH, 0, d)
UNION ALL SELECT d, NULL FROM c;

结果:

date                        days
-----------------------     -----
2012-09-01 00:00:00.000     5
2012-10-01 00:00:00.000     10
2012-09-26 00:00:00.000     NULL
2012-09-27 00:00:00.000     NULL
2012-09-28 00:00:00.000     NULL
2012-09-29 00:00:00.000     NULL
2012-09-30 00:00:00.000     NULL
2012-10-01 00:00:00.000     NULL
2012-10-02 00:00:00.000     NULL
2012-10-03 00:00:00.000     NULL
2012-10-04 00:00:00.000     NULL
2012-10-05 00:00:00.000     NULL
2012-10-06 00:00:00.000     NULL
2012-10-07 00:00:00.000     NULL
2012-10-08 00:00:00.000     NULL
2012-10-09 00:00:00.000     NULL
2012-10-10 00:00:00.000     NULL

答案 2 :(得分:-1)

Here您可以找到有关创建日历表的详细信息。您可以使用它来执行此类查询:

SELECT CalendarMonth, count(*) day_num 
FROM dbo.Calendar 
WHERE CalendarDate  between @start_date and @end_date;