查找名称上的行的平均值;显示所有行

时间:2017-11-06 06:31:19

标签: mysql sql group-by

我有一个包含以下值的表格

name    symbol  current value
a       a1      1
a       a2      2
a       a3      4
a       a4      3
a       a5      5
b       b1      6
b       b2      7
b       b3      8
c       c1      1
c       c2      2
c       c3      3
c       c4      3
c       c5      5
d       d1      6
d       d2      6

必需:要按名称查找当前值分组的平均值,请显示所有结果。即;结果显示如下;

name    symbol  current value   Required
a       a1              1           =current value/(sum of all 'a' current values)
a       a2              2           =current value/(sum of all 'a' current values)
a       a3              4           =current value/(sum of all 'a' current values)
a       a4              3           =current value/(sum of all 'a' current values)
a       a5              5           =current value/(sum of all 'a' current values)
b       b1              6           = current value /(sum of all 'b' current values)
b       b2              7           = current value /(sum of all 'b' current values)
b       b3              8           = current value /(sum of all 'b' current values)

同样适用于所有名称

2 个答案:

答案 0 :(得分:1)

加入查找平均值的子查询:

SELECT t1.*,
    CASE WHEN t2.avg > 0 THEN t1.current_value / t2.avg ELSE 0 END AS avg
FROM yourTable t1
INNER JOIN
(
    SELECT name, SUM(current_value) AS avg
    FROM yourTable
    GROUP BY name
) t2
    ON t1.name = t2.name;

CASE表达式是必要的,以防止可能的除以零,如果给定的name恰好具有所有零电流值,则可能发生这种情况。在这种情况下,我将平均值默认为零。

答案 1 :(得分:0)

尝试这个逻辑:)

SELECT
    *
FROM
    table_listing_sample
WHERE
    NAME = 'a'
AND NAME = 'b'
ORDER BY
    id