如何计算天数?

时间:2009-10-13 13:59:20

标签: sql-server

使用SQL Server 2005

表1

ID FromDate ToDate

001 23-02-2009 25-02-2009
001 27-02-2009 29-02-2009
002 12-02-2009, 25-03-2009

...

表2

ID Name Total

001 Raja 30
002 Ravi 22

我想获得这个人格的总天数

尝试查询,

SELECT
   table2.Id, table2.name, table2.total, 
   datediff(day, table1.fromdate, table2.todate) 
FROM table1 
LEFT OUTER JOIN table2 ON table1.personid = table2.personid

获取输出

ID Name Total Days

001 Raja 30 3
001 Raja 30 3
...,

它应该总计天数,它应该显示在一行中,

注意:假设我选择特定的期间日期意味着它应该仅显示那些天

例如

其中日期为26-02-2009至03-03-2009,应显示

ID Name Total Days

001 Raja 30 3
...,

因为我是在2009年2月25日之后的日期,

Expected Output

ID Name Total Days

001 Raja 30 6
002 Ravi 22 16

如何修改我的查询?

3 个答案:

答案 0 :(得分:0)

SELECT  table2.Id, table2.name, table2.total,
        COALESCE(
        (
        SELECT  SUM(DATEDIFF(day, table1.fromdate, table1.todate) + 1)
        FROM    table1
        WHERE   table1.personid = table2.personid
        ), 0) AS [days]
FROM    table2

答案 1 :(得分:0)

我认为GROUP BY查询会更简单:

SELECT table2.Id, table2.name, table2.total, 
SUM(DATEDIFF(day, table1.fromdate, table1.todate)) AS Days
FROM table1 
left outer join table2 on 
table1.personid = table2.personid
GROUP BY table2.Id, table2.name, table2.total

答案 2 :(得分:0)

DATEDIFF给出了两个日期之间的天数差异,因此以相同的方式,1和3之间的差异为2(3 - 1 = 2),DATEDIFF(d)实际上是D2 - D1。因此,为了弥补您想要计算的额外日期,您需要每天DATEADD(ToDate或FromDate)来抵消您的日期:

SELECT table2.id, table2.Name, table2.Total, SUM(DATEDIFF(d, DATEADD(d, -1, table1.FromDate), table1.ToDate))
    FROM table1
        INNER JOIN table2 ON table1.id = table2.id
    GROUP BY table2.id, table2.Name, table2.Total