sql >> データベース >  >> RDS >> Mysql

avgとgroupbyを使用したSQLクエリ

    必要なものがわかったら、これを試してください:

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

    または、IDごとに1行だけが必要な場合は、次のようにします。

    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
    


    1. JDBCバッチ操作の理解

    2. PostgreSQL相関関数の使用

    3. 人、友人のペアのテーブルが与えられた相互の友人の数を見つけるためのSQLクエリ

    4. インデックス作成後のMySQLクエリは遅くなります