28
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLのcase式で重複排除してカウントする

Posted at
SELECT COUNT(DISTINCT CASE 
        WHEN table.column >= 1 AND table.column <= 10 
        THEN table.id END)
FROM table

ポイントは、case式でIDを出力している点です。単純にcase式で数をカウントする例文は以下ですが

SELECT SUM(CASE 
        WHEN table.column >= 1 AND table.column <= 10 
        THEN 1 ELSE 0 END)
FROM table

これでは重複排除のための情報が落ちてしまっています。case式で特定の条件で絞られたIDの配列を返した後、COUNT DISTINCT を用いることで重複排除したカウントが行えます。

WHERE句を使えば同じ事が実現出来ますが、SELECT文で上記のカウントを行いたい場合に有効です。

28
23
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
28
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?