SQL - AVG和Group by

时间:2017-12-06 10:22:15

标签: sql sql-server group-by average

我有下表:

Date      |   Product   |   Price 
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40

我很难在SQL Server中找到一个可以给我这个结果的查询:

Date      |   Product |   Price 
06-12-17  |    1      |   25
05-12-17  |    1      |   30

我想要每天每件产品的平均价格

产品从1.1到24.4

4 个答案:

答案 0 :(得分:3)

如果您只需要product的左侧部分,castint,则使用结果值和date进行汇总。

select date, 
       cast(product as int) as product, 
       avg(price) as Price
from table1
group by date, cast(product as int)

<强>结果:

date        product Price
--------------------------
05-12-17    1       30
06-12-17    1       25

<强> DEMO

<强>更新

如果产品属于varchar数据类型,请使用cast两次。

select date, 
       cast(cast(product as dec(3,1)) as int) as product, 
       avg(price) as Price
from table1
group by date, cast(cast(product as dec(3,1)) as int)

<强> Varchar() Datatype DEMO

答案 1 :(得分:2)

取决于您想要输出的数字。 喜欢如果

    每个号码
  • FLOOR()
  • cast(product as int)转换为int
  

查询:

 SELECT
  Date,
  FLOOR(product) product, // This function can be replaced with above according to the output
  AVG(price) price

FROM your_table
GROUP BY date, FLOOR(product) order by Date

正如您所说输出为错误,您也可以尝试以下操作。

 SELECT
  Date,
  FLOOR(convert(float, product)) product, // This function can be replaced by FLOOR(cast(product as float))
  AVG(price) price

FROM your_table
GROUP BY date, FLOOR(convert(float, product)) order by Date;

答案 2 :(得分:0)

假设每个产品值都有'。'(点)。否则从第2行删除-1。

SELECT Date,
   LEFT(CAST(product AS VARCHAR),charindex ('.',product) - 1),
   AVG(price)
FROM TABLE
GROUP BY Date, LEFT(CAST(product AS VARCHAR),charindex ('.',product) - 1);

答案 3 :(得分:0)

试试这个:

     SELECT date,cast(product AS int) product,avg(Price) Price FROM (
     SELECT * FROM (VALUES 
     (cast('06-12-17' as date) ,    1.1      ,   10)
     ,(cast('06-12-17' as date) ,    1.2      ,   20)
     ,(cast('06-12-17' as date) ,    1.3      ,   30)
     ,(cast('06-12-17' as date) ,    1.4      ,   40)
     ,(cast('05-12-17' as date) ,    1.1      ,   20)
     ,(cast('05-12-17' as date) ,    1.2      ,   20)
     ,(cast('05-12-17' as date) ,    1.3      ,   40)
     ,(cast('05-12-17' as date) ,    1.4      ,   40)) a(Date      ,   
     Product   ,   Price ))x
     GROUP BY date,cast(product AS int)