{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "IPhtyon Notebook에서 SQL을 손쉽게 사용하려면 ```ipython-sql``` [extension](https://github.com/catherinedevlin/ipython-sql)을 설치해야 합니다. \n", "\n", "\n", "**Note: DO NOT PANIC** \n", "* 와닝이 뜨거나 이미 설치되었다고 해서 놀라지 말기 바랍니다. SQL 명령이 실행만 된다면 제대로 설치 된 것입니다. \n", "* SQL 질의문 작성법을 모른다고 당황하지 말기 바랍니다. 이제 곧 배우게 됩니다." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "%load_ext sql" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "파일에 저장되어 있는 SQLite 데이터베이스를 불러오는 방법을 익혀 봅시다.\n", "\n", "**NOTE: 이 예제에서는 \"dataset_1.db\"라는 파일을 불러올 것입니다. 이 데이터베이스 파일이 notebook과 같은 디렉터리에 있는지 꼭 확인하기 바랍니다. 이 파일을 갖고 앞으로 한 동안 활동을 할 것입니다.**" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Connected: @dataset_1.db'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%sql sqlite:///dataset_1.db" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "US National Oceanic and Atmospheric Administration (NOAA) 열대 우림 데이터를 살펴 봅시다. - `precipitation_full`- 다음과 같은 스키마를 갖고 있습니다.:\n", "\n", "> * `state_code`\n", "> * `station_id`\n", "> * `year`\n", "> * `month`\n", "> * `day`\n", "> * `hour`\n", "> * `precipitation`\n", "> * `flag_1`\n", "> * `flag_2`\n", "\n", "이 테이블의 각 터플은 어떤 장소(`station_id`)에서의 한 시간 동안의 상태값 (`state_code`)과 강우량을(`precipitation`- 100분의 1인치 단위)을 나타냅니다. 어떤 터플에`hour=25`이 기록되어 있다면 그것은 그 날의 전체 강우량을 나타냅니다. 당장은 `flag_1`과 `flag_2`은 사용하지 않습니다.\n", "\n", "질의문으로 테이블의 내용을 살펴봅시다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "다음과 같은 방법으로 비어 있는 데이터베이스 하나를 불러올 수도 있습니다.\n", "\n", "``%sql sqlite://``\n", "\n", "질의문을 작성해봅시다. (SQL질의문 작성법을 몰라도 걱정 말기 바랍니다. 차근 차근 배우게 될 것입니다.)\n", "\n", "**`%sql` 은 한 줄의 SQL명령을 쓸 때 사용됩니다. 단, Jupyter Notebook에서만 사용되는 것이지, SQLite에서 사용되는 키워드는 아닙니다.**" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " * sqlite:///dataset_1.db\n", "Done.\n" ] }, { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
state_codestation_idyearmonthdayhourprecipitationflag_1flag_2
18072013911None[
1807201391250I
1807201393024None]
18072013930250I
1630320139110g
" ], "text/plain": [ "[(1, 807, 2013, 9, 1, 1, None, '[', ''),\n", " (1, 807, 2013, 9, 1, 25, 0, 'I', ''),\n", " (1, 807, 2013, 9, 30, 24, None, ']', ''),\n", " (1, 807, 2013, 9, 30, 25, 0, 'I', ''),\n", " (1, 6303, 2013, 9, 1, 1, 0, 'g', '')]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%sql SELECT * FROM precipitation_full LIMIT 5;" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " * sqlite:///dataset_1.db\n", "Done.\n" ] }, { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", "
COUNT(*)
74251
" ], "text/plain": [ "[(74251,)]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%sql SELECT COUNT(*) FROM precipitation_full;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "그리고 **`%%sql` 여러 줄에 명령을 써야 할 경우 사용합니다.:**" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " * sqlite:///dataset_1.db\n", "Done.\n" ] }, { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", "
SUM(p.precipitation)
31982
" ], "text/plain": [ "[(31982,)]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%sql\n", "SELECT SUM(p.precipitation) \n", "FROM precipitation_full p, states s \n", "WHERE p.state_code = s.code AND s.abbrev = 'CA';" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "질의문을 실행했던 결과로 나온 값들을 활용할 수 있습니다. " ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " * sqlite:///dataset_1.db\n", "Done.\n" ] } ], "source": [ "result = %sql SELECT * FROM states;" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['code', 'name', 'abbrev']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result.keys" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*이 줄은 컬럼의 이름을 나타내는 줄입니다. *\n", "\n", "다음의 명령은 첫 번째 결과를 나타냅니다. 그리고 그 결과에서 컬럼 이림 'name'의 값을 출력하는 방법입니다." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 'Alabama', 'AL')" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result[1]" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Alabama'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result[1].name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "자, 이제 갖고 이런 저런 실험을 해보기 바랍니다. 더 자세한 것은 앞으로 배울 것입니다." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }