Jhonatan51998 commited on
Commit
23ac22a
·
verified ·
1 Parent(s): 2e728f6

Upload notebooks/northwind_sqlalchemy.ipynb with huggingface_hub

Browse files
Files changed (1) hide show
  1. notebooks/northwind_sqlalchemy.ipynb +2261 -0
notebooks/northwind_sqlalchemy.ipynb ADDED
@@ -0,0 +1,2261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Base de datos Northwind con SQLAlchemy\n",
8
+ "\n",
9
+ "Este notebook muestra como crear una base de datos relacional usando SQLAlchemy en Python, cargar datos desde un archivo `.sql` externo y realizar consultas SQL directamente desde el codigo.\n",
10
+ "\n",
11
+ "SQLAlchemy es la libreria ORM (Object Relational Mapper) mas popular de Python. Permite interactuar con bases de datos relacionales usando Python puro o ejecutando SQL crudo. En este notebook usaremos SQLite como motor de base de datos para que no se necesite instalar ningun servidor externo.\n",
12
+ "\n",
13
+ "## Estructura del proyecto\n",
14
+ "\n",
15
+ "El notebook asume que los dos archivos estan en el mismo directorio:\n",
16
+ "\n",
17
+ "- `northwind_sqlalchemy.ipynb` este notebook\n",
18
+ "- `northwind_data.sql` archivo con todos los INSERT de Northwind\n",
19
+ "\n",
20
+ "## Contenido\n",
21
+ "\n",
22
+ "1. Instalacion de dependencias\n",
23
+ "2. Creacion del motor y la sesion\n",
24
+ "3. Definicion de tablas con el ORM\n",
25
+ "4. Carga de datos desde el archivo SQL\n",
26
+ "5. Consultas SQL con text()\n",
27
+ "6. Consultas con el ORM\n",
28
+ "7. Consultas avanzadas con JOINs y agregaciones"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {},
34
+ "source": [
35
+ "## 1. Instalacion de dependencias\n",
36
+ "\n",
37
+ "Primero instalamos las librerias necesarias. SQLAlchemy para el acceso a la base de datos y pandas para mostrar los resultados en formato de tabla."
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "execution_count": 1,
43
+ "metadata": {},
44
+ "outputs": [
45
+ {
46
+ "name": "stdout",
47
+ "output_type": "stream",
48
+ "text": [
49
+ "Note: you may need to restart the kernel to use updated packages.\n"
50
+ ]
51
+ }
52
+ ],
53
+ "source": [
54
+ "%pip install sqlalchemy pandas --quiet"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "markdown",
59
+ "metadata": {},
60
+ "source": [
61
+ "## 2. Creacion del motor y la sesion\n",
62
+ "\n",
63
+ "El engine es el punto de entrada principal a la base de datos. Contiene la cadena de conexion y administra el pool de conexiones. SQLite con /// seguido de un nombre de archivo crea la base de datos en disco. Si se usa sqlite:///:memory: la base existe solo en RAM.\n",
64
+ "\n",
65
+ "La Session actua como una unidad de trabajo: agrupa operaciones y las confirma o revierte como un bloque."
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": 2,
71
+ "metadata": {},
72
+ "outputs": [
73
+ {
74
+ "name": "stdout",
75
+ "output_type": "stream",
76
+ "text": [
77
+ "Motor creado: Engine(sqlite:///northwind.db)\n",
78
+ "Sesion lista: <sqlalchemy.orm.session.Session object at 0x1069551c0>\n"
79
+ ]
80
+ }
81
+ ],
82
+ "source": [
83
+ "from sqlalchemy import (\n",
84
+ " create_engine, Column, Integer, String, Numeric,\n",
85
+ " DateTime, ForeignKey, text\n",
86
+ ")\n",
87
+ "from sqlalchemy.orm import declarative_base, sessionmaker, relationship\n",
88
+ "import pandas as pd\n",
89
+ "\n",
90
+ "engine = create_engine(\"sqlite:///northwind.db\", echo=False)\n",
91
+ "Base = declarative_base()\n",
92
+ "Session = sessionmaker(bind=engine)\n",
93
+ "session = Session()\n",
94
+ "\n",
95
+ "print(\"Motor creado:\", engine)\n",
96
+ "print(\"Sesion lista:\", session)"
97
+ ]
98
+ },
99
+ {
100
+ "cell_type": "markdown",
101
+ "metadata": {},
102
+ "source": [
103
+ "## 3. Definicion de tablas con el ORM\n",
104
+ "\n",
105
+ "Cada clase Python representa una tabla en la base de datos. Los atributos Column definen las columnas con su tipo y restricciones. Las ForeignKey crean relaciones entre tablas y relationship() permite navegar entre objetos relacionados en Python sin escribir SQL.\n",
106
+ "\n",
107
+ "Definimos las tablas en el mismo orden que respeta las dependencias de claves foraneas."
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": 3,
113
+ "metadata": {},
114
+ "outputs": [
115
+ {
116
+ "name": "stdout",
117
+ "output_type": "stream",
118
+ "text": [
119
+ "Tablas creadas: ['categories', 'suppliers', 'shippers', 'customers', 'employees', 'products', 'orders', 'order_details']\n"
120
+ ]
121
+ }
122
+ ],
123
+ "source": [
124
+ "class Category(Base):\n",
125
+ " __tablename__ = \"categories\"\n",
126
+ " category_id = Column(Integer, primary_key=True, autoincrement=True)\n",
127
+ " category_name = Column(String(25))\n",
128
+ " description = Column(String(255))\n",
129
+ " products = relationship(\"Product\", back_populates=\"category\")\n",
130
+ "\n",
131
+ "\n",
132
+ "class Supplier(Base):\n",
133
+ " __tablename__ = \"suppliers\"\n",
134
+ " supplier_id = Column(Integer, primary_key=True, autoincrement=True)\n",
135
+ " supplier_name = Column(String(50))\n",
136
+ " contact_name = Column(String(50))\n",
137
+ " address = Column(String(50))\n",
138
+ " city = Column(String(20))\n",
139
+ " postal_code = Column(String(10))\n",
140
+ " country = Column(String(15))\n",
141
+ " phone = Column(String(15))\n",
142
+ " products = relationship(\"Product\", back_populates=\"supplier\")\n",
143
+ "\n",
144
+ "\n",
145
+ "class Shipper(Base):\n",
146
+ " __tablename__ = \"shippers\"\n",
147
+ " shipper_id = Column(Integer, primary_key=True, autoincrement=True)\n",
148
+ " shipper_name = Column(String(25))\n",
149
+ " phone = Column(String(15))\n",
150
+ " orders = relationship(\"Order\", back_populates=\"shipper\")\n",
151
+ "\n",
152
+ "\n",
153
+ "class Customer(Base):\n",
154
+ " __tablename__ = \"customers\"\n",
155
+ " customer_id = Column(Integer, primary_key=True, autoincrement=True)\n",
156
+ " customer_name = Column(String(50))\n",
157
+ " contact_name = Column(String(50))\n",
158
+ " address = Column(String(50))\n",
159
+ " city = Column(String(20))\n",
160
+ " postal_code = Column(String(10))\n",
161
+ " country = Column(String(15))\n",
162
+ " orders = relationship(\"Order\", back_populates=\"customer\")\n",
163
+ "\n",
164
+ "\n",
165
+ "class Employee(Base):\n",
166
+ " __tablename__ = \"employees\"\n",
167
+ " employee_id = Column(Integer, primary_key=True, autoincrement=True)\n",
168
+ " last_name = Column(String(15))\n",
169
+ " first_name = Column(String(15))\n",
170
+ " birth_date = Column(DateTime)\n",
171
+ " photo = Column(String(25))\n",
172
+ " notes = Column(String(1024))\n",
173
+ " orders = relationship(\"Order\", back_populates=\"employee\")\n",
174
+ "\n",
175
+ "\n",
176
+ "class Product(Base):\n",
177
+ " __tablename__ = \"products\"\n",
178
+ " product_id = Column(Integer, primary_key=True, autoincrement=True)\n",
179
+ " product_name = Column(String(50))\n",
180
+ " supplier_id = Column(Integer, ForeignKey(\"suppliers.supplier_id\"))\n",
181
+ " category_id = Column(Integer, ForeignKey(\"categories.category_id\"))\n",
182
+ " unit = Column(String(25))\n",
183
+ " price = Column(Numeric)\n",
184
+ " supplier = relationship(\"Supplier\", back_populates=\"products\")\n",
185
+ " category = relationship(\"Category\", back_populates=\"products\")\n",
186
+ " order_details = relationship(\"OrderDetail\", back_populates=\"product\")\n",
187
+ "\n",
188
+ "\n",
189
+ "class Order(Base):\n",
190
+ " __tablename__ = \"orders\"\n",
191
+ " order_id = Column(Integer, primary_key=True, autoincrement=True)\n",
192
+ " customer_id = Column(Integer, ForeignKey(\"customers.customer_id\"))\n",
193
+ " employee_id = Column(Integer, ForeignKey(\"employees.employee_id\"))\n",
194
+ " order_date = Column(DateTime)\n",
195
+ " shipper_id = Column(Integer, ForeignKey(\"shippers.shipper_id\"))\n",
196
+ " customer = relationship(\"Customer\", back_populates=\"orders\")\n",
197
+ " employee = relationship(\"Employee\", back_populates=\"orders\")\n",
198
+ " shipper = relationship(\"Shipper\", back_populates=\"orders\")\n",
199
+ " details = relationship(\"OrderDetail\", back_populates=\"order\")\n",
200
+ "\n",
201
+ "\n",
202
+ "class OrderDetail(Base):\n",
203
+ " __tablename__ = \"order_details\"\n",
204
+ " order_detail_id = Column(Integer, primary_key=True, autoincrement=True)\n",
205
+ " order_id = Column(Integer, ForeignKey(\"orders.order_id\"))\n",
206
+ " product_id = Column(Integer, ForeignKey(\"products.product_id\"))\n",
207
+ " quantity = Column(Integer)\n",
208
+ " order = relationship(\"Order\", back_populates=\"details\")\n",
209
+ " product = relationship(\"Product\", back_populates=\"order_details\")\n",
210
+ "\n",
211
+ "\n",
212
+ "Base.metadata.create_all(engine)\n",
213
+ "print(\"Tablas creadas:\", list(Base.metadata.tables.keys()))"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "metadata": {},
219
+ "source": [
220
+ "## 4. Carga de datos desde el archivo SQL\n",
221
+ "\n",
222
+ "En lugar de tener los datos fijos en el codigo, los leemos desde el archivo `northwind_data.sql`. Esto separa la logica de la aplicacion de los datos, lo cual facilita cambiar el conjunto de datos sin tocar el notebook.\n",
223
+ "\n",
224
+ "### Como funciona el parser\n",
225
+ "\n",
226
+ "El archivo `.sql` contiene sentencias `INSERT INTO NombreTabla VALUES(...)`. El parser hace lo siguiente:\n",
227
+ "\n",
228
+ "1. Lee el archivo linea a linea e ignora comentarios (lineas que empiezan con `--`) y lineas vacias.\n",
229
+ "2. Identifica la tabla destino extrayendo el nombre entre `INSERT INTO` y `VALUES`.\n",
230
+ "3. Extrae la lista de valores entre el primer `(` y el ultimo `)` de cada sentencia.\n",
231
+ "4. Separa los valores respetando las comillas SQL: una comilla simple doble `''` dentro de un string se trata como caracter de escape, no como fin del valor.\n",
232
+ "5. Convierte cada valor al tipo Python correcto: entero, flotante o cadena de texto.\n",
233
+ "6. Los registros parseados se agrupan por tabla y se insertan en la base de datos usando los modelos ORM."
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "execution_count": 4,
239
+ "metadata": {},
240
+ "outputs": [
241
+ {
242
+ "name": "stdout",
243
+ "output_type": "stream",
244
+ "text": [
245
+ " categories -> 8 filas leidas\n",
246
+ " suppliers -> 29 filas leidas\n",
247
+ " shippers -> 3 filas leidas\n",
248
+ " customers -> 91 filas leidas\n",
249
+ " employees -> 10 filas leidas\n",
250
+ " products -> 77 filas leidas\n",
251
+ " orders -> 196 filas leidas\n",
252
+ " orderdetails -> 518 filas leidas\n"
253
+ ]
254
+ }
255
+ ],
256
+ "source": [
257
+ "import re\n",
258
+ "from datetime import datetime\n",
259
+ "\n",
260
+ "DATA_FILE = \"northwind_data.sql\" # cambia la ruta si el archivo esta en otro directorio\n",
261
+ "\n",
262
+ "\n",
263
+ "def parse_sql_values(raw_values: str) -> list:\n",
264
+ " \"\"\"\n",
265
+ " Recibe el contenido entre los parentesis del VALUES(...) y retorna\n",
266
+ " una lista de valores Python, respetando strings con comillas escapadas.\n",
267
+ " \"\"\"\n",
268
+ " values = []\n",
269
+ " current = \"\"\n",
270
+ " in_string = False\n",
271
+ " i = 0\n",
272
+ "\n",
273
+ " while i < len(raw_values):\n",
274
+ " ch = raw_values[i]\n",
275
+ "\n",
276
+ " if in_string:\n",
277
+ " if ch == \"'\":\n",
278
+ " # comilla doble '' es escape dentro del string SQL\n",
279
+ " if i + 1 < len(raw_values) and raw_values[i + 1] == \"'\":\n",
280
+ " current += \"'\"\n",
281
+ " i += 2\n",
282
+ " continue\n",
283
+ " else:\n",
284
+ " in_string = False\n",
285
+ " else:\n",
286
+ " current += ch\n",
287
+ " else:\n",
288
+ " if ch == \"'\":\n",
289
+ " in_string = True\n",
290
+ " elif ch == \",\":\n",
291
+ " values.append(current.strip())\n",
292
+ " current = \"\"\n",
293
+ " i += 1\n",
294
+ " continue\n",
295
+ " else:\n",
296
+ " current += ch\n",
297
+ " i += 1\n",
298
+ "\n",
299
+ " if current.strip():\n",
300
+ " values.append(current.strip())\n",
301
+ "\n",
302
+ " # Convertir tipos: entero, flotante o string\n",
303
+ " result = []\n",
304
+ " for v in values:\n",
305
+ " if v == \"NULL\":\n",
306
+ " result.append(None)\n",
307
+ " else:\n",
308
+ " try:\n",
309
+ " result.append(int(v))\n",
310
+ " except ValueError:\n",
311
+ " try:\n",
312
+ " result.append(float(v))\n",
313
+ " except ValueError:\n",
314
+ " result.append(v)\n",
315
+ " return result\n",
316
+ "\n",
317
+ "\n",
318
+ "def load_sql_file(path: str) -> dict:\n",
319
+ " \"\"\"\n",
320
+ " Lee el archivo SQL y retorna un diccionario {tabla: [lista_de_filas]}.\n",
321
+ " Cada fila es una lista de valores Python listos para insertar.\n",
322
+ " \"\"\"\n",
323
+ " records = {}\n",
324
+ " pattern = re.compile(\n",
325
+ " r\"INSERT\\s+INTO\\s+(\\w+)\\s+VALUES\\s*\\((.+)\\)\\s*;\",\n",
326
+ " re.IGNORECASE\n",
327
+ " )\n",
328
+ "\n",
329
+ " with open(path, encoding=\"utf-8\") as f:\n",
330
+ " for line in f:\n",
331
+ " line = line.strip()\n",
332
+ " if not line or line.startswith(\"--\"):\n",
333
+ " continue\n",
334
+ " match = pattern.match(line)\n",
335
+ " if match:\n",
336
+ " table = match.group(1).lower()\n",
337
+ " raw = match.group(2)\n",
338
+ " values = parse_sql_values(raw)\n",
339
+ " records.setdefault(table, []).append(values)\n",
340
+ "\n",
341
+ " return records\n",
342
+ "\n",
343
+ "\n",
344
+ "# Cargar el archivo y mostrar cuantas filas se leyeron por tabla\n",
345
+ "data = load_sql_file(DATA_FILE)\n",
346
+ "\n",
347
+ "for table, rows in data.items():\n",
348
+ " print(f\" {table:15s} -> {len(rows):4d} filas leidas\")"
349
+ ]
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "execution_count": 5,
354
+ "metadata": {},
355
+ "outputs": [
356
+ {
357
+ "name": "stdout",
358
+ "output_type": "stream",
359
+ "text": [
360
+ "Categorias insertadas : 8\n",
361
+ "Proveedores insertados : 29\n",
362
+ "Transportistas : 3\n",
363
+ "Clientes insertados : 91\n",
364
+ "Empleados insertados : 10\n",
365
+ "Productos insertados : 77\n",
366
+ "Ordenes insertadas : 196\n",
367
+ "Detalles insertados : 518\n"
368
+ ]
369
+ }
370
+ ],
371
+ "source": [
372
+ "def poblar_base_de_datos(data: dict, session) -> None:\n",
373
+ " \"\"\"\n",
374
+ " Toma el diccionario parseado del archivo SQL e inserta los registros\n",
375
+ " en la base de datos usando los modelos ORM.\n",
376
+ " Solo inserta si la tabla esta vacia (idempotente: se puede ejecutar varias veces).\n",
377
+ " \"\"\"\n",
378
+ "\n",
379
+ " if session.query(Category).count() == 0:\n",
380
+ " for row in data.get(\"categories\", []):\n",
381
+ " session.add(Category(category_name=row[0], description=row[1]))\n",
382
+ " session.commit()\n",
383
+ " print(f\"Categorias insertadas : {session.query(Category).count()}\")\n",
384
+ "\n",
385
+ " if session.query(Supplier).count() == 0:\n",
386
+ " for row in data.get(\"suppliers\", []):\n",
387
+ " session.add(Supplier(\n",
388
+ " supplier_name=row[0], contact_name=row[1], address=row[2],\n",
389
+ " city=row[3], postal_code=row[4], country=row[5], phone=row[6]\n",
390
+ " ))\n",
391
+ " session.commit()\n",
392
+ " print(f\"Proveedores insertados : {session.query(Supplier).count()}\")\n",
393
+ "\n",
394
+ " if session.query(Shipper).count() == 0:\n",
395
+ " for row in data.get(\"shippers\", []):\n",
396
+ " session.add(Shipper(shipper_name=row[0], phone=row[1]))\n",
397
+ " session.commit()\n",
398
+ " print(f\"Transportistas : {session.query(Shipper).count()}\")\n",
399
+ "\n",
400
+ " if session.query(Customer).count() == 0:\n",
401
+ " for row in data.get(\"customers\", []):\n",
402
+ " session.add(Customer(\n",
403
+ " customer_name=row[0], contact_name=row[1], address=row[2],\n",
404
+ " city=row[3], postal_code=row[4], country=row[5]\n",
405
+ " ))\n",
406
+ " session.commit()\n",
407
+ " print(f\"Clientes insertados : {session.query(Customer).count()}\")\n",
408
+ "\n",
409
+ " if session.query(Employee).count() == 0:\n",
410
+ " for row in data.get(\"employees\", []):\n",
411
+ " birth = datetime.strptime(row[2], \"%Y-%m-%d\") if isinstance(row[2], str) else None\n",
412
+ " session.add(Employee(\n",
413
+ " last_name=row[0], first_name=row[1],\n",
414
+ " birth_date=birth, photo=row[3], notes=row[4]\n",
415
+ " ))\n",
416
+ " session.commit()\n",
417
+ " print(f\"Empleados insertados : {session.query(Employee).count()}\")\n",
418
+ "\n",
419
+ " if session.query(Product).count() == 0:\n",
420
+ " for row in data.get(\"products\", []):\n",
421
+ " session.add(Product(\n",
422
+ " product_name=row[0], supplier_id=row[1],\n",
423
+ " category_id=row[2], unit=row[3], price=row[4]\n",
424
+ " ))\n",
425
+ " session.commit()\n",
426
+ " print(f\"Productos insertados : {session.query(Product).count()}\")\n",
427
+ "\n",
428
+ " if session.query(Order).count() == 0:\n",
429
+ " for row in data.get(\"orders\", []):\n",
430
+ " order_date = datetime.strptime(row[2], \"%Y-%m-%d\") if isinstance(row[2], str) else None\n",
431
+ " session.add(Order(\n",
432
+ " customer_id=row[0], employee_id=row[1],\n",
433
+ " order_date=order_date, shipper_id=row[3]\n",
434
+ " ))\n",
435
+ " session.commit()\n",
436
+ " print(f\"Ordenes insertadas : {session.query(Order).count()}\")\n",
437
+ "\n",
438
+ " if session.query(OrderDetail).count() == 0:\n",
439
+ " raw_details = data.get(\"orderdetails\", [])\n",
440
+ " if raw_details:\n",
441
+ " # El archivo usa order_id absoluto (10248...) pero nuestra BD empieza en 1.\n",
442
+ " # Calculamos el offset para remapear los IDs.\n",
443
+ " min_order_id = min(row[0] for row in raw_details)\n",
444
+ " for row in raw_details:\n",
445
+ " mapped_order_id = row[0] - min_order_id + 1\n",
446
+ " session.add(OrderDetail(\n",
447
+ " order_id=mapped_order_id,\n",
448
+ " product_id=row[1],\n",
449
+ " quantity=row[2]\n",
450
+ " ))\n",
451
+ " session.commit()\n",
452
+ " print(f\"Detalles insertados : {session.query(OrderDetail).count()}\")\n",
453
+ "\n",
454
+ "\n",
455
+ "poblar_base_de_datos(data, session)"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "code",
460
+ "execution_count": 6,
461
+ "metadata": {},
462
+ "outputs": [
463
+ {
464
+ "data": {
465
+ "text/html": [
466
+ "<div>\n",
467
+ "<style scoped>\n",
468
+ " .dataframe tbody tr th:only-of-type {\n",
469
+ " vertical-align: middle;\n",
470
+ " }\n",
471
+ "\n",
472
+ " .dataframe tbody tr th {\n",
473
+ " vertical-align: top;\n",
474
+ " }\n",
475
+ "\n",
476
+ " .dataframe thead th {\n",
477
+ " text-align: right;\n",
478
+ " }\n",
479
+ "</style>\n",
480
+ "<table border=\"1\" class=\"dataframe\">\n",
481
+ " <thead>\n",
482
+ " <tr style=\"text-align: right;\">\n",
483
+ " <th></th>\n",
484
+ " <th>tabla</th>\n",
485
+ " <th>registros</th>\n",
486
+ " </tr>\n",
487
+ " </thead>\n",
488
+ " <tbody>\n",
489
+ " <tr>\n",
490
+ " <th>0</th>\n",
491
+ " <td>categories</td>\n",
492
+ " <td>8</td>\n",
493
+ " </tr>\n",
494
+ " <tr>\n",
495
+ " <th>1</th>\n",
496
+ " <td>suppliers</td>\n",
497
+ " <td>29</td>\n",
498
+ " </tr>\n",
499
+ " <tr>\n",
500
+ " <th>2</th>\n",
501
+ " <td>shippers</td>\n",
502
+ " <td>3</td>\n",
503
+ " </tr>\n",
504
+ " <tr>\n",
505
+ " <th>3</th>\n",
506
+ " <td>customers</td>\n",
507
+ " <td>91</td>\n",
508
+ " </tr>\n",
509
+ " <tr>\n",
510
+ " <th>4</th>\n",
511
+ " <td>employees</td>\n",
512
+ " <td>10</td>\n",
513
+ " </tr>\n",
514
+ " <tr>\n",
515
+ " <th>5</th>\n",
516
+ " <td>products</td>\n",
517
+ " <td>77</td>\n",
518
+ " </tr>\n",
519
+ " <tr>\n",
520
+ " <th>6</th>\n",
521
+ " <td>orders</td>\n",
522
+ " <td>196</td>\n",
523
+ " </tr>\n",
524
+ " <tr>\n",
525
+ " <th>7</th>\n",
526
+ " <td>order_details</td>\n",
527
+ " <td>518</td>\n",
528
+ " </tr>\n",
529
+ " </tbody>\n",
530
+ "</table>\n",
531
+ "</div>"
532
+ ],
533
+ "text/plain": [
534
+ " tabla registros\n",
535
+ "0 categories 8\n",
536
+ "1 suppliers 29\n",
537
+ "2 shippers 3\n",
538
+ "3 customers 91\n",
539
+ "4 employees 10\n",
540
+ "5 products 77\n",
541
+ "6 orders 196\n",
542
+ "7 order_details 518"
543
+ ]
544
+ },
545
+ "execution_count": 6,
546
+ "metadata": {},
547
+ "output_type": "execute_result"
548
+ }
549
+ ],
550
+ "source": [
551
+ "# Verificacion: conteo de registros por tabla\n",
552
+ "tablas = [\n",
553
+ " (\"categories\", Category),\n",
554
+ " (\"suppliers\", Supplier),\n",
555
+ " (\"shippers\", Shipper),\n",
556
+ " (\"customers\", Customer),\n",
557
+ " (\"employees\", Employee),\n",
558
+ " (\"products\", Product),\n",
559
+ " (\"orders\", Order),\n",
560
+ " (\"order_details\", OrderDetail),\n",
561
+ "]\n",
562
+ "\n",
563
+ "resumen = pd.DataFrame(\n",
564
+ " [(nombre, session.query(modelo).count()) for nombre, modelo in tablas],\n",
565
+ " columns=[\"tabla\", \"registros\"]\n",
566
+ ")\n",
567
+ "resumen"
568
+ ]
569
+ },
570
+ {
571
+ "cell_type": "markdown",
572
+ "metadata": {},
573
+ "source": [
574
+ "## 5. Consultas SQL con text()\n",
575
+ "\n",
576
+ "SQLAlchemy permite ejecutar SQL crudo usando la funcion text(). Esto es util cuando se necesita control total sobre la consulta o cuando se trabaja con SQL heredado.\n",
577
+ "\n",
578
+ "El resultado se puede convertir directamente a un DataFrame de pandas. Definimos una funcion auxiliar sql() que ejecuta cualquier consulta y devuelve el resultado como DataFrame. Los parametros con :nombre evitan inyeccion SQL al pasar valores del usuario."
579
+ ]
580
+ },
581
+ {
582
+ "cell_type": "code",
583
+ "execution_count": 3,
584
+ "metadata": {},
585
+ "outputs": [
586
+ {
587
+ "data": {
588
+ "text/html": [
589
+ "<div>\n",
590
+ "<style scoped>\n",
591
+ " .dataframe tbody tr th:only-of-type {\n",
592
+ " vertical-align: middle;\n",
593
+ " }\n",
594
+ "\n",
595
+ " .dataframe tbody tr th {\n",
596
+ " vertical-align: top;\n",
597
+ " }\n",
598
+ "\n",
599
+ " .dataframe thead th {\n",
600
+ " text-align: right;\n",
601
+ " }\n",
602
+ "</style>\n",
603
+ "<table border=\"1\" class=\"dataframe\">\n",
604
+ " <thead>\n",
605
+ " <tr style=\"text-align: right;\">\n",
606
+ " <th></th>\n",
607
+ " <th>category_id</th>\n",
608
+ " <th>category_name</th>\n",
609
+ " <th>description</th>\n",
610
+ " </tr>\n",
611
+ " </thead>\n",
612
+ " <tbody>\n",
613
+ " <tr>\n",
614
+ " <th>0</th>\n",
615
+ " <td>1</td>\n",
616
+ " <td>Beverages</td>\n",
617
+ " <td>Soft drinks, coffees, teas, beers, and ales</td>\n",
618
+ " </tr>\n",
619
+ " <tr>\n",
620
+ " <th>1</th>\n",
621
+ " <td>2</td>\n",
622
+ " <td>Condiments</td>\n",
623
+ " <td>Sweet and savory sauces, relishes, spreads, an...</td>\n",
624
+ " </tr>\n",
625
+ " <tr>\n",
626
+ " <th>2</th>\n",
627
+ " <td>3</td>\n",
628
+ " <td>Confections</td>\n",
629
+ " <td>Desserts, candies, and sweet breads</td>\n",
630
+ " </tr>\n",
631
+ " <tr>\n",
632
+ " <th>3</th>\n",
633
+ " <td>4</td>\n",
634
+ " <td>Dairy Products</td>\n",
635
+ " <td>Cheeses</td>\n",
636
+ " </tr>\n",
637
+ " <tr>\n",
638
+ " <th>4</th>\n",
639
+ " <td>5</td>\n",
640
+ " <td>Grains/Cereals</td>\n",
641
+ " <td>Breads, crackers, pasta, and cereal</td>\n",
642
+ " </tr>\n",
643
+ " <tr>\n",
644
+ " <th>5</th>\n",
645
+ " <td>6</td>\n",
646
+ " <td>Meat/Poultry</td>\n",
647
+ " <td>Prepared meats</td>\n",
648
+ " </tr>\n",
649
+ " <tr>\n",
650
+ " <th>6</th>\n",
651
+ " <td>7</td>\n",
652
+ " <td>Produce</td>\n",
653
+ " <td>Dried fruit and bean curd</td>\n",
654
+ " </tr>\n",
655
+ " <tr>\n",
656
+ " <th>7</th>\n",
657
+ " <td>8</td>\n",
658
+ " <td>Seafood</td>\n",
659
+ " <td>Seaweed and fish</td>\n",
660
+ " </tr>\n",
661
+ " </tbody>\n",
662
+ "</table>\n",
663
+ "</div>"
664
+ ],
665
+ "text/plain": [
666
+ " category_id category_name \\\n",
667
+ "0 1 Beverages \n",
668
+ "1 2 Condiments \n",
669
+ "2 3 Confections \n",
670
+ "3 4 Dairy Products \n",
671
+ "4 5 Grains/Cereals \n",
672
+ "5 6 Meat/Poultry \n",
673
+ "6 7 Produce \n",
674
+ "7 8 Seafood \n",
675
+ "\n",
676
+ " description \n",
677
+ "0 Soft drinks, coffees, teas, beers, and ales \n",
678
+ "1 Sweet and savory sauces, relishes, spreads, an... \n",
679
+ "2 Desserts, candies, and sweet breads \n",
680
+ "3 Cheeses \n",
681
+ "4 Breads, crackers, pasta, and cereal \n",
682
+ "5 Prepared meats \n",
683
+ "6 Dried fruit and bean curd \n",
684
+ "7 Seaweed and fish "
685
+ ]
686
+ },
687
+ "execution_count": 3,
688
+ "metadata": {},
689
+ "output_type": "execute_result"
690
+ }
691
+ ],
692
+ "source": [
693
+ "def sql(query, **params):\n",
694
+ " \"\"\"Ejecuta SQL crudo y retorna un DataFrame de pandas.\"\"\"\n",
695
+ " with engine.connect() as conn:\n",
696
+ " result = conn.execute(text(query), params)\n",
697
+ " return pd.DataFrame(result.fetchall(), columns=result.keys())\n",
698
+ "\n",
699
+ "\n",
700
+ "# Consulta basica: todas las categorias\n",
701
+ "sql(\"SELECT * FROM categories\")"
702
+ ]
703
+ },
704
+ {
705
+ "cell_type": "code",
706
+ "execution_count": 8,
707
+ "metadata": {},
708
+ "outputs": [
709
+ {
710
+ "data": {
711
+ "text/html": [
712
+ "<div>\n",
713
+ "<style scoped>\n",
714
+ " .dataframe tbody tr th:only-of-type {\n",
715
+ " vertical-align: middle;\n",
716
+ " }\n",
717
+ "\n",
718
+ " .dataframe tbody tr th {\n",
719
+ " vertical-align: top;\n",
720
+ " }\n",
721
+ "\n",
722
+ " .dataframe thead th {\n",
723
+ " text-align: right;\n",
724
+ " }\n",
725
+ "</style>\n",
726
+ "<table border=\"1\" class=\"dataframe\">\n",
727
+ " <thead>\n",
728
+ " <tr style=\"text-align: right;\">\n",
729
+ " <th></th>\n",
730
+ " <th>product_name</th>\n",
731
+ " <th>price</th>\n",
732
+ " <th>category_name</th>\n",
733
+ " </tr>\n",
734
+ " </thead>\n",
735
+ " <tbody>\n",
736
+ " <tr>\n",
737
+ " <th>0</th>\n",
738
+ " <td>Côte de Blaye</td>\n",
739
+ " <td>263.5</td>\n",
740
+ " <td>Beverages</td>\n",
741
+ " </tr>\n",
742
+ " <tr>\n",
743
+ " <th>1</th>\n",
744
+ " <td>Ipoh Coffee</td>\n",
745
+ " <td>46.0</td>\n",
746
+ " <td>Beverages</td>\n",
747
+ " </tr>\n",
748
+ " <tr>\n",
749
+ " <th>2</th>\n",
750
+ " <td>Chang</td>\n",
751
+ " <td>19.0</td>\n",
752
+ " <td>Beverages</td>\n",
753
+ " </tr>\n",
754
+ " <tr>\n",
755
+ " <th>3</th>\n",
756
+ " <td>Chais</td>\n",
757
+ " <td>18.0</td>\n",
758
+ " <td>Beverages</td>\n",
759
+ " </tr>\n",
760
+ " <tr>\n",
761
+ " <th>4</th>\n",
762
+ " <td>Steeleye Stout</td>\n",
763
+ " <td>18.0</td>\n",
764
+ " <td>Beverages</td>\n",
765
+ " </tr>\n",
766
+ " <tr>\n",
767
+ " <th>5</th>\n",
768
+ " <td>Chartreuse verte</td>\n",
769
+ " <td>18.0</td>\n",
770
+ " <td>Beverages</td>\n",
771
+ " </tr>\n",
772
+ " <tr>\n",
773
+ " <th>6</th>\n",
774
+ " <td>Lakkalikööri</td>\n",
775
+ " <td>18.0</td>\n",
776
+ " <td>Beverages</td>\n",
777
+ " </tr>\n",
778
+ " <tr>\n",
779
+ " <th>7</th>\n",
780
+ " <td>Outback Lager</td>\n",
781
+ " <td>15.0</td>\n",
782
+ " <td>Beverages</td>\n",
783
+ " </tr>\n",
784
+ " <tr>\n",
785
+ " <th>8</th>\n",
786
+ " <td>Sasquatch Ale</td>\n",
787
+ " <td>14.0</td>\n",
788
+ " <td>Beverages</td>\n",
789
+ " </tr>\n",
790
+ " <tr>\n",
791
+ " <th>9</th>\n",
792
+ " <td>Laughing Lumberjack Lager</td>\n",
793
+ " <td>14.0</td>\n",
794
+ " <td>Beverages</td>\n",
795
+ " </tr>\n",
796
+ " </tbody>\n",
797
+ "</table>\n",
798
+ "</div>"
799
+ ],
800
+ "text/plain": [
801
+ " product_name price category_name\n",
802
+ "0 Côte de Blaye 263.5 Beverages\n",
803
+ "1 Ipoh Coffee 46.0 Beverages\n",
804
+ "2 Chang 19.0 Beverages\n",
805
+ "3 Chais 18.0 Beverages\n",
806
+ "4 Steeleye Stout 18.0 Beverages\n",
807
+ "5 Chartreuse verte 18.0 Beverages\n",
808
+ "6 Lakkalikööri 18.0 Beverages\n",
809
+ "7 Outback Lager 15.0 Beverages\n",
810
+ "8 Sasquatch Ale 14.0 Beverages\n",
811
+ "9 Laughing Lumberjack Lager 14.0 Beverages"
812
+ ]
813
+ },
814
+ "execution_count": 8,
815
+ "metadata": {},
816
+ "output_type": "execute_result"
817
+ }
818
+ ],
819
+ "source": [
820
+ "# Filtrar productos de la categoria Beverages con precio mayor a 10\n",
821
+ "sql(\"\"\"\n",
822
+ " SELECT p.product_name, p.price, c.category_name\n",
823
+ " FROM products p\n",
824
+ " JOIN categories c ON p.category_id = c.category_id\n",
825
+ " WHERE c.category_name = :cat\n",
826
+ " AND p.price > :min_price\n",
827
+ " ORDER BY p.price DESC\n",
828
+ "\"\"\", cat=\"Beverages\", min_price=10)"
829
+ ]
830
+ },
831
+ {
832
+ "cell_type": "code",
833
+ "execution_count": 5,
834
+ "id": "a298704a",
835
+ "metadata": {},
836
+ "outputs": [
837
+ {
838
+ "data": {
839
+ "text/html": [
840
+ "<div>\n",
841
+ "<style scoped>\n",
842
+ " .dataframe tbody tr th:only-of-type {\n",
843
+ " vertical-align: middle;\n",
844
+ " }\n",
845
+ "\n",
846
+ " .dataframe tbody tr th {\n",
847
+ " vertical-align: top;\n",
848
+ " }\n",
849
+ "\n",
850
+ " .dataframe thead th {\n",
851
+ " text-align: right;\n",
852
+ " }\n",
853
+ "</style>\n",
854
+ "<table border=\"1\" class=\"dataframe\">\n",
855
+ " <thead>\n",
856
+ " <tr style=\"text-align: right;\">\n",
857
+ " <th></th>\n",
858
+ " <th>product_name</th>\n",
859
+ " <th>price</th>\n",
860
+ " <th>category_name</th>\n",
861
+ " </tr>\n",
862
+ " </thead>\n",
863
+ " <tbody>\n",
864
+ " <tr>\n",
865
+ " <th>0</th>\n",
866
+ " <td>Côte de Blaye</td>\n",
867
+ " <td>263.5</td>\n",
868
+ " <td>Beverages</td>\n",
869
+ " </tr>\n",
870
+ " <tr>\n",
871
+ " <th>1</th>\n",
872
+ " <td>Ipoh Coffee</td>\n",
873
+ " <td>46.0</td>\n",
874
+ " <td>Beverages</td>\n",
875
+ " </tr>\n",
876
+ " <tr>\n",
877
+ " <th>2</th>\n",
878
+ " <td>Chang</td>\n",
879
+ " <td>19.0</td>\n",
880
+ " <td>Beverages</td>\n",
881
+ " </tr>\n",
882
+ " <tr>\n",
883
+ " <th>3</th>\n",
884
+ " <td>Chais</td>\n",
885
+ " <td>18.0</td>\n",
886
+ " <td>Beverages</td>\n",
887
+ " </tr>\n",
888
+ " <tr>\n",
889
+ " <th>4</th>\n",
890
+ " <td>Steeleye Stout</td>\n",
891
+ " <td>18.0</td>\n",
892
+ " <td>Beverages</td>\n",
893
+ " </tr>\n",
894
+ " <tr>\n",
895
+ " <th>5</th>\n",
896
+ " <td>Chartreuse verte</td>\n",
897
+ " <td>18.0</td>\n",
898
+ " <td>Beverages</td>\n",
899
+ " </tr>\n",
900
+ " <tr>\n",
901
+ " <th>6</th>\n",
902
+ " <td>Lakkalikööri</td>\n",
903
+ " <td>18.0</td>\n",
904
+ " <td>Beverages</td>\n",
905
+ " </tr>\n",
906
+ " <tr>\n",
907
+ " <th>7</th>\n",
908
+ " <td>Outback Lager</td>\n",
909
+ " <td>15.0</td>\n",
910
+ " <td>Beverages</td>\n",
911
+ " </tr>\n",
912
+ " <tr>\n",
913
+ " <th>8</th>\n",
914
+ " <td>Sasquatch Ale</td>\n",
915
+ " <td>14.0</td>\n",
916
+ " <td>Beverages</td>\n",
917
+ " </tr>\n",
918
+ " <tr>\n",
919
+ " <th>9</th>\n",
920
+ " <td>Laughing Lumberjack Lager</td>\n",
921
+ " <td>14.0</td>\n",
922
+ " <td>Beverages</td>\n",
923
+ " </tr>\n",
924
+ " </tbody>\n",
925
+ "</table>\n",
926
+ "</div>"
927
+ ],
928
+ "text/plain": [
929
+ " product_name price category_name\n",
930
+ "0 Côte de Blaye 263.5 Beverages\n",
931
+ "1 Ipoh Coffee 46.0 Beverages\n",
932
+ "2 Chang 19.0 Beverages\n",
933
+ "3 Chais 18.0 Beverages\n",
934
+ "4 Steeleye Stout 18.0 Beverages\n",
935
+ "5 Chartreuse verte 18.0 Beverages\n",
936
+ "6 Lakkalikööri 18.0 Beverages\n",
937
+ "7 Outback Lager 15.0 Beverages\n",
938
+ "8 Sasquatch Ale 14.0 Beverages\n",
939
+ "9 Laughing Lumberjack Lager 14.0 Beverages"
940
+ ]
941
+ },
942
+ "execution_count": 5,
943
+ "metadata": {},
944
+ "output_type": "execute_result"
945
+ }
946
+ ],
947
+ "source": [
948
+ "sql(\"\"\"\n",
949
+ " SELECT p.product_name, p.price, c.category_name\n",
950
+ " FROM products p\n",
951
+ " JOIN categories c ON p.category_id = c.category_id\n",
952
+ " WHERE c.category_name = \"Beverages\"\n",
953
+ " AND p.price > 10\n",
954
+ " ORDER BY p.price DESC\"\"\")"
955
+ ]
956
+ },
957
+ {
958
+ "cell_type": "code",
959
+ "execution_count": 9,
960
+ "metadata": {},
961
+ "outputs": [
962
+ {
963
+ "data": {
964
+ "text/html": [
965
+ "<div>\n",
966
+ "<style scoped>\n",
967
+ " .dataframe tbody tr th:only-of-type {\n",
968
+ " vertical-align: middle;\n",
969
+ " }\n",
970
+ "\n",
971
+ " .dataframe tbody tr th {\n",
972
+ " vertical-align: top;\n",
973
+ " }\n",
974
+ "\n",
975
+ " .dataframe thead th {\n",
976
+ " text-align: right;\n",
977
+ " }\n",
978
+ "</style>\n",
979
+ "<table border=\"1\" class=\"dataframe\">\n",
980
+ " <thead>\n",
981
+ " <tr style=\"text-align: right;\">\n",
982
+ " <th></th>\n",
983
+ " <th>category_name</th>\n",
984
+ " <th>total_products</th>\n",
985
+ " <th>avg_price</th>\n",
986
+ " <th>min_price</th>\n",
987
+ " <th>max_price</th>\n",
988
+ " </tr>\n",
989
+ " </thead>\n",
990
+ " <tbody>\n",
991
+ " <tr>\n",
992
+ " <th>0</th>\n",
993
+ " <td>Confections</td>\n",
994
+ " <td>13</td>\n",
995
+ " <td>25.16</td>\n",
996
+ " <td>9.20</td>\n",
997
+ " <td>81.00</td>\n",
998
+ " </tr>\n",
999
+ " <tr>\n",
1000
+ " <th>1</th>\n",
1001
+ " <td>Seafood</td>\n",
1002
+ " <td>12</td>\n",
1003
+ " <td>20.68</td>\n",
1004
+ " <td>6.00</td>\n",
1005
+ " <td>62.50</td>\n",
1006
+ " </tr>\n",
1007
+ " <tr>\n",
1008
+ " <th>2</th>\n",
1009
+ " <td>Condiments</td>\n",
1010
+ " <td>12</td>\n",
1011
+ " <td>23.06</td>\n",
1012
+ " <td>10.00</td>\n",
1013
+ " <td>43.90</td>\n",
1014
+ " </tr>\n",
1015
+ " <tr>\n",
1016
+ " <th>3</th>\n",
1017
+ " <td>Beverages</td>\n",
1018
+ " <td>12</td>\n",
1019
+ " <td>37.98</td>\n",
1020
+ " <td>4.50</td>\n",
1021
+ " <td>263.50</td>\n",
1022
+ " </tr>\n",
1023
+ " <tr>\n",
1024
+ " <th>4</th>\n",
1025
+ " <td>Dairy Products</td>\n",
1026
+ " <td>10</td>\n",
1027
+ " <td>28.73</td>\n",
1028
+ " <td>2.50</td>\n",
1029
+ " <td>55.00</td>\n",
1030
+ " </tr>\n",
1031
+ " <tr>\n",
1032
+ " <th>5</th>\n",
1033
+ " <td>Grains/Cereals</td>\n",
1034
+ " <td>7</td>\n",
1035
+ " <td>20.25</td>\n",
1036
+ " <td>7.00</td>\n",
1037
+ " <td>38.00</td>\n",
1038
+ " </tr>\n",
1039
+ " <tr>\n",
1040
+ " <th>6</th>\n",
1041
+ " <td>Meat/Poultry</td>\n",
1042
+ " <td>6</td>\n",
1043
+ " <td>54.01</td>\n",
1044
+ " <td>7.45</td>\n",
1045
+ " <td>123.79</td>\n",
1046
+ " </tr>\n",
1047
+ " <tr>\n",
1048
+ " <th>7</th>\n",
1049
+ " <td>Produce</td>\n",
1050
+ " <td>5</td>\n",
1051
+ " <td>32.37</td>\n",
1052
+ " <td>10.00</td>\n",
1053
+ " <td>53.00</td>\n",
1054
+ " </tr>\n",
1055
+ " </tbody>\n",
1056
+ "</table>\n",
1057
+ "</div>"
1058
+ ],
1059
+ "text/plain": [
1060
+ " category_name total_products avg_price min_price max_price\n",
1061
+ "0 Confections 13 25.16 9.20 81.00\n",
1062
+ "1 Seafood 12 20.68 6.00 62.50\n",
1063
+ "2 Condiments 12 23.06 10.00 43.90\n",
1064
+ "3 Beverages 12 37.98 4.50 263.50\n",
1065
+ "4 Dairy Products 10 28.73 2.50 55.00\n",
1066
+ "5 Grains/Cereals 7 20.25 7.00 38.00\n",
1067
+ "6 Meat/Poultry 6 54.01 7.45 123.79\n",
1068
+ "7 Produce 5 32.37 10.00 53.00"
1069
+ ]
1070
+ },
1071
+ "execution_count": 9,
1072
+ "metadata": {},
1073
+ "output_type": "execute_result"
1074
+ }
1075
+ ],
1076
+ "source": [
1077
+ "# Estadisticas de productos por categoria usando GROUP BY\n",
1078
+ "sql(\"\"\"\n",
1079
+ " SELECT c.category_name,\n",
1080
+ " COUNT(p.product_id) AS total_products,\n",
1081
+ " ROUND(AVG(p.price), 2) AS avg_price,\n",
1082
+ " MIN(p.price) AS min_price,\n",
1083
+ " MAX(p.price) AS max_price\n",
1084
+ " FROM categories c\n",
1085
+ " LEFT JOIN products p ON c.category_id = p.category_id\n",
1086
+ " GROUP BY c.category_name\n",
1087
+ " ORDER BY total_products DESC\n",
1088
+ "\"\"\")"
1089
+ ]
1090
+ },
1091
+ {
1092
+ "cell_type": "code",
1093
+ "execution_count": 10,
1094
+ "metadata": {},
1095
+ "outputs": [
1096
+ {
1097
+ "data": {
1098
+ "text/html": [
1099
+ "<div>\n",
1100
+ "<style scoped>\n",
1101
+ " .dataframe tbody tr th:only-of-type {\n",
1102
+ " vertical-align: middle;\n",
1103
+ " }\n",
1104
+ "\n",
1105
+ " .dataframe tbody tr th {\n",
1106
+ " vertical-align: top;\n",
1107
+ " }\n",
1108
+ "\n",
1109
+ " .dataframe thead th {\n",
1110
+ " text-align: right;\n",
1111
+ " }\n",
1112
+ "</style>\n",
1113
+ "<table border=\"1\" class=\"dataframe\">\n",
1114
+ " <thead>\n",
1115
+ " <tr style=\"text-align: right;\">\n",
1116
+ " <th></th>\n",
1117
+ " <th>country</th>\n",
1118
+ " <th>total_customers</th>\n",
1119
+ " </tr>\n",
1120
+ " </thead>\n",
1121
+ " <tbody>\n",
1122
+ " <tr>\n",
1123
+ " <th>0</th>\n",
1124
+ " <td>USA</td>\n",
1125
+ " <td>13</td>\n",
1126
+ " </tr>\n",
1127
+ " <tr>\n",
1128
+ " <th>1</th>\n",
1129
+ " <td>Germany</td>\n",
1130
+ " <td>11</td>\n",
1131
+ " </tr>\n",
1132
+ " <tr>\n",
1133
+ " <th>2</th>\n",
1134
+ " <td>France</td>\n",
1135
+ " <td>11</td>\n",
1136
+ " </tr>\n",
1137
+ " <tr>\n",
1138
+ " <th>3</th>\n",
1139
+ " <td>Brazil</td>\n",
1140
+ " <td>9</td>\n",
1141
+ " </tr>\n",
1142
+ " <tr>\n",
1143
+ " <th>4</th>\n",
1144
+ " <td>UK</td>\n",
1145
+ " <td>7</td>\n",
1146
+ " </tr>\n",
1147
+ " <tr>\n",
1148
+ " <th>5</th>\n",
1149
+ " <td>Spain</td>\n",
1150
+ " <td>5</td>\n",
1151
+ " </tr>\n",
1152
+ " <tr>\n",
1153
+ " <th>6</th>\n",
1154
+ " <td>Mexico</td>\n",
1155
+ " <td>5</td>\n",
1156
+ " </tr>\n",
1157
+ " <tr>\n",
1158
+ " <th>7</th>\n",
1159
+ " <td>Venezuela</td>\n",
1160
+ " <td>4</td>\n",
1161
+ " </tr>\n",
1162
+ " <tr>\n",
1163
+ " <th>8</th>\n",
1164
+ " <td>Italy</td>\n",
1165
+ " <td>3</td>\n",
1166
+ " </tr>\n",
1167
+ " <tr>\n",
1168
+ " <th>9</th>\n",
1169
+ " <td>Canada</td>\n",
1170
+ " <td>3</td>\n",
1171
+ " </tr>\n",
1172
+ " </tbody>\n",
1173
+ "</table>\n",
1174
+ "</div>"
1175
+ ],
1176
+ "text/plain": [
1177
+ " country total_customers\n",
1178
+ "0 USA 13\n",
1179
+ "1 Germany 11\n",
1180
+ "2 France 11\n",
1181
+ "3 Brazil 9\n",
1182
+ "4 UK 7\n",
1183
+ "5 Spain 5\n",
1184
+ "6 Mexico 5\n",
1185
+ "7 Venezuela 4\n",
1186
+ "8 Italy 3\n",
1187
+ "9 Canada 3"
1188
+ ]
1189
+ },
1190
+ "execution_count": 10,
1191
+ "metadata": {},
1192
+ "output_type": "execute_result"
1193
+ }
1194
+ ],
1195
+ "source": [
1196
+ "# Clientes por pais (top 10)\n",
1197
+ "sql(\"\"\"\n",
1198
+ " SELECT country,\n",
1199
+ " COUNT(*) AS total_customers\n",
1200
+ " FROM customers\n",
1201
+ " GROUP BY country\n",
1202
+ " ORDER BY total_customers DESC\n",
1203
+ " LIMIT 10\n",
1204
+ "\"\"\")"
1205
+ ]
1206
+ },
1207
+ {
1208
+ "cell_type": "markdown",
1209
+ "metadata": {},
1210
+ "source": [
1211
+ "## 6. Consultas con el ORM\n",
1212
+ "\n",
1213
+ "El ORM de SQLAlchemy permite construir consultas usando objetos Python. Esto hace el codigo mas seguro y portable entre distintos motores de base de datos. Se usa session.query() para iniciar una consulta y metodos como .filter(), .join(), .order_by() y .limit() para construirla.\n",
1214
+ "\n",
1215
+ "Una ventaja clave del ORM es que las relaciones definidas con relationship() permiten navegar de un objeto a otro sin escribir SQL adicional."
1216
+ ]
1217
+ },
1218
+ {
1219
+ "cell_type": "code",
1220
+ "execution_count": 11,
1221
+ "metadata": {},
1222
+ "outputs": [
1223
+ {
1224
+ "name": "stdout",
1225
+ "output_type": "stream",
1226
+ "text": [
1227
+ " Côte de Blaye $263.5000000000\n",
1228
+ " Thüringer Rostbratwurst $123.7900000000\n",
1229
+ " Mishi Kobe Niku $97.0000000000\n",
1230
+ " Sir Rodney's Marmalade $81.0000000000\n",
1231
+ " Carnarvon Tigers $62.5000000000\n"
1232
+ ]
1233
+ }
1234
+ ],
1235
+ "source": [
1236
+ "# ORM: los 5 productos mas caros\n",
1237
+ "top_products = (\n",
1238
+ " session.query(Product)\n",
1239
+ " .order_by(Product.price.desc())\n",
1240
+ " .limit(5)\n",
1241
+ " .all()\n",
1242
+ ")\n",
1243
+ "\n",
1244
+ "for p in top_products:\n",
1245
+ " print(f\" {p.product_name:40s} ${p.price}\")"
1246
+ ]
1247
+ },
1248
+ {
1249
+ "cell_type": "code",
1250
+ "execution_count": 12,
1251
+ "metadata": {},
1252
+ "outputs": [
1253
+ {
1254
+ "name": "stdout",
1255
+ "output_type": "stream",
1256
+ "text": [
1257
+ " Alfreds Futterkiste Ciudad: Berlin Ordenes: 0\n",
1258
+ " Blauer See Delikatessen Ciudad: Mannheim Ordenes: 0\n",
1259
+ " Drachenblut Delikatessend Ciudad: Aachen Ordenes: 2\n",
1260
+ " Frankenversand Ciudad: München Ordenes: 4\n",
1261
+ " Königlich Essen Ciudad: Brandenburg Ordenes: 2\n",
1262
+ " Lehmanns Marktstand Ciudad: Frankfurt a.M. Ordenes: 3\n",
1263
+ " Morgenstern Gesundkost Ciudad: Leipzig Ordenes: 1\n",
1264
+ " Ottilies Käseladen Ciudad: Köln Ordenes: 1\n",
1265
+ " QUICK-Stop Ciudad: Cunewalde Ordenes: 7\n",
1266
+ " Toms Spezialitäten Ciudad: Münster Ordenes: 1\n",
1267
+ " Die Wandernde Kuh Ciudad: Stuttgart Ordenes: 4\n"
1268
+ ]
1269
+ }
1270
+ ],
1271
+ "source": [
1272
+ "# ORM: clientes de Alemania con el total de ordenes de cada uno\n",
1273
+ "german_customers = (\n",
1274
+ " session.query(Customer)\n",
1275
+ " .filter(Customer.country == \"Germany\")\n",
1276
+ " .all()\n",
1277
+ ")\n",
1278
+ "\n",
1279
+ "for c in german_customers:\n",
1280
+ " print(f\" {c.customer_name:35s} Ciudad: {c.city:15s} Ordenes: {len(c.orders)}\")"
1281
+ ]
1282
+ },
1283
+ {
1284
+ "cell_type": "code",
1285
+ "execution_count": 13,
1286
+ "metadata": {},
1287
+ "outputs": [
1288
+ {
1289
+ "name": "stdout",
1290
+ "output_type": "stream",
1291
+ "text": [
1292
+ "Producto : Chef Anton's Cajun Seasoning\n",
1293
+ "Precio : 22.0000000000\n",
1294
+ "Categoria : Condiments\n",
1295
+ "Proveedor : New Orleans Cajun Delights\n",
1296
+ "Pais : USA\n"
1297
+ ]
1298
+ }
1299
+ ],
1300
+ "source": [
1301
+ "# ORM: navegar la relacion producto -> categoria -> proveedor sin escribir SQL\n",
1302
+ "producto = (\n",
1303
+ " session.query(Product)\n",
1304
+ " .filter(Product.product_name.like(\"%Cajun%\"))\n",
1305
+ " .first()\n",
1306
+ ")\n",
1307
+ "\n",
1308
+ "if producto:\n",
1309
+ " print(\"Producto :\", producto.product_name)\n",
1310
+ " print(\"Precio :\", producto.price)\n",
1311
+ " print(\"Categoria :\", producto.category.category_name)\n",
1312
+ " print(\"Proveedor :\", producto.supplier.supplier_name)\n",
1313
+ " print(\"Pais :\", producto.supplier.country)"
1314
+ ]
1315
+ },
1316
+ {
1317
+ "cell_type": "markdown",
1318
+ "metadata": {},
1319
+ "source": [
1320
+ "## 7. Consultas avanzadas con JOINs y agregaciones\n",
1321
+ "\n",
1322
+ "Combinamos varias tablas para obtener informacion de negocio util. Este tipo de consultas es habitual en reportes y dashboards."
1323
+ ]
1324
+ },
1325
+ {
1326
+ "cell_type": "code",
1327
+ "execution_count": 14,
1328
+ "metadata": {},
1329
+ "outputs": [
1330
+ {
1331
+ "data": {
1332
+ "text/html": [
1333
+ "<div>\n",
1334
+ "<style scoped>\n",
1335
+ " .dataframe tbody tr th:only-of-type {\n",
1336
+ " vertical-align: middle;\n",
1337
+ " }\n",
1338
+ "\n",
1339
+ " .dataframe tbody tr th {\n",
1340
+ " vertical-align: top;\n",
1341
+ " }\n",
1342
+ "\n",
1343
+ " .dataframe thead th {\n",
1344
+ " text-align: right;\n",
1345
+ " }\n",
1346
+ "</style>\n",
1347
+ "<table border=\"1\" class=\"dataframe\">\n",
1348
+ " <thead>\n",
1349
+ " <tr style=\"text-align: right;\">\n",
1350
+ " <th></th>\n",
1351
+ " <th>product_name</th>\n",
1352
+ " <th>category_name</th>\n",
1353
+ " <th>total_units_sold</th>\n",
1354
+ " <th>total_revenue</th>\n",
1355
+ " </tr>\n",
1356
+ " </thead>\n",
1357
+ " <tbody>\n",
1358
+ " <tr>\n",
1359
+ " <th>0</th>\n",
1360
+ " <td>Côte de Blaye</td>\n",
1361
+ " <td>Beverages</td>\n",
1362
+ " <td>239</td>\n",
1363
+ " <td>62976.50</td>\n",
1364
+ " </tr>\n",
1365
+ " <tr>\n",
1366
+ " <th>1</th>\n",
1367
+ " <td>Thüringer Rostbratwurst</td>\n",
1368
+ " <td>Meat/Poultry</td>\n",
1369
+ " <td>168</td>\n",
1370
+ " <td>20796.72</td>\n",
1371
+ " </tr>\n",
1372
+ " <tr>\n",
1373
+ " <th>2</th>\n",
1374
+ " <td>Raclette Courdavault</td>\n",
1375
+ " <td>Dairy Products</td>\n",
1376
+ " <td>346</td>\n",
1377
+ " <td>19030.00</td>\n",
1378
+ " </tr>\n",
1379
+ " <tr>\n",
1380
+ " <th>3</th>\n",
1381
+ " <td>Tarte au sucre</td>\n",
1382
+ " <td>Confections</td>\n",
1383
+ " <td>325</td>\n",
1384
+ " <td>16022.50</td>\n",
1385
+ " </tr>\n",
1386
+ " <tr>\n",
1387
+ " <th>4</th>\n",
1388
+ " <td>Camembert Pierrot</td>\n",
1389
+ " <td>Dairy Products</td>\n",
1390
+ " <td>430</td>\n",
1391
+ " <td>14620.00</td>\n",
1392
+ " </tr>\n",
1393
+ " <tr>\n",
1394
+ " <th>5</th>\n",
1395
+ " <td>Alice Mutton</td>\n",
1396
+ " <td>Meat/Poultry</td>\n",
1397
+ " <td>331</td>\n",
1398
+ " <td>12909.00</td>\n",
1399
+ " </tr>\n",
1400
+ " <tr>\n",
1401
+ " <th>6</th>\n",
1402
+ " <td>Gnocchi di nonna Alice</td>\n",
1403
+ " <td>Grains/Cereals</td>\n",
1404
+ " <td>269</td>\n",
1405
+ " <td>10222.00</td>\n",
1406
+ " </tr>\n",
1407
+ " <tr>\n",
1408
+ " <th>7</th>\n",
1409
+ " <td>Mozzarella di Giovanni</td>\n",
1410
+ " <td>Dairy Products</td>\n",
1411
+ " <td>270</td>\n",
1412
+ " <td>9396.00</td>\n",
1413
+ " </tr>\n",
1414
+ " <tr>\n",
1415
+ " <th>8</th>\n",
1416
+ " <td>Vegie-spread</td>\n",
1417
+ " <td>Condiments</td>\n",
1418
+ " <td>209</td>\n",
1419
+ " <td>9175.10</td>\n",
1420
+ " </tr>\n",
1421
+ " <tr>\n",
1422
+ " <th>9</th>\n",
1423
+ " <td>Manjimup Dried Apples</td>\n",
1424
+ " <td>Produce</td>\n",
1425
+ " <td>163</td>\n",
1426
+ " <td>8639.00</td>\n",
1427
+ " </tr>\n",
1428
+ " <tr>\n",
1429
+ " <th>10</th>\n",
1430
+ " <td>Rössle Sauerkraut</td>\n",
1431
+ " <td>Produce</td>\n",
1432
+ " <td>189</td>\n",
1433
+ " <td>8618.40</td>\n",
1434
+ " </tr>\n",
1435
+ " <tr>\n",
1436
+ " <th>11</th>\n",
1437
+ " <td>Sir Rodney's Marmalade</td>\n",
1438
+ " <td>Confections</td>\n",
1439
+ " <td>106</td>\n",
1440
+ " <td>8586.00</td>\n",
1441
+ " </tr>\n",
1442
+ " <tr>\n",
1443
+ " <th>12</th>\n",
1444
+ " <td>Perth Pasties</td>\n",
1445
+ " <td>Meat/Poultry</td>\n",
1446
+ " <td>251</td>\n",
1447
+ " <td>8232.80</td>\n",
1448
+ " </tr>\n",
1449
+ " <tr>\n",
1450
+ " <th>13</th>\n",
1451
+ " <td>Gumbär Gummibärchen</td>\n",
1452
+ " <td>Confections</td>\n",
1453
+ " <td>232</td>\n",
1454
+ " <td>7245.36</td>\n",
1455
+ " </tr>\n",
1456
+ " <tr>\n",
1457
+ " <th>14</th>\n",
1458
+ " <td>Fløtemysost</td>\n",
1459
+ " <td>Dairy Products</td>\n",
1460
+ " <td>336</td>\n",
1461
+ " <td>7224.00</td>\n",
1462
+ " </tr>\n",
1463
+ " </tbody>\n",
1464
+ "</table>\n",
1465
+ "</div>"
1466
+ ],
1467
+ "text/plain": [
1468
+ " product_name category_name total_units_sold total_revenue\n",
1469
+ "0 Côte de Blaye Beverages 239 62976.50\n",
1470
+ "1 Thüringer Rostbratwurst Meat/Poultry 168 20796.72\n",
1471
+ "2 Raclette Courdavault Dairy Products 346 19030.00\n",
1472
+ "3 Tarte au sucre Confections 325 16022.50\n",
1473
+ "4 Camembert Pierrot Dairy Products 430 14620.00\n",
1474
+ "5 Alice Mutton Meat/Poultry 331 12909.00\n",
1475
+ "6 Gnocchi di nonna Alice Grains/Cereals 269 10222.00\n",
1476
+ "7 Mozzarella di Giovanni Dairy Products 270 9396.00\n",
1477
+ "8 Vegie-spread Condiments 209 9175.10\n",
1478
+ "9 Manjimup Dried Apples Produce 163 8639.00\n",
1479
+ "10 Rössle Sauerkraut Produce 189 8618.40\n",
1480
+ "11 Sir Rodney's Marmalade Confections 106 8586.00\n",
1481
+ "12 Perth Pasties Meat/Poultry 251 8232.80\n",
1482
+ "13 Gumbär Gummibärchen Confections 232 7245.36\n",
1483
+ "14 Fløtemysost Dairy Products 336 7224.00"
1484
+ ]
1485
+ },
1486
+ "execution_count": 14,
1487
+ "metadata": {},
1488
+ "output_type": "execute_result"
1489
+ }
1490
+ ],
1491
+ "source": [
1492
+ "# Reporte de ventas: total de unidades y revenue por producto\n",
1493
+ "sql(\"\"\"\n",
1494
+ " SELECT p.product_name,\n",
1495
+ " c.category_name,\n",
1496
+ " SUM(od.quantity) AS total_units_sold,\n",
1497
+ " ROUND(SUM(od.quantity * p.price), 2) AS total_revenue\n",
1498
+ " FROM order_details od\n",
1499
+ " JOIN products p ON od.product_id = p.product_id\n",
1500
+ " JOIN categories c ON p.category_id = c.category_id\n",
1501
+ " GROUP BY p.product_name, c.category_name\n",
1502
+ " ORDER BY total_revenue DESC\n",
1503
+ " LIMIT 15\n",
1504
+ "\"\"\")"
1505
+ ]
1506
+ },
1507
+ {
1508
+ "cell_type": "code",
1509
+ "execution_count": 15,
1510
+ "metadata": {},
1511
+ "outputs": [
1512
+ {
1513
+ "data": {
1514
+ "text/html": [
1515
+ "<div>\n",
1516
+ "<style scoped>\n",
1517
+ " .dataframe tbody tr th:only-of-type {\n",
1518
+ " vertical-align: middle;\n",
1519
+ " }\n",
1520
+ "\n",
1521
+ " .dataframe tbody tr th {\n",
1522
+ " vertical-align: top;\n",
1523
+ " }\n",
1524
+ "\n",
1525
+ " .dataframe thead th {\n",
1526
+ " text-align: right;\n",
1527
+ " }\n",
1528
+ "</style>\n",
1529
+ "<table border=\"1\" class=\"dataframe\">\n",
1530
+ " <thead>\n",
1531
+ " <tr style=\"text-align: right;\">\n",
1532
+ " <th></th>\n",
1533
+ " <th>employee_name</th>\n",
1534
+ " <th>total_orders</th>\n",
1535
+ " </tr>\n",
1536
+ " </thead>\n",
1537
+ " <tbody>\n",
1538
+ " <tr>\n",
1539
+ " <th>0</th>\n",
1540
+ " <td>Margaret Peacock</td>\n",
1541
+ " <td>40</td>\n",
1542
+ " </tr>\n",
1543
+ " <tr>\n",
1544
+ " <th>1</th>\n",
1545
+ " <td>Janet Leverling</td>\n",
1546
+ " <td>31</td>\n",
1547
+ " </tr>\n",
1548
+ " <tr>\n",
1549
+ " <th>2</th>\n",
1550
+ " <td>Nancy Davolio</td>\n",
1551
+ " <td>29</td>\n",
1552
+ " </tr>\n",
1553
+ " <tr>\n",
1554
+ " <th>3</th>\n",
1555
+ " <td>Laura Callahan</td>\n",
1556
+ " <td>27</td>\n",
1557
+ " </tr>\n",
1558
+ " <tr>\n",
1559
+ " <th>4</th>\n",
1560
+ " <td>Andrew Fuller</td>\n",
1561
+ " <td>20</td>\n",
1562
+ " </tr>\n",
1563
+ " <tr>\n",
1564
+ " <th>5</th>\n",
1565
+ " <td>Michael Suyama</td>\n",
1566
+ " <td>18</td>\n",
1567
+ " </tr>\n",
1568
+ " <tr>\n",
1569
+ " <th>6</th>\n",
1570
+ " <td>Robert King</td>\n",
1571
+ " <td>14</td>\n",
1572
+ " </tr>\n",
1573
+ " <tr>\n",
1574
+ " <th>7</th>\n",
1575
+ " <td>Steven Buchanan</td>\n",
1576
+ " <td>11</td>\n",
1577
+ " </tr>\n",
1578
+ " <tr>\n",
1579
+ " <th>8</th>\n",
1580
+ " <td>Anne Dodsworth</td>\n",
1581
+ " <td>6</td>\n",
1582
+ " </tr>\n",
1583
+ " </tbody>\n",
1584
+ "</table>\n",
1585
+ "</div>"
1586
+ ],
1587
+ "text/plain": [
1588
+ " employee_name total_orders\n",
1589
+ "0 Margaret Peacock 40\n",
1590
+ "1 Janet Leverling 31\n",
1591
+ "2 Nancy Davolio 29\n",
1592
+ "3 Laura Callahan 27\n",
1593
+ "4 Andrew Fuller 20\n",
1594
+ "5 Michael Suyama 18\n",
1595
+ "6 Robert King 14\n",
1596
+ "7 Steven Buchanan 11\n",
1597
+ "8 Anne Dodsworth 6"
1598
+ ]
1599
+ },
1600
+ "execution_count": 15,
1601
+ "metadata": {},
1602
+ "output_type": "execute_result"
1603
+ }
1604
+ ],
1605
+ "source": [
1606
+ "# Empleados mas activos: cuantas ordenes atendio cada uno\n",
1607
+ "sql(\"\"\"\n",
1608
+ " SELECT e.first_name || ' ' || e.last_name AS employee_name,\n",
1609
+ " COUNT(o.order_id) AS total_orders\n",
1610
+ " FROM employees e\n",
1611
+ " JOIN orders o ON e.employee_id = o.employee_id\n",
1612
+ " GROUP BY e.employee_id\n",
1613
+ " ORDER BY total_orders DESC\n",
1614
+ "\"\"\")"
1615
+ ]
1616
+ },
1617
+ {
1618
+ "cell_type": "code",
1619
+ "execution_count": 16,
1620
+ "metadata": {},
1621
+ "outputs": [
1622
+ {
1623
+ "data": {
1624
+ "text/html": [
1625
+ "<div>\n",
1626
+ "<style scoped>\n",
1627
+ " .dataframe tbody tr th:only-of-type {\n",
1628
+ " vertical-align: middle;\n",
1629
+ " }\n",
1630
+ "\n",
1631
+ " .dataframe tbody tr th {\n",
1632
+ " vertical-align: top;\n",
1633
+ " }\n",
1634
+ "\n",
1635
+ " .dataframe thead th {\n",
1636
+ " text-align: right;\n",
1637
+ " }\n",
1638
+ "</style>\n",
1639
+ "<table border=\"1\" class=\"dataframe\">\n",
1640
+ " <thead>\n",
1641
+ " <tr style=\"text-align: right;\">\n",
1642
+ " <th></th>\n",
1643
+ " <th>month</th>\n",
1644
+ " <th>total_orders</th>\n",
1645
+ " </tr>\n",
1646
+ " </thead>\n",
1647
+ " <tbody>\n",
1648
+ " <tr>\n",
1649
+ " <th>0</th>\n",
1650
+ " <td>1996-07</td>\n",
1651
+ " <td>22</td>\n",
1652
+ " </tr>\n",
1653
+ " <tr>\n",
1654
+ " <th>1</th>\n",
1655
+ " <td>1996-08</td>\n",
1656
+ " <td>25</td>\n",
1657
+ " </tr>\n",
1658
+ " <tr>\n",
1659
+ " <th>2</th>\n",
1660
+ " <td>1996-09</td>\n",
1661
+ " <td>23</td>\n",
1662
+ " </tr>\n",
1663
+ " <tr>\n",
1664
+ " <th>3</th>\n",
1665
+ " <td>1996-10</td>\n",
1666
+ " <td>26</td>\n",
1667
+ " </tr>\n",
1668
+ " <tr>\n",
1669
+ " <th>4</th>\n",
1670
+ " <td>1996-11</td>\n",
1671
+ " <td>25</td>\n",
1672
+ " </tr>\n",
1673
+ " <tr>\n",
1674
+ " <th>5</th>\n",
1675
+ " <td>1996-12</td>\n",
1676
+ " <td>31</td>\n",
1677
+ " </tr>\n",
1678
+ " <tr>\n",
1679
+ " <th>6</th>\n",
1680
+ " <td>1997-01</td>\n",
1681
+ " <td>33</td>\n",
1682
+ " </tr>\n",
1683
+ " <tr>\n",
1684
+ " <th>7</th>\n",
1685
+ " <td>1997-02</td>\n",
1686
+ " <td>11</td>\n",
1687
+ " </tr>\n",
1688
+ " </tbody>\n",
1689
+ "</table>\n",
1690
+ "</div>"
1691
+ ],
1692
+ "text/plain": [
1693
+ " month total_orders\n",
1694
+ "0 1996-07 22\n",
1695
+ "1 1996-08 25\n",
1696
+ "2 1996-09 23\n",
1697
+ "3 1996-10 26\n",
1698
+ "4 1996-11 25\n",
1699
+ "5 1996-12 31\n",
1700
+ "6 1997-01 33\n",
1701
+ "7 1997-02 11"
1702
+ ]
1703
+ },
1704
+ "execution_count": 16,
1705
+ "metadata": {},
1706
+ "output_type": "execute_result"
1707
+ }
1708
+ ],
1709
+ "source": [
1710
+ "# Pedidos por mes usando funciones de fecha de SQLite\n",
1711
+ "sql(\"\"\"\n",
1712
+ " SELECT strftime('%Y-%m', order_date) AS month,\n",
1713
+ " COUNT(*) AS total_orders\n",
1714
+ " FROM orders\n",
1715
+ " GROUP BY month\n",
1716
+ " ORDER BY month\n",
1717
+ "\"\"\")"
1718
+ ]
1719
+ },
1720
+ {
1721
+ "cell_type": "code",
1722
+ "execution_count": 17,
1723
+ "metadata": {},
1724
+ "outputs": [
1725
+ {
1726
+ "data": {
1727
+ "text/html": [
1728
+ "<div>\n",
1729
+ "<style scoped>\n",
1730
+ " .dataframe tbody tr th:only-of-type {\n",
1731
+ " vertical-align: middle;\n",
1732
+ " }\n",
1733
+ "\n",
1734
+ " .dataframe tbody tr th {\n",
1735
+ " vertical-align: top;\n",
1736
+ " }\n",
1737
+ "\n",
1738
+ " .dataframe thead th {\n",
1739
+ " text-align: right;\n",
1740
+ " }\n",
1741
+ "</style>\n",
1742
+ "<table border=\"1\" class=\"dataframe\">\n",
1743
+ " <thead>\n",
1744
+ " <tr style=\"text-align: right;\">\n",
1745
+ " <th></th>\n",
1746
+ " <th>customer_name</th>\n",
1747
+ " <th>country</th>\n",
1748
+ " <th>total</th>\n",
1749
+ " </tr>\n",
1750
+ " </thead>\n",
1751
+ " <tbody>\n",
1752
+ " <tr>\n",
1753
+ " <th>0</th>\n",
1754
+ " <td>Ernst Handel</td>\n",
1755
+ " <td>Austria</td>\n",
1756
+ " <td>10</td>\n",
1757
+ " </tr>\n",
1758
+ " <tr>\n",
1759
+ " <th>1</th>\n",
1760
+ " <td>QUICK-Stop</td>\n",
1761
+ " <td>Germany</td>\n",
1762
+ " <td>7</td>\n",
1763
+ " </tr>\n",
1764
+ " <tr>\n",
1765
+ " <th>2</th>\n",
1766
+ " <td>Rattlesnake Canyon Grocery</td>\n",
1767
+ " <td>USA</td>\n",
1768
+ " <td>7</td>\n",
1769
+ " </tr>\n",
1770
+ " <tr>\n",
1771
+ " <th>3</th>\n",
1772
+ " <td>Wartian Herkku</td>\n",
1773
+ " <td>Finland</td>\n",
1774
+ " <td>7</td>\n",
1775
+ " </tr>\n",
1776
+ " <tr>\n",
1777
+ " <th>4</th>\n",
1778
+ " <td>Hungry Owl All-Night Grocers</td>\n",
1779
+ " <td>Ireland</td>\n",
1780
+ " <td>6</td>\n",
1781
+ " </tr>\n",
1782
+ " <tr>\n",
1783
+ " <th>5</th>\n",
1784
+ " <td>Split Rail Beer &amp; Ale</td>\n",
1785
+ " <td>USA</td>\n",
1786
+ " <td>6</td>\n",
1787
+ " </tr>\n",
1788
+ " <tr>\n",
1789
+ " <th>6</th>\n",
1790
+ " <td>La maison d'Asie</td>\n",
1791
+ " <td>France</td>\n",
1792
+ " <td>5</td>\n",
1793
+ " </tr>\n",
1794
+ " <tr>\n",
1795
+ " <th>7</th>\n",
1796
+ " <td>LILA-Supermercado</td>\n",
1797
+ " <td>Venezuela</td>\n",
1798
+ " <td>5</td>\n",
1799
+ " </tr>\n",
1800
+ " <tr>\n",
1801
+ " <th>8</th>\n",
1802
+ " <td>Mère Paillarde</td>\n",
1803
+ " <td>Canada</td>\n",
1804
+ " <td>5</td>\n",
1805
+ " </tr>\n",
1806
+ " <tr>\n",
1807
+ " <th>9</th>\n",
1808
+ " <td>Blondel père et fils</td>\n",
1809
+ " <td>France</td>\n",
1810
+ " <td>4</td>\n",
1811
+ " </tr>\n",
1812
+ " <tr>\n",
1813
+ " <th>10</th>\n",
1814
+ " <td>Bottom-Dollar Marketse</td>\n",
1815
+ " <td>Canada</td>\n",
1816
+ " <td>4</td>\n",
1817
+ " </tr>\n",
1818
+ " <tr>\n",
1819
+ " <th>11</th>\n",
1820
+ " <td>Folk och fä HB</td>\n",
1821
+ " <td>Sweden</td>\n",
1822
+ " <td>4</td>\n",
1823
+ " </tr>\n",
1824
+ " <tr>\n",
1825
+ " <th>12</th>\n",
1826
+ " <td>Frankenversand</td>\n",
1827
+ " <td>Germany</td>\n",
1828
+ " <td>4</td>\n",
1829
+ " </tr>\n",
1830
+ " <tr>\n",
1831
+ " <th>13</th>\n",
1832
+ " <td>Old World Delicatessen</td>\n",
1833
+ " <td>USA</td>\n",
1834
+ " <td>4</td>\n",
1835
+ " </tr>\n",
1836
+ " <tr>\n",
1837
+ " <th>14</th>\n",
1838
+ " <td>Que Delícia</td>\n",
1839
+ " <td>Brazil</td>\n",
1840
+ " <td>4</td>\n",
1841
+ " </tr>\n",
1842
+ " <tr>\n",
1843
+ " <th>15</th>\n",
1844
+ " <td>Save-a-lot Markets</td>\n",
1845
+ " <td>USA</td>\n",
1846
+ " <td>4</td>\n",
1847
+ " </tr>\n",
1848
+ " <tr>\n",
1849
+ " <th>16</th>\n",
1850
+ " <td>Tortuga Restaurante</td>\n",
1851
+ " <td>Mexico</td>\n",
1852
+ " <td>4</td>\n",
1853
+ " </tr>\n",
1854
+ " <tr>\n",
1855
+ " <th>17</th>\n",
1856
+ " <td>Die Wandernde Kuh</td>\n",
1857
+ " <td>Germany</td>\n",
1858
+ " <td>4</td>\n",
1859
+ " </tr>\n",
1860
+ " <tr>\n",
1861
+ " <th>18</th>\n",
1862
+ " <td>Berglunds snabbköp</td>\n",
1863
+ " <td>Sweden</td>\n",
1864
+ " <td>3</td>\n",
1865
+ " </tr>\n",
1866
+ " <tr>\n",
1867
+ " <th>19</th>\n",
1868
+ " <td>Bon app</td>\n",
1869
+ " <td>France</td>\n",
1870
+ " <td>3</td>\n",
1871
+ " </tr>\n",
1872
+ " <tr>\n",
1873
+ " <th>20</th>\n",
1874
+ " <td>Familia Arquibaldo</td>\n",
1875
+ " <td>Brazil</td>\n",
1876
+ " <td>3</td>\n",
1877
+ " </tr>\n",
1878
+ " <tr>\n",
1879
+ " <th>21</th>\n",
1880
+ " <td>Hungry Coyote Import Store</td>\n",
1881
+ " <td>USA</td>\n",
1882
+ " <td>3</td>\n",
1883
+ " </tr>\n",
1884
+ " <tr>\n",
1885
+ " <th>22</th>\n",
1886
+ " <td>Island Trading</td>\n",
1887
+ " <td>UK</td>\n",
1888
+ " <td>3</td>\n",
1889
+ " </tr>\n",
1890
+ " <tr>\n",
1891
+ " <th>23</th>\n",
1892
+ " <td>Lehmanns Marktstand</td>\n",
1893
+ " <td>Germany</td>\n",
1894
+ " <td>3</td>\n",
1895
+ " </tr>\n",
1896
+ " <tr>\n",
1897
+ " <th>24</th>\n",
1898
+ " <td>Magazzini Alimentari Riuniti</td>\n",
1899
+ " <td>Italy</td>\n",
1900
+ " <td>3</td>\n",
1901
+ " </tr>\n",
1902
+ " <tr>\n",
1903
+ " <th>25</th>\n",
1904
+ " <td>Piccolo und mehr</td>\n",
1905
+ " <td>Austria</td>\n",
1906
+ " <td>3</td>\n",
1907
+ " </tr>\n",
1908
+ " <tr>\n",
1909
+ " <th>26</th>\n",
1910
+ " <td>Princesa Isabel Vinhoss</td>\n",
1911
+ " <td>Portugal</td>\n",
1912
+ " <td>3</td>\n",
1913
+ " </tr>\n",
1914
+ " <tr>\n",
1915
+ " <th>27</th>\n",
1916
+ " <td>Reggiani Caseifici</td>\n",
1917
+ " <td>Italy</td>\n",
1918
+ " <td>3</td>\n",
1919
+ " </tr>\n",
1920
+ " <tr>\n",
1921
+ " <th>28</th>\n",
1922
+ " <td>Romero y tomillo</td>\n",
1923
+ " <td>Spain</td>\n",
1924
+ " <td>3</td>\n",
1925
+ " </tr>\n",
1926
+ " <tr>\n",
1927
+ " <th>29</th>\n",
1928
+ " <td>Seven Seas Imports</td>\n",
1929
+ " <td>UK</td>\n",
1930
+ " <td>3</td>\n",
1931
+ " </tr>\n",
1932
+ " </tbody>\n",
1933
+ "</table>\n",
1934
+ "</div>"
1935
+ ],
1936
+ "text/plain": [
1937
+ " customer_name country total\n",
1938
+ "0 Ernst Handel Austria 10\n",
1939
+ "1 QUICK-Stop Germany 7\n",
1940
+ "2 Rattlesnake Canyon Grocery USA 7\n",
1941
+ "3 Wartian Herkku Finland 7\n",
1942
+ "4 Hungry Owl All-Night Grocers Ireland 6\n",
1943
+ "5 Split Rail Beer & Ale USA 6\n",
1944
+ "6 La maison d'Asie France 5\n",
1945
+ "7 LILA-Supermercado Venezuela 5\n",
1946
+ "8 Mère Paillarde Canada 5\n",
1947
+ "9 Blondel père et fils France 4\n",
1948
+ "10 Bottom-Dollar Marketse Canada 4\n",
1949
+ "11 Folk och fä HB Sweden 4\n",
1950
+ "12 Frankenversand Germany 4\n",
1951
+ "13 Old World Delicatessen USA 4\n",
1952
+ "14 Que Delícia Brazil 4\n",
1953
+ "15 Save-a-lot Markets USA 4\n",
1954
+ "16 Tortuga Restaurante Mexico 4\n",
1955
+ "17 Die Wandernde Kuh Germany 4\n",
1956
+ "18 Berglunds snabbköp Sweden 3\n",
1957
+ "19 Bon app France 3\n",
1958
+ "20 Familia Arquibaldo Brazil 3\n",
1959
+ "21 Hungry Coyote Import Store USA 3\n",
1960
+ "22 Island Trading UK 3\n",
1961
+ "23 Lehmanns Marktstand Germany 3\n",
1962
+ "24 Magazzini Alimentari Riuniti Italy 3\n",
1963
+ "25 Piccolo und mehr Austria 3\n",
1964
+ "26 Princesa Isabel Vinhoss Portugal 3\n",
1965
+ "27 Reggiani Caseifici Italy 3\n",
1966
+ "28 Romero y tomillo Spain 3\n",
1967
+ "29 Seven Seas Imports UK 3"
1968
+ ]
1969
+ },
1970
+ "execution_count": 17,
1971
+ "metadata": {},
1972
+ "output_type": "execute_result"
1973
+ }
1974
+ ],
1975
+ "source": [
1976
+ "# Subquery: clientes que hicieron mas de 2 pedidos\n",
1977
+ "sql(\"\"\"\n",
1978
+ " SELECT c.customer_name,\n",
1979
+ " c.country,\n",
1980
+ " oc.total\n",
1981
+ " FROM customers c\n",
1982
+ " JOIN (\n",
1983
+ " SELECT customer_id, COUNT(*) AS total\n",
1984
+ " FROM orders\n",
1985
+ " GROUP BY customer_id\n",
1986
+ " HAVING COUNT(*) > 2\n",
1987
+ " ) AS oc ON c.customer_id = oc.customer_id\n",
1988
+ " ORDER BY oc.total DESC\n",
1989
+ "\"\"\")"
1990
+ ]
1991
+ },
1992
+ {
1993
+ "cell_type": "code",
1994
+ "execution_count": 18,
1995
+ "metadata": {},
1996
+ "outputs": [
1997
+ {
1998
+ "data": {
1999
+ "text/html": [
2000
+ "<div>\n",
2001
+ "<style scoped>\n",
2002
+ " .dataframe tbody tr th:only-of-type {\n",
2003
+ " vertical-align: middle;\n",
2004
+ " }\n",
2005
+ "\n",
2006
+ " .dataframe tbody tr th {\n",
2007
+ " vertical-align: top;\n",
2008
+ " }\n",
2009
+ "\n",
2010
+ " .dataframe thead th {\n",
2011
+ " text-align: right;\n",
2012
+ " }\n",
2013
+ "</style>\n",
2014
+ "<table border=\"1\" class=\"dataframe\">\n",
2015
+ " <thead>\n",
2016
+ " <tr style=\"text-align: right;\">\n",
2017
+ " <th></th>\n",
2018
+ " <th>supplier_name</th>\n",
2019
+ " <th>country</th>\n",
2020
+ " <th>num_products</th>\n",
2021
+ " <th>avg_price</th>\n",
2022
+ " </tr>\n",
2023
+ " </thead>\n",
2024
+ " <tbody>\n",
2025
+ " <tr>\n",
2026
+ " <th>0</th>\n",
2027
+ " <td>Plutzer Lebensmittelgroßmärkte AG</td>\n",
2028
+ " <td>Germany</td>\n",
2029
+ " <td>5</td>\n",
2030
+ " <td>44.68</td>\n",
2031
+ " </tr>\n",
2032
+ " <tr>\n",
2033
+ " <th>1</th>\n",
2034
+ " <td>Pavlova, Ltd.</td>\n",
2035
+ " <td>Australia</td>\n",
2036
+ " <td>5</td>\n",
2037
+ " <td>35.57</td>\n",
2038
+ " </tr>\n",
2039
+ " <tr>\n",
2040
+ " <th>2</th>\n",
2041
+ " <td>Specialty Biscuits, Ltd.</td>\n",
2042
+ " <td>UK</td>\n",
2043
+ " <td>4</td>\n",
2044
+ " <td>28.18</td>\n",
2045
+ " </tr>\n",
2046
+ " <tr>\n",
2047
+ " <th>3</th>\n",
2048
+ " <td>New Orleans Cajun Delights</td>\n",
2049
+ " <td>USA</td>\n",
2050
+ " <td>4</td>\n",
2051
+ " <td>20.35</td>\n",
2052
+ " </tr>\n",
2053
+ " <tr>\n",
2054
+ " <th>4</th>\n",
2055
+ " <td>G'day, Mate</td>\n",
2056
+ " <td>Australia</td>\n",
2057
+ " <td>3</td>\n",
2058
+ " <td>30.93</td>\n",
2059
+ " </tr>\n",
2060
+ " <tr>\n",
2061
+ " <th>5</th>\n",
2062
+ " <td>Karkki Oy</td>\n",
2063
+ " <td>Finland</td>\n",
2064
+ " <td>3</td>\n",
2065
+ " <td>18.08</td>\n",
2066
+ " </tr>\n",
2067
+ " <tr>\n",
2068
+ " <th>6</th>\n",
2069
+ " <td>Leka Trading</td>\n",
2070
+ " <td>Singapore</td>\n",
2071
+ " <td>3</td>\n",
2072
+ " <td>26.48</td>\n",
2073
+ " </tr>\n",
2074
+ " <tr>\n",
2075
+ " <th>7</th>\n",
2076
+ " <td>Svensk Sjöföda AB</td>\n",
2077
+ " <td>Sweden</td>\n",
2078
+ " <td>3</td>\n",
2079
+ " <td>20.00</td>\n",
2080
+ " </tr>\n",
2081
+ " <tr>\n",
2082
+ " <th>8</th>\n",
2083
+ " <td>Bigfoot Breweries</td>\n",
2084
+ " <td>USA</td>\n",
2085
+ " <td>3</td>\n",
2086
+ " <td>15.33</td>\n",
2087
+ " </tr>\n",
2088
+ " <tr>\n",
2089
+ " <th>9</th>\n",
2090
+ " <td>Norske Meierier</td>\n",
2091
+ " <td>Norway</td>\n",
2092
+ " <td>3</td>\n",
2093
+ " <td>20.00</td>\n",
2094
+ " </tr>\n",
2095
+ " </tbody>\n",
2096
+ "</table>\n",
2097
+ "</div>"
2098
+ ],
2099
+ "text/plain": [
2100
+ " supplier_name country num_products avg_price\n",
2101
+ "0 Plutzer Lebensmittelgroßmärkte AG Germany 5 44.68\n",
2102
+ "1 Pavlova, Ltd. Australia 5 35.57\n",
2103
+ "2 Specialty Biscuits, Ltd. UK 4 28.18\n",
2104
+ "3 New Orleans Cajun Delights USA 4 20.35\n",
2105
+ "4 G'day, Mate Australia 3 30.93\n",
2106
+ "5 Karkki Oy Finland 3 18.08\n",
2107
+ "6 Leka Trading Singapore 3 26.48\n",
2108
+ "7 Svensk Sjöföda AB Sweden 3 20.00\n",
2109
+ "8 Bigfoot Breweries USA 3 15.33\n",
2110
+ "9 Norske Meierier Norway 3 20.00"
2111
+ ]
2112
+ },
2113
+ "execution_count": 18,
2114
+ "metadata": {},
2115
+ "output_type": "execute_result"
2116
+ }
2117
+ ],
2118
+ "source": [
2119
+ "# Proveedores con mas productos en el catalogo\n",
2120
+ "sql(\"\"\"\n",
2121
+ " SELECT s.supplier_name,\n",
2122
+ " s.country,\n",
2123
+ " COUNT(p.product_id) AS num_products,\n",
2124
+ " ROUND(AVG(p.price), 2) AS avg_price\n",
2125
+ " FROM suppliers s\n",
2126
+ " JOIN products p ON s.supplier_id = p.supplier_id\n",
2127
+ " GROUP BY s.supplier_id\n",
2128
+ " ORDER BY num_products DESC\n",
2129
+ " LIMIT 10\n",
2130
+ "\"\"\")"
2131
+ ]
2132
+ },
2133
+ {
2134
+ "cell_type": "code",
2135
+ "execution_count": 19,
2136
+ "metadata": {},
2137
+ "outputs": [
2138
+ {
2139
+ "data": {
2140
+ "text/html": [
2141
+ "<div>\n",
2142
+ "<style scoped>\n",
2143
+ " .dataframe tbody tr th:only-of-type {\n",
2144
+ " vertical-align: middle;\n",
2145
+ " }\n",
2146
+ "\n",
2147
+ " .dataframe tbody tr th {\n",
2148
+ " vertical-align: top;\n",
2149
+ " }\n",
2150
+ "\n",
2151
+ " .dataframe thead th {\n",
2152
+ " text-align: right;\n",
2153
+ " }\n",
2154
+ "</style>\n",
2155
+ "<table border=\"1\" class=\"dataframe\">\n",
2156
+ " <thead>\n",
2157
+ " <tr style=\"text-align: right;\">\n",
2158
+ " <th></th>\n",
2159
+ " <th>shipper_name</th>\n",
2160
+ " <th>shipments</th>\n",
2161
+ " </tr>\n",
2162
+ " </thead>\n",
2163
+ " <tbody>\n",
2164
+ " <tr>\n",
2165
+ " <th>0</th>\n",
2166
+ " <td>United Package</td>\n",
2167
+ " <td>74</td>\n",
2168
+ " </tr>\n",
2169
+ " <tr>\n",
2170
+ " <th>1</th>\n",
2171
+ " <td>Federal Shipping</td>\n",
2172
+ " <td>68</td>\n",
2173
+ " </tr>\n",
2174
+ " <tr>\n",
2175
+ " <th>2</th>\n",
2176
+ " <td>Speedy Express</td>\n",
2177
+ " <td>54</td>\n",
2178
+ " </tr>\n",
2179
+ " </tbody>\n",
2180
+ "</table>\n",
2181
+ "</div>"
2182
+ ],
2183
+ "text/plain": [
2184
+ " shipper_name shipments\n",
2185
+ "0 United Package 74\n",
2186
+ "1 Federal Shipping 68\n",
2187
+ "2 Speedy Express 54"
2188
+ ]
2189
+ },
2190
+ "execution_count": 19,
2191
+ "metadata": {},
2192
+ "output_type": "execute_result"
2193
+ }
2194
+ ],
2195
+ "source": [
2196
+ "# Transportista mas usado\n",
2197
+ "sql(\"\"\"\n",
2198
+ " SELECT sh.shipper_name,\n",
2199
+ " COUNT(o.order_id) AS shipments\n",
2200
+ " FROM shippers sh\n",
2201
+ " JOIN orders o ON sh.shipper_id = o.shipper_id\n",
2202
+ " GROUP BY sh.shipper_name\n",
2203
+ " ORDER BY shipments DESC\n",
2204
+ "\"\"\")"
2205
+ ]
2206
+ },
2207
+ {
2208
+ "cell_type": "markdown",
2209
+ "metadata": {},
2210
+ "source": [
2211
+ "## Resumen\n",
2212
+ "\n",
2213
+ "En este notebook aprendimos a:\n",
2214
+ "\n",
2215
+ "1. Crear un motor de base de datos con create_engine() y conectarlo a SQLite.\n",
2216
+ "2. Definir modelos ORM como clases Python con columnas, tipos y claves foraneas.\n",
2217
+ "3. Crear las tablas en la base de datos con Base.metadata.create_all(engine).\n",
2218
+ "4. Leer y parsear un archivo `.sql` externo para extraer los datos de insercion.\n",
2219
+ "5. Poblar la base de datos desde el archivo, sin datos fijos en el codigo del notebook.\n",
2220
+ "6. Ejecutar SQL crudo con text() y convertir los resultados a DataFrames de pandas.\n",
2221
+ "7. Usar el ORM para consultas con filtros, ordenamiento y navegacion de relaciones.\n",
2222
+ "8. Escribir consultas avanzadas con JOINs, GROUP BY, HAVING y subconsultas.\n",
2223
+ "\n",
2224
+ "Para produccion se recomienda usar PostgreSQL o MySQL en lugar de SQLite, pero la API de SQLAlchemy es identica: solo cambia la cadena de conexion del create_engine()."
2225
+ ]
2226
+ },
2227
+ {
2228
+ "cell_type": "markdown",
2229
+ "id": "3a324f40",
2230
+ "metadata": {},
2231
+ "source": []
2232
+ },
2233
+ {
2234
+ "cell_type": "markdown",
2235
+ "id": "53a28a32",
2236
+ "metadata": {},
2237
+ "source": []
2238
+ }
2239
+ ],
2240
+ "metadata": {
2241
+ "kernelspec": {
2242
+ "display_name": "entorno1",
2243
+ "language": "python",
2244
+ "name": "python3"
2245
+ },
2246
+ "language_info": {
2247
+ "codemirror_mode": {
2248
+ "name": "ipython",
2249
+ "version": 3
2250
+ },
2251
+ "file_extension": ".py",
2252
+ "mimetype": "text/x-python",
2253
+ "name": "python",
2254
+ "nbconvert_exporter": "python",
2255
+ "pygments_lexer": "ipython3",
2256
+ "version": "3.9.23"
2257
+ }
2258
+ },
2259
+ "nbformat": 4,
2260
+ "nbformat_minor": 5
2261
+ }