9
7

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.

Postgresでdistinct onしながらcountしようとしたらハマった

Last updated at Posted at 2018-04-11

##やろうとしたこと
あるサービスのアクセスユーザー数をセッション単位で数えたかった

table名:user_browsing_log

列名 Type note
session_id text セッションid
browsing_at timestamp without time zone アクセス日時

最初に作ったSQL

first.sql
select distinct on(session_id) count(*) from user_browsing_log;

実行結果

ERROR: column "user_browsing_log.session_id" must appear in the GROUP BY clause or be used in an aggregate function

session_idをgroup byせよとのこと

2番目に作ったSQL

second.sql
select distinct on(session_id) count(*) from user_browsing_log group by session_id;

でもこうするとあるsession_idが何回アクセスしたか、になってしまう、、、、

#####正解

correct.sql
select count(distinct session_id) from user_browsing_log;

めっちゃ単純だしsqlにしてみると当たり前も当たり前な感じだった

ある列だけを基準にdistinctして他の列も取得するときのdistinct onを使う場合が固定概念になってしまってハマっていた

9
7
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
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?