SQL stament将行分组并计算平均值

时间:2015-11-12 10:13:21

标签: mysql

我遇到了以下问题。我有一个看起来像这样的表:

field_number.. Value  
````````````````````````````````  
1 ......................... 1  
2 ..........................1  
3 ......................... 2  
4 ..........................2   

我想对不同的fieldnumbers进行分组,并为value列提供平均值。所以输出应该是:

field_number................Value

name(1,2)......................   1..............       ((1+1)/2)

name(3,4)......................   2..............       ((2+2)/2)

我已检查过以前的问题,但找不到任何涵盖此问题的问题(我可能会搜索错误的关键字)。因此,如果已经涵盖了我的应用程序,那么任何帮助或指向先前的答案将不胜感激。

** =============更新============= **

我查看了你的建议,但没有把它弄好。所以我试图更具体。我几乎有我想要的结果,除了我希望在我的一个列中有固定值的事实。我有以下查询:

Select 
Avg(wp_rg_lead_detail.value),
wp_rg_lead_detail.field_number,
From
wp_rg_lead_detail
Where
wp_rg_lead_detail.field_number In (15, 17, 24) A
UNION
Select
Avg(wp_rg_lead_detail.value),
wp_rg_lead_detail.field_number,
From
wp_rg_lead_detail
Where
wp_rg_lead_detail.field_number In (16, 108, 18)

这给了我一个包含两列

的表格
wp_rg_lead_detail.value................field_number
4.3 (average)..............................15 (first value of av calculation)

我想要的是在固定值(文本)中更改字段编号(在本例中为15)。我应该如何以及如何将其添加到查询中?

3 个答案:

答案 0 :(得分:1)

SELECT avg(value) FROM table WHERE field_number in (1,2)
SELECT avg(value) FROM table WHERE field_number in (3,4)

答案 1 :(得分:1)

For a generalized answer.

SELECT CONCAT('name','(',GROUP_CONCAT(field_number),')') AS field_number,
AVG(Value) as Value
FROM table_name
group by table_name.`Value`

Hope this helps.

答案 2 :(得分:1)

If your table is really this simple, you can also get away with:

select distinct
   Value,
   count(Value) as '#'
from table_name
group by Value

If you acctually want to group by a range, than you can put the logic of the range in your grouping clause (see this fiddle)

select distinct
    avg(Value) as average,
   floor(Value),
   count(Value) as '#'
from table_name
group by floor(Value)

In the fiddle I used grouping on whole integers, but you can make that as complex as you like (see, for instance, this example)

If you are actually also interested in your corresponding fields, use group_concat() like so

select 
    Value, 
    group_concat(
        distinct field_number 
        order by Value
    ) as fields
from table_name tn1
group by Value
order by Value

output:

Value            | fields
---------------------------------
1                | 1,2      
2                | 3,4

See this fiddle implemented from this blog post