如何计算两个日期之间的天数与条件

时间:2014-08-12 06:16:27

标签: sql sql-server sql-server-2008

我有桌子,它有以下数据:

USERID  NAME  DATEFROM      DATETO
1       xxx  2014-05-10     2014-05-15 
1       xxx  2014-05-20     2014-05-25   
4       yyy  2014-04-20     2014-04-21

现在我有sql查询,如:

select * from leave where datefrom>='2014-05-01' and dateto<='2014-05-31'

所以我现在要输出:

userid name total_leave_days
1      xxx   12
4      yyy   2

(2014-05-10 - 2014-05-15 )=6 days
(2014-05-20 - 2014-05-25 )=6 days
total = 12 days for useid 1
(2014-04-20 - 2014-04-21)= 2 days for userid 4

我怎样才能算出这总天数。?

4 个答案:

答案 0 :(得分:2)

请尝试:

select 
    USERID, 
    NAME, 
    SUM(DATEDIFF(day, DATEFROM, DATETO)+1) total_leave_days
From leave 
group by USERID, NAME

SQL Fiddle Demo

答案 1 :(得分:1)

您可以使用DateDiff

SELECT UserID, Name, SUM(DATEDIFF(DAY, DateFrom, DateTo) + 1) AS total_leave_days
FROM leave
WHERE datefrom >= '2014-05-01' AND dateto <= '2014-05-31'
GROUP BY UserID, Name

+ 1当然是因为DATEDIFF将返回独占计数,这听起来像是你想要的包含天数。

答案 2 :(得分:1)

试试这个:

select userid, name, sum (1 + datediff(day,datefrom,dateto)) as total_leave_days
from leaves
where datefrom>='2014-05-01' and dateto<='2014-05-31'
group by userid, name

这会将每个userid的总叶数相加。请注意,datediff将为您提供2014-05-10至2014-05-15范围内的5天差异,因此我们需要在结果中添加1以获得6天,即包含两端的范围。

Demo

答案 3 :(得分:1)

重要的是要注意你需要&#34; + 1&#34;模仿预期的计算,因为有一个固有的假设&#34;&#34;开始一天&#34;对于开始日期和&#34;结束日期&#34;结束日期 - 但dbms不这么认为。日期始终存储为&#34;日期开始&#34;。

select
        USERID
      , name
      , sum( datediff(day,DATEFROM,DATETO) + 1 ) as leave_days
from leavetable
group by
        USERID
      , name

产生这个:

| USERID | NAME | LEAVE_DAYS |
|--------|------|------------|
|      1 |  xxx |         12 |
|      4 |  yyy |          2 |

请参阅:http://sqlfiddle.com/#!3/ebe5d/1