計算機科学のブログ

SQL - SQLite - Python - 結合と複数テーブル操作 - みんなでうまくやれないの? - group by, order by, distinct

Head First SQL ―頭とからだで覚えるSQLの基本Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 8章(結合と複数テーブル操作 - みんなでうまくやれないの?)、p.345(自分で考えてみよう)の解答を求めてみる。

コード

sample1.py

#! /usr/bin/env python3
import sqlite3

con = sqlite3.connect('sample.db')
cur = con.cursor()


def p(cur: sqlite3.Cursor, table: str):
    cur.execute(
        f"""
select * from {table}
"""
    )
    if (d := cur.description) is not None:
        print([t[0] for t in d])
    for row in cur.fetchall():
        print(row)


p(cur, 'my_contacts')

print('group by')
for x in ['status', 'profession', 'interests']:
    _sql = f"""
    select {x} from my_contacts
    group by {x}
    order by {x}
    """
    cur.execute(_sql)
    if (d := cur.description) is not None:
        print([t[0] for t in d])
    for row in cur.fetchall():
        print(row)

print('distinct')
for x in ['status', 'profession', 'interests']:
    _sql = f"""
    select distinct {x} from my_contacts
    order by {x}
    """
    cur.execute(_sql)
    if (d := cur.description) is not None:
        print([t[0] for t in d])
    for row in cur.fetchall():
        print(row)


cur.close()
con.close()

入出力結果(Terminal, Zsh)

% ./sample1.py 
['email', 'birthday', 'first_name', 'last_name', 'interests', 'seeking', 'status', 'profession', 'location', 'gender', 'tel', 'city', 'state']
('jill_anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', 'カヤック乗り、爬虫類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F', None, None, None)
('jill_anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', 'カヤック乗り、爬虫類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F', None, None, None)
('anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', '爬虫類', '友達', '独身', 'ライター', None, 'M', None, None, None)
('jill@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', 'カヤック乗り、爬虫類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F', None, None, None)
group by
['status']
('独身',)
['profession']
('テクニカルライター',)
('ライター',)
['interests']
('カヤック乗り、爬虫類',)
('爬虫類',)
distinct
['status']
('独身',)
['profession']
('テクニカルライター',)
('ライター',)
['interests']
('カヤック乗り、爬虫類',)
('爬虫類',)
%