table>>>销售
state | date | item | px
101 1/1/2012 tennis 2
101 1/1/2012 soccer 10
101 1/1/2012 crystal 100
101 1/1/2012 soccer 10
102 1/1/2012 crystal 100
102 1/1/2012 tennis 2
102 1/2/2012 tennis 2
103 1/2/2012 tennis 2
103 1/2/2012 crystal 100
103 1/3/2012 soccer 10
103 1/3/2012 crystal 100
$query="SELECT state, MAX(date), COUNT(state), AVG(px) FROM sales GROUP BY state ORDER by state ASC";
...生产:
state | date | item count | avg px
101 1/1/2012 4 30.5
102 1/2/2012 3 34.67
103 1/3/2012 4 53
问题:如何修改查询以生成每个州的DISTINCT项的平均px? (而不是每个州中所有项目的平均px)
例如,州101的平均值应为/(2 + 10 + 100)/ 3 = 37.33;即1个网球,1个足球和1个水晶的平均px。
08-04-12编辑>>>将第二个表中的px列标题更改为avg px。 /为清晰起见而编辑。 THX。
答案 0 :(得分:0)
试一试。
编辑:根据项目和状态添加内部查询到不同。
SELECT
state,
CONVERT(DATETIME, AVG(AverageDate)) AS AverageDate,
SUM(ItemCount) AS [item count],
AVG(px) AS px
FROM
(
SELECT
state,
item,
COUNT(*) AS ItemCount,
AVG(CAST(date AS INT)) AS AverageDate,
AVG(px) AS px
FROM sales
GROUP BY
state,
item
)
GROUP BY state;