在SQL表的日期字段中将值除以一个月中的天数

时间:2014-12-04 21:40:43

标签: sql-server datetime

我正在研究一个SQL查询,它根据日期列中的值对SQL表中的数据执行一些算术除法。

详细说明我有以下SQL表Deals

id  Date        Type   Quantity Price 
3   2014-11-04  Sweet   2500    23    
9   2014-12-04  Sweet   5000    30      
10  2014-12-04  Midale  2500    25.4    
11  2014-11-04  Sweet   5000    45    

现在,我想对按类型和日期分组的数量列进行一些算术运算。

我使用了以下查询

SELECT 
    Type,
    COUNT(Id) AS Trades, 
    SUM(Quantity ) AS M3,
    ROUND((6.2898*SUM(Quantity ))/31,4) AS BBLperDay, 
    CAST(Date as date) AS TradeMonth,
    ROUND(SUM(Quantity*Price)/Sum(Quantity),4) AS WeightedAverage
FROM Deals 
GROUP BY 
    Type,CAST(Date as date)

以上查询返回

   Type  Trades     M3     BBLperDay    TradeMonth
   Sweet    2     7500  1521.7258   2014-11-04
   Midale   1     2500  507.2419    2014-12-04
   Sweet    1     5000  1014.4839   2014-12-04

上述结果是正确的,但我在表达式

中的日期硬编码为31天
  6.2898*SUM(Quantity )/31 AS BBLperDay

有没有办法可以根据月份从Date列中获取值。如果月份是日期列中的12月,则该值将自动为31,因为12月的天数为31。

1 个答案:

答案 0 :(得分:4)

找不到。一个月内的几天

Select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,getdate()),0)))

或如果您使用SQL SERVER 2012+

Select DAY(EOMONTH(getdate()))

像这样更改您的查询。

SELECT 
    Type,
    COUNT(Id) AS Trades, 
    SUM(Quantity ) AS M3,
    ROUND((6.2898*SUM(Quantity ))/DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,TradeMonth),0))),4) AS BBLperDay, 
    CAST(Date as date) AS TradeMonth,
    ROUND(SUM(Quantity*Price)/Sum(Quantity),4) AS WeightedAverage
FROM Deals 
GROUP BY 
    Type,CAST(Date as date),TradeMonth