SQL日期范围查询

时间:2013-08-01 21:57:49

标签: sql sql-server tsql

我正在使用一个TA​​BLE,其日期范围由两个字段(开始和结束)绑定:

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个)。

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

2 个答案:

答案 0 :(得分: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 演示

答案 1 :(得分: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