如何根据SQL中的给定日期获取记录

时间:2015-08-03 18:48:52

标签: sql sql-server

我正在尝试根据下表中给定的两个日期来计算天数和Reading。我在SQL方面经验不足,但没有任何线索可以解决这个问题,请大家帮帮我。

Create Table Meter_Reading(ID(int),From_Date (Datetime), To_Date(Datetime), Reading (int))

    INSERT INTO Meter_Reading VALUES (1, '2015-05-15', '2015-06-14',20);
    INSERT INTO Meter_Reading VALUES (2, '2015-06-15', '2015-07-17',30);
    INSERT INTO Meter_Reading VALUES (3, '2015-07-18', '2013-08-11',10);

    Declare @StartDT Datetime,@EndDT Datetime

    SET @STARTDT = '2015-05-01'
    SET @ENDDT  = '2015-06-30'

    select ID  
          ,case when From_Date >= @StartDT THEN DATEDIFF(d,@StartDT,From_Date)
                    ELSE DATEDIFF(d,TO_Date,@ENDDT) end 'Days'
          ,Reading
    FROM Meter_Reading
    WHERE (From_Date <= @ENDDT
            and TO_Date >= @STARTDT)   

    Output with the above logic:
     1  14  20
     2  45  30

    Output Expected:
     1  31  20
     2  16  30

2 个答案:

答案 0 :(得分:0)

我认为这会给你你想要的东西。

Declare @StartDT DATE
        ,@EndDT DaTE

SET @STARTDT = '2015-05-01'
SET @ENDDT  = '2015-06-30'


select PRODUCT_ID   
        ,case when From_Date >= @StartDT THEN DATEDIFF(d,@StartDT,From_Date)
                ELSE DATEDIFF(d,TO_DATE,@ENDDT) end 'DATEDIF'
FROM TABLEName
WHERE (FROM_DATE <= @ENDDT
        and TO_DATE >= @STartDT )       

答案 1 :(得分:0)

你需要一些复杂的日期逻辑,如下所示:

select t.*,
       datediff(day, (case when t.from_date < @StartDate then @StartDate else t.from_date and),
                (case when t.to_date > @EndDate then @EndDate else t.to_date end)
               ) + 1 as diff
from table t
where t.from_date <= @EndDate and t.to_date >= @StartDate