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

1つのクエリでグループ化、並べ替え、カウント

    http://sqlfiddle.com/#!9/ e9206 / 16

    望ましい結果が得られるからです:

     SELECT A.family, C.NbrFamily,A.sub_family,B.NbrSubFamily,A.name,COUNT(A.Name)
     FROM  commodities as A
    LEFT JOIN (
      SELECT family,sub_family,COUNT(Name) AS NbrSubFamily 
      FROM commodities 
      GROUP BY family,sub_family
    ) B
    ON A.sub_family = B.sub_family 
      AND A.family = B.family 
    LEFT JOIN (
      SELECT family,COUNT(Name) AS NbrFamily 
      FROM commodities 
      GROUP BY family
    ) C
    
    ON  A.family = C.family 
    GROUP BY A.family,A.sub_family,A.name
    ORDER BY A.id
    



    1. 複数のテーブルレコードを単一の行に結合する内側または左側

    2. OracleのJSON_ARRAYAGG()関数

    3. php:セッションとデータベース

    4. MariaDB NULLIF()の説明