0
0

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! Day40 <要復習:分析関数COUNT() OVER()句内でDISTINCTは使えない!?>

Posted at

550. Game Play Analysis IV (問題レベル: Medium)要課金

今日の問題はこれ。
全ユーザーの中で初日から2日連続プレイした人の割合を計算するという問題。

最終的に提出した回答はこちら。

SQL
SELECT
    ROUND(COUNT(b.player_id)*1.0/COUNT(DISTINCT a.player_id)*1.0,2) AS fraction
FROM 
    (SELECT player_id, MIN(event_date) AS fday FROM activity GROUP BY player_id) a
LEFT JOIN
    activity b
ON DATEDIFF(day, a.fday, b.event_date)=1 AND a.player_id=b.player_id

ロジックはそれほど難しくないが、初日の取得、重複したIDの処理など細かい処理が重なるためヒント無しでは出来ませんでした。

躓いたのは、

SQL
SELECT a.player_id, COUNT(DISTINCT b.player_id) OVER() AS b
FROM activity a
LEFT JOIN
activity b
ON a.player_id=b.player_id

このように分析関数ではCOUNT() OVER()句内でDISTINCTは使えない!?ようです。
自信が無いのですが、調べた限りは使え無さそう。この辺りまた復習します!

今日のポイントはCOUNT() OVER()句内でDISTINCTは使えない!?としました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?