SQL query with avg and group by

前端 未结 2 432
自闭症患者
自闭症患者 2020-12-01 12:35

I have some problems with writing a SQL query for MySQL. I have a table with the following structure:

mysql> select id, pass, val from data_r1 limit 10;
+         


        
相关标签:
2条回答
  • 2020-12-01 12:46

    As I understand, you want the average value for each id at each pass. The solution is

    SELECT id, pass, avg(value) FROM data_r1
    GROUP BY id, pass;
    
    0 讨论(0)
  • 2020-12-01 12:56

    If I understand what you need, try this:

    SELECT id, pass, AVG(val) AS val_1 
    FROM data_r1 
    GROUP BY id, pass;
    

    Or, if you want just one row for every id, this:

    SELECT d1.id,
        (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
         WHERE d2.id = d1.id AND pass = 1) as val_1,
        (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
         WHERE d2.id = d1.id AND pass = 2) as val_2,
        (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
         WHERE d2.id = d1.id AND pass = 3) as val_3,
        (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
         WHERE d2.id = d1.id AND pass = 4) as val_4,
        (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
         WHERE d2.id = d1.id AND pass = 5) as val_5,
        (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
         WHERE d2.id = d1.id AND pass = 6) as val_6,
        (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
         WHERE d2.id = d1.id AND pass = 7) as val_7
    from data_r1 d1
    GROUP BY d1.id
    
    0 讨论(0)
提交回复
热议问题