0
1

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 3 years have passed since last update.

100日でSQLの達人になる@LeetCode! Day27 <GROUP BYとUNIONを一緒に使う時は注意が必要>

Posted at

1341. Movie Rating (問題レベル: Medium)要課金

今日の問題はこれ。
最も多くの映画にratingを投票しているユーザー名と最も平均レビュー点数が高い映画をリストアップするという問題。

全く異なる変数をリストアップする問題のためUNIONを使うことはすぐに分かりました。
また、一人だけ、一本だけリストするためにSELECT TOP1 変数名もすぐに分かりました。
ユーザー名だけ、映画名だけをリストするのはすぐに出来ましたが、UNIONでエラーが出てしまう。
調べるとMS SQL Server(だけではない!?)ではGROUP BYUNIONを一緒に使う時にはエラーがおきるようだ。

つまり、これでは駄目で(注:説明のため、簡略化して記載するためにこの問題の回答とは異なります)

MS SQL Server
SELECT TOP 1 mr.user_id AS result
FROM movierating mr
GROUP BY mr.user_id
ORDER BY count(*), mr.user_id ASC
UNION
SELECT TOP 1 mr.movie_id  AS result
FROM movierating mr
GROUP BY mr.movie_id
ORDER BY count(*), mr.movie_id ASC
MS SQL Server
SELECT t1.user_id AS result
FROM (
SELECT TOP 1 mr.user_id
FROM movierating mr
GROUP BY mr.user_id
ORDER BY COUNT(*), mr.user_id ASC
) t1
UNION
SELECT t2.movie_id AS result
FROM (
SELECT TOP 1 mr.movie_id
FROM movierating mr
GROUP BY mr.movie_id
ORDER BY COUNT(*), mr.movie_id ASC
) t2

のように一旦テーブルの中でGROUP BY, ORDER BYをした結果をSELECT文でもう一度取り出す形になる。

今日のポイントはGROUP BYUNIONを一緒に使う時には注意が必要!

  • LeetCodeの問題は、MS SQL Serverで解いています。
0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?