LoginSignup
2
1

More than 5 years have passed since last update.

集計時、グループ内の種類のカウントをするSQL

Posted at

SQLでグループ内の種類をカウントしたい場合は以下のようにすると、取得できる。

COUNTでNULLをカウントされない仕様を利用しているから、データベースによっては利用できないかも。
(Oracleだと使える。)

社員テーブルの部内の課の種類の数をカウントしている。

sample.sql

SELECT 部
     , COUNT(DISTINCT CASE WHEN 課 = 'ABC'
                           THEN NULL
                           ELSE 課 END) 課件数
     , COUNT(社員ID) 社員件数
  FROM 社員
 GROUP BY 部
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1