LoginSignup
0
0

More than 1 year has passed since last update.

【忘備録】期間内に特定のカラムが複数回登録されているレコードを抽出する(SQL、Rails、Pandas)

Posted at

簡単だろうと勝手にたかを括っていたら時間が掛かってしまったため、
忘備録としてメモ。

Booksテーブルから次の条件を満たしたレコードを抽出するSQL文を作成する。

・2022年中に3回以上同じcategoryが登録されているbookレコード

(Booksテーブル)

存在するカラム:category,tag1,tag2,created_at,updated_at

created_atが2022年内なら登録されているとする。

SQL

books.sql
SELECT * 
FROM books
WHERE category in (
SELECT category
FROM books
WHERE created_at BETWEEN '2022-01-01 00:00:00' AND '2022-12-31 23:59:59'
GROUP by category
HAVING count(category) >= 3
);

Rails

目的は達成したが、気になったのでついでに考えてみる。

books.rb
category_list = Book.where(created_at: '2022-01-01 00:00:00'..'2022-12-31 23:59:59')
                    .group(:category)
                    .having("count(category) >= ?", 3)
                    .pluck(:category)

Book.where(category: category_list)

Pandas

Pandasだとこうなる。
dfはBookテーブルをデータテーブルにしたもの。

books.py
period = df[(df['created_at'] >= "2022-01-01 00:00:00") & (df['created_at']<= '2022-12-31 23:59:59')]

category_list = period.groupby("category")["category"].filter(lambda x: len(x) >= 3)

df[df['category'].isin(category_list)]
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