1

我正在使用日期范围受两个字段(开始和结束)约束的表格:

ID  |  START      |  END
1      2010-01-01    2010-07-01
2      2011-01-01    2011-07-01
3      2012-01-01    2013-07-01
4      2013-01-01    2013-07-01
5      2009-01-01    2013-07-01

我可以通过如下查询粗略估计所有范围表示的“月”数:

SELECT SUM(DATEDIFF(dy, Start, End) / 30) as Total_Months
FROM TABLE

我更想做的是查询给定时间段内的所有范围代表多少个月(或几天)。

因此,如果我问上面示例中的时间段代表了多少个月[2013-01-01 - 2013-07-01],它会说18(第 3、4 和 5 行各 6 个)。

实现这一目标的最佳方法是什么?

4

2 回答 2

1

更新:你可以这样做

SELECT SUM(DATEDIFF(dy, 
                    CASE WHEN '2013-01-01' > Start THEN '2013-01-01' ELSE Start END,
                    CASE WHEN '2013-07-01' < [End] THEN '2013-07-01' ELSE [End] END) / 30) Total_Months
  FROM Table1
 WHERE '2013-01-01' BETWEEN Start AND [End]
   AND '2013-07-01' BETWEEN Start AND [End]

输出:

| TOTAL_MONTHS |
----------------
| 18 |

这是SQLFiddle演示

于 2013-08-01T22:14:49.387 回答
0

像这样的东西?

SELECT SUM(DATEDIFF(dy, Start, End) / 30) as Total_Months
WHERE Start >= '2013-01-01' AND End <= '2013-07-01'
FROM TABLE

或使其参数化:

SELECT SUM(DATEDIFF(dy, Start, End) / 30) as Total_Months
WHERE Start >= @startDate AND End <= @endDate
FROM TABLE
于 2013-08-01T22:10:08.897 回答