如何使用MS SQL查询在两个日期和时间之间获取日期

时间:2014-09-01 12:30:44

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

我有表格列 像

----------------------------------------------------
DateFrom   | Dateto     | TimeFrom | TimeTo| ZoneID |
----------------------------------------------------+
2014-09-01 | 2014-09-30 | 03:00    | 08:00 |   1    |
----------------------------------------------------+
2014-09-01 | 2014-09-30 | 09:00    | 15:00 |   1    |  
----------------------------------------------------+
2014-09-01 | 2014-09-30 | 16:00    | 23:00 |   1    |
----------------------------------------------------+
2014-09-01 | 2015-09-30 | 03:00    | 08:00 |   2    |

我希望在datefrom和dateto,timefrom和timeto之间记录 如果我试图获得日期2014-10-03然后它显示所有记录请帮助如何使用SQL查询获取特定记录。 谢谢你提前。

我希望获得todate和fromdate之间的记录,时间和时间两者

这个查询我写的请检查。

    SELECT       
    Tariff.TariffZoneID,CAST(TariffDate.TimeFrom AS VARCHAR(32)) AS TimeFrom ,CAST(TariffDate.TimeTo AS VARCHAR(32)) AS TimeTo,'2014-09-25 00:00:00.000' AS DateFrom,'2014-09-25 00:00:00.000' AS DateTo,TariffZone.Name,TariffZone.MaximumPrice,
    TariffZone.FactionMinute,Tariff.SequenceNo,tariffdate.weekId,   Tariff.Time,Tariff.IsFaction,Tariff.Amount
FROM 
    TariffDate 
    INNER JOIN TariffZone ON TariffDate.TariffZoneID = TariffZone.TariffZoneID 
    INNER JOIN Tariff ON TariffZone.TariffZoneID = Tariff.TariffZoneID 
    WHERE TariffDate.TariffDateID >= (
            SELECT ISNULL(MAX(tariffdateid), 0) 
            FROM TariffDate 
            where datefrom <= cast('2014-09-25 00:00:00.000' as date) 
            and timeFrom<=cast('05:00:00.0000000' as time) and FacilityID =2 and WeekID= datepart(dw,CAST('2014-09-25 00:00:00.000' AS DATE)) 
            )
    AND
    TariffDate.TariffDateID <= 
    (
        SELECT ISNULL(MIN(tariffdateid) , 0)
        FROM TariffDate 
        WHERE dateto <= CAST('2014-09-25 00:00:00.000' AS DATE) 
        and  timeTo <=CAST('07:00:00.0000000' AS TIME) 
        and FacilityID =2 and WeekID= datepart(dw,CAST('2014-09-25 00:00:00.000' AS DATE))) 
    and Tariff.FacilityID =2 

3 个答案:

答案 0 :(得分:0)

您应该合并DateFromTimeFrom列值,并使用datetime sql类型。 像这样修改SQL条件:

  WHERE (CAST(CAST(DateFrom AS DATE) AS DATETIME) + CAST(TimeFrom  AS TIME)) <= '2014-09-25 05:00:00'
        AND FacityID=....

  WHERE (CAST(CAST(DateTo AS DATE) AS DATETIME) + CAST(TimeTo  AS TIME)) <= '2014-09-25 07:00:00'
        AND FacityID=....

您没有获得所有记录,因为对于符合条件的每个日期,您只获得与单独时间条件匹配的记录(&lt; 7:00等)。

答案 1 :(得分:0)

SELECT * FROM test WHERE CONCAT(datefrom,'',timefrom)&lt; ='2014-08-07 10:00'

你可以通过使用CONCAT

来简化

答案 2 :(得分:0)

我希望,如果您使用以下代码结构作为查询的过滤器,它将获取fromdate到todate的记录。

WHERE (CAST('2014-09-25 00:00:00.000' AS DATE)!>dateto and CAST('2014-09-25 00:00:00.000' AS time) !>timeTo)...
and (CAST('2014-09-25 00:00:00.000' AS DATE)!<datefrom and CAST('2014-09-25 00:00:00.000' AS time) !<timeFrom)...