SQL - AVG 和分组依据

mil*_*nDD 3 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
Run Code Online (Sandbox Code Playgroud)

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

Date      |   Product |   Price 
06-12-17  |    1      |   25
05-12-17  |    1      |   30
Run Code Online (Sandbox Code Playgroud)

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

产品从 1.1 到 24.4

zar*_*ruq 5

如果您只需要product, castto 的左侧部分,int然后使用结果值和 进行聚合date

select date, 
       cast(product as int) as product, 
       avg(price) as Price
from table1
group by date, cast(product as int)
Run Code Online (Sandbox Code Playgroud)

结果:

date        product Price
--------------------------
05-12-17    1       30
06-12-17    1       25
Run Code Online (Sandbox Code Playgroud)

演示


更新:

如果产品是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)
Run Code Online (Sandbox Code Playgroud)

Varchar() 数据类型演示