本月底之前的SQL天数

时间:2015-03-10 14:46:03

标签: sql sql-server

我有交易表,看起来像:

+----+--------------+----------------+------+
| ID |  OrderDate   |  DeliveryDate  |  EUR |
+----+--------------+----------------+------+
| 1  | 2015-02-21   |  2015-02-25    | 100  |
| 2  | 2015-03-01   |  2015-03-14    | 110  |
| 3  | 2015-03-01   |  2015-03-17    |  90  |
| 4  | 2015-03-10   |  2015-03-20    | 250  |
| 5  | 2015-03-31   |  2015-03-31    | 350  |
+----+--------------+----------------+------+

我需要根据订单交付月份之前的天数获得收入和订单数量(COUNT个ID)。

SELECT datediff(day, OrderDate, CAST(DATEADD(month, DATEDIFF(month,0,getdate()+1,0)-1) as Date) as DBEOM, SUM(EUR) as Rev, COUNT(ID) as NumberOfOrders

FROM transactions
WHERE MONTH(DeliveryDate) = 3 AND YEAR(DeliveryDate) = 2015

GROUP BY datediff(day, OrderDate, CAST(DATEADD(month, DATEDIFF(month,0,getdate()+1,0)-1) as Date) as DBEOM
ORDER BY 1

这种情况下的结果如下:

+-----+-----+----------------+
|DBEOM| Rev | NumberOfOrders |
+-----+-----+----------------+
|   0 | 350 |              1 |
|  21 | 250 |              1 |
|  30 | 200 |              2 |
+-----+-----+----------------+

这是在SQL 2008中完成的,所以我不能简单地使用EOMONTH。我试过了,上面是什么,但我得到了 错误 -

  

[Microsoft] [ODBC SQL Server驱动程序] [SQL Server] datediff函数   需要3个参数。

非常感谢您的建议!

2 个答案:

答案 0 :(得分:0)

我发现的最简单的方法是在本月的最后一天使用更原始的函数来获取下个月的第一天然后减去一天。

我不是TSQL的人,所以这种语法可能不会是正确的,但你需要更像

的东西

DATEADD(日,DATEFROMPARTS(DATEPART(年,DATEADD(月,1,getdate()),DATEPART(月,DATEADD(月,1,getdate()),1), - 1)

答案 1 :(得分:0)

尝试:

SELECT datediff(day,
              OrderDate,
              dateadd(DAY,
                      -1,
                      dateadd(MONTH,
                              1,
                              dateadd(DAY,
                                      1-day(DeliveryDate),
                                      DeliveryDate
                                     )
                             )
                     )
             ) as DBEOM, SUM(EUR) as Rev, COUNT(ID) as NumberOfOrders

FROM t
WHERE MONTH(DeliveryDate) = 3 AND YEAR(DeliveryDate) = 2015

GROUP BY datediff(day,
              OrderDate,
              dateadd(DAY,
                      -1,
                      dateadd(MONTH,
                              1,
                              dateadd(DAY,
                                      1-day(DeliveryDate),
                                      DeliveryDate
                                     )
                             )
                     )
             )
ORDER BY 1

sqlfiddle.com