来自多列的SQL平均值

时间:2014-06-25 00:31:17

标签: mysql sql sql-server mysql-workbench

如何从多列获得平均值?
 例如:

Columns:   ID 125Hz 250Hz 500Hz 750Hz 1000Hz 1500Hz 2000Hz 3000Hz 4000Hz 6000Hz 8000Hz
Values:    1  92    82     63    83    32     43     54     56     54     34      54

我想获得除ID之外的所有列的平均值。我该怎么做?

5 个答案:

答案 0 :(得分:2)

在SQL-SERVER中,您可以使用此

DECLARE @total int
DECLARE @query varchar(550)
DECLARE @ALLColumns VARCHAR(500)
SET @ALLColumns = ''

    ----Build the string columns
SELECT  @ALLColumns = @ALLColumns + '+' + '['+sc.NAME+']'
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%YOUR_TABLE_NAME%' 
AND sc.NAME LIKE  '[0-9]%';--[0-9]% just get the column that start with number
    ----Get the total number of column, 
SELECT @total = count(*) FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%YOUR_TABLE_NAME%' 
AND sc.NAME LIKE  '[0-9]%';--[0-9]% just get the column that start with number

SET @query = 'SELECT SUM('+ SUBSTRING(@ALLColumns,2,LEN(@ALLColumns))+')/'
    +CAST(@total as varchar(4))+ ' AS [AVG] 
    FROM [YOUR_TABLE_NAME] 
    GROUP BY [ID]'

--SELECT @query 
EXECUTE(@query) 

这将执行如下的查询:

SELECT SUM([125Hz]+[250Hz]+[500Hz]+[750Hz]+[1000Hz]+[1500Hz]+[2000Hz]
           +[3000Hz]+[4000Hz]+[6000Hz]+[8000Hz])/11 AS [AVG] 
FROM [YOUR_TABLE_NAME] GROUP BY [ID]

<强>更新

添加一个列来存储avg,我称之为[AVG]并将@query的值变为

SET @query = '
CREATE TABLE #Medition (ID int,[AVG] decimal(18,4))
INSERT INTO #Medition (ID,[AVG]) 
SELECT ID,SUM ('+ SUBSTRING(@ALLColumns,2,LEN(@ALLColumns))+')/'
+CAST(@total as varchar(10)) 
+ ' AS [AVG] FROM Medition GROUP BY ID
UPDATE YOUR_TABLE_NAME  SET YOUR_TABLE_NAME.[AVG] = #Medition.[AVG]
FROM YOUR_TABLE_NAME INNER JOIN #Medition ON YOUR_TABLE_NAME.ID =#Medition.ID
DROP TABLE #Medition
'

注意:构建查询字符串有点难看

答案 1 :(得分:1)

您必须手动添加列,因为没有可用于水平聚合的内置函数。

select (125Hz+250Hz+500Hz+750Hz+1000Hz+1500Hz+2000Hz+3000Hz+4000Hz+6000Hz+8000Hz)/11 as aveHz from table_name

答案 2 :(得分:0)

SELECT sum(125Hz + 250Hz + 500Hz + 750Hz + 1000Hz + 1500Hz + 2000Hz + 3000Hz + 
4000Hz + 6000Hz + 8000Hz)/11 as averageHz from TABLE

答案 3 :(得分:0)

另一种方法,在没有实际使用幻数11的情况下,更加冗长。

WITH t1 AS
(
    SELECT * FROM myTable
    WHERE (...) -- Should limit result to 1 row
),
t2 AS
(
    SELECT col1 FROM t1
    UNION ALL
    SELECT col2 FROM t1
    UNION ALL
    (...)
)
SELECT AVG(col1) FROM t2;

答案 4 :(得分:0)

这将显示您拥有的每个ID的所有字段的平均值。

SELECT AVG(125Hz+250Hz+500Hz+750Hz+1000Hz+1500Hz+2000Hz+3000Hz+4000Hz+6000Hz+8000Hz) 
AS Average FROM table
GROUP BY ID