需要为Date逻辑编写查询

时间:2015-05-25 11:12:50

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

我有一个下面的查询,其中包含EST_PICK_DATE between '2015-02-01' and '2015-06-01'之类的日期过滤器,其中逻辑EST_PICK_DATE应该是当月和下个月的第一个月的3个月。 当前月份的I.E,EST_PICK_DATE应该在'2015-02-01''2015-06-01'之间 我需要动态地写下面的查询 在下面的查询中,我已经对值'2015-02-01''2015-06-01'进行了硬编码,但它应该是动态的 怎么做到这一点?我在SSIS包中使用此查询,那么我应该在SQL级别中执行还是应该在包中实现此逻辑?如果是,怎么样?

INSERT INTO STG_Open_Orders (Div_Code, net_price, gross_price)
SELECT ord.DIV_CODE AS Div_Code, ord_l.NET_PRICE AS net_price, ord_l.gross_price AS gross_price, 
FROM ORD ord inner join ORD_L ord_l ONord.ORD_ID=ord_l.ORD_ID
WHERE ord_l.EST_PICK_DATE BETWEEN '2015-02-01' AND'2015-06-01'

3 个答案:

答案 0 :(得分:5)

试试这个

INSERT INTO STG_Open_Orders (Div_Code, net_price, gross_price)
SELECT ord.DIV_CODE AS Div_Code, ord_l.NET_PRICE AS net_price, ord_l.gross_price AS gross_price, 
FROM ORD ord inner join ORD_L ord_l ONord.ORD_ID=ord_l.ORD_ID
WHERE ord_l.EST_PICK_DATE BETWEEN DATEADD(m, DATEDIFF(m, 0,DATEADD(month,-3,getdate())), 0) AND DATEADD(m, DATEDIFF(m, 0,DATEADD(month,1,getdate())), 0)

这是您的开始日期和结束日期功能

SELECT DATEADD(m, DATEDIFF(m, 0,DATEADD(month,-3,getdate())), 0)
2015-02-01 00:00:00.000

SELECT DATEADD(m, DATEDIFF(m, 0,DATEADD(month,1,getdate())), 0)
2015-06-01 00:00:00.000

具体日期:

Declare @YourDate as date = '6/3/2015' -- note the format is mm/dd/yyyy
SELECT CAST(DATEADD(m, DATEDIFF(m, 0,DATEADD(month,-3,@YourDate)), 0) as date)
SELECT CAST(DATEADD(m, DATEDIFF(m, 0,DATEADD(month,1,@YourDate)), 0) as date)

答案 1 :(得分:3)

您可以使用GETDATE()和一些sql技巧来获取每月的第一天:

INSERT INTO STG_Open_Orders (Div_Code, net_price, gross_price)
SELECT ord.DIV_CODE AS Div_Code, 
       ord_l.NET_PRICE AS net_price, 
       ord_l.gross_price AS gross_price, 
FROM ORD ord 
inner join ORD_L ord_l ONord.ORD_ID=ord_l.ORD_ID
WHERE ord_l.EST_PICK_DATE BETWEEN 
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-3, 0) -- first day 3 months ago
AND 
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())+1, 0) -- first day next month

答案 2 :(得分:2)

试试这个(根据系统的当前日期):

angular.module('env_settings')
.value('address', {

    management: null,
    data_store: null,
    repository: null,

    single_service: null
});