SQL - 获取过去7天的平均价格

时间:2017-06-20 10:25:44

标签: c# sql-server

我有一个看起来像这样的表:

timestamp | commodity | amount | price |

我试图得到商品的加权平均值,从过去7天开始每天(为了创建图表,c#程序),我设法创建一个查询来获得加权平均值:

SELECT SUM(price * amount),
       SUM(amount) 
  FROM [table_name] 
 WHERE (commodity = @commodity) 
   AND (timestamp >= @fromDate 
   AND timestamp <= @toDate);

所以,我发送此查询7次,每次都将(-1)添加到fromDate和toDate,以获得过去7天的平均值。

我想询问是否有办法在1个查询中执行此操作,如果存在,是否可以实现以获取上个月的相同信息。

4 个答案:

答案 0 :(得分:1)

您可以使用转换为日期并执行以下代码:

  SELECT convert(date, timestamp) as [Dates], 
         SUM(price * amount),
         SUM(amount) 
    FROM [table_name] 
   WHERE (commodity = @commodity) 
     AND (timestamp >= @fromDate 
     AND timestamp <= @toDate)
GROUP BY convert(date, timestamp)

答案 1 :(得分:0)

你必须按日期分组

 SELECT SUM(price* amount),SUM(amount) FROM [table_name] WHERE (commodity = @commodity) AND (cast(timestamp  as date)>= @fromDate AND cast(timestamp  as date)<= @toDate)
Group By cast(timestamp  as date)

答案 2 :(得分:0)

您应该按日期对数据进行分组:

SELECT SUM(price * amount),SUM(amount) 
FROM [table_name] 
WHERE (commodity = @commodity) 
AND (timestamp >= @fromDate 
AND timestamp <= @toDate)
GROUP BY CAST(timestamp as DATE);

答案 3 :(得分:0)

要生成日期,您可以按如下方式使用:

;with Datescte as (
      Select top (datediff(day, @fromDate, @toDate) +1) Dt = Dateadd(day, Row_Number() over (order by (Select null))-1, @fromDate) 
        from master..spt_values s1, master..spt_values s2
    ), cte2 as (
      SELECT convert(date, timestamp) as [Dates], 
             SUM(price * amount) as [Sum_Price_Amount],
             SUM(amount) as [Sum_Amount] 
        FROM [table_name] 
       WHERE (commodity = @commodity) 
         AND (timestamp >= @fromDate 
         AND timestamp <= @toDate)
    GROUP BY convert(date, timestamp)
    )
      Select Dt as [Dates] , Sum_Price_Amount, Sum_Amount 
        FROM Datescte d
        LEFT JOIN cte2 d2
          ON d.Dt = d2.Dates