-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_data.py
More file actions
1060 lines (783 loc) · 39.3 KB
/
Copy pathanalyze_data.py
File metadata and controls
1060 lines (783 loc) · 39.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""analyze_data.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1C9sH3CaJGJYlDKOW0QdzuRbTzR_YzNWG
# **E-Commerce Data Analysis**
## **Introduction**
This assignment focuses on building and analyzing a relational database for an e-commerce application using SQLite and Python. The objective is to demonstrate end-to-end data handling skills, including database creation, data import, and analytical querying. By combining SQL-based queries with Python-based data processing, the assignment highlights an understanding of both database-side operations and application-level analysis. The insights generated from this project support data-driven decision-making related to customers, products, revenue, and sales trends.
## **Part 2: SQL Queries and Python Analysis**
This section performs analytical queries on the e-commerce SQLite database created in Part 1. The goal is to answer key business questions using both **SQL-based** and **Python-based** data processing techniques.
## **What We Will Do**
1. Upload the SQLite database file.
2. Execute **five analytical queries** that address practical business questions.
3. For **Queries 3–5**, implement **both SQL and Python versions** of each analysis to demonstrate understanding of database-side and application-side data processing.
## **Query Difficulty Progression**
| Query | Difficulty | Technique Used |
|---------|---------------|------------------------------------|
| Query 1 | Basic | SELECT with WHERE (SQL only) |
| Query 2 | Intermediate | JOIN tables (SQL only) |
| Query 3 | Advanced | GROUP BY (SQL + Python) |
| Query 4 | Advanced | GROUP BY (SQL + Python) |
| Query 5 | Advanced | GROUP BY (SQL + Python) |
This progression ensures a gradual increase in complexity, moving from simple filtering to multi-table joins and finally to aggregated analyses implemented using both SQL and Python logic.
## **Upload CSV Files**
In this step, upload all three CSV files **one by one** so they are available in the Colab runtime environment.
## **Upload File 1: customers.csv**
Begin by uploading the **customers.csv** file. This file contains customer-level information and will be used later for database analysis and querying.
"""
from google.colab import files
print("Please select 'customers (1).csv' file")
uploaded = files.upload()
print("Customers file uploaded!")
"""The `customers.csv` file has been successfully uploaded and is now available in the runtime environment. This file will be used as input for the analytical queries performed in this section.
## **Upload File 2: products.csv**
Next, upload the **products.csv** file. This file contains product-level details such as product name, category, price, and cost, which will be used in join operations and aggregated analyses in the queries that follow.
"""
print("Please select 'products (1).csv' file")
uploaded = files.upload()
print("Products file uploaded!")
"""The `products.csv` file has been successfully uploaded and is now available in the runtime environment. This file will be used in subsequent queries that involve joining product information with customer and order data.
## **Upload File 3: orders.csv**
Finally, upload the **orders.csv** file. This file contains transaction-level order data, including customer IDs, product IDs, quantities, and order dates.
This dataset will be used extensively in join operations and aggregated analyses to answer business questions related to sales, revenue, and customer behavior.
"""
print("Please select 'orders (1).csv' file")
uploaded = files.upload()
print("Orders file uploaded!")
"""The `orders.csv` file has been successfully uploaded and is now available in the runtime environment. This file contains the transactional data required for performing joins and aggregated analyses in the queries that follow.
## **Create Database and Import Data**
In this step, we create the SQLite database and populate it with data from the uploaded CSV files.
The database schema is defined programmatically, and the data is imported in the correct order to maintain referential integrity between tables.
Once this step is complete, the database will be fully initialized and ready for analytical queries in the following sections.
"""
import sqlite3
import csv
DB_PATH = "ecommerce.db"
def create_database(db_path):
"""
Create the SQLite database and define all table schemas.
Existing tables are dropped to ensure a clean setup when rerun.
"""
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Enable foreign key constraint enforcement in SQLite
cursor.execute("PRAGMA foreign_keys = ON;")
# Drop tables if they already exist to avoid conflicts
cursor.execute("DROP TABLE IF EXISTS orders;")
cursor.execute("DROP TABLE IF EXISTS products;")
cursor.execute("DROP TABLE IF EXISTS customers;")
# Create customers table
cursor.execute("""
CREATE TABLE IF NOT EXISTS customers (
customer_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
city TEXT NOT NULL,
join_date DATE NOT NULL
)
""")
print(" Created 'customers' table")
# Create products table
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
product_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
category TEXT NOT NULL,
price REAL NOT NULL CHECK(price >= 0),
cost REAL NOT NULL CHECK(cost >= 0)
)
""")
print(" Created 'products' table")
# Create orders table with foreign key references
cursor.execute("""
CREATE TABLE IF NOT EXISTS orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK(quantity > 0),
order_date DATE NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (product_id) REFERENCES products(product_id)
)
""")
print(" Created 'orders' table")
# Commit all schema changes
conn.commit()
print(f"\nDatabase created: {db_path}")
def import_csv(db_path, csv_file, table_name):
"""
Import data from a CSV file into the specified database table.
Assumes the CSV column order matches the table schema.
"""
rows_imported = 0
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Open CSV file for reading
with open(csv_file, "r", newline="", encoding="utf-8") as file:
csv_reader = csv.reader(file)
# Read header to determine number of columns
header = next(csv_reader)
# Build parameterized INSERT statement
placeholders = ", ".join(["?" for _ in range(len(header))])
insert_sql = f"INSERT INTO {table_name} VALUES ({placeholders})"
# Insert each row into the table
for row in csv_reader:
cursor.execute(insert_sql, row)
rows_imported += 1
# Commit inserted rows
conn.commit()
print(f" Imported {rows_imported} rows into '{table_name}'")
return rows_imported
def verify_data(db_path):
"""
Verify successful data import by printing row counts for each table.
"""
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
tables = ["customers", "products", "orders"]
print("\nRow Counts:")
total = 0
# Count records in each table
for table in tables:
cursor.execute(f"SELECT COUNT(*) FROM {table}")
count = cursor.fetchone()[0]
total += count
print(f" {table:15} : {count:5} rows")
print(f" {'TOTAL':15} : {total:5} rows")
print("=" * 50)
print("DATABASE SETUP")
print("=" * 50)
print("\nCreating database and tables...")
create_database(DB_PATH)
print("\nImporting data from CSV files...")
import_csv(DB_PATH, "customers (1).csv", "customers")
import_csv(DB_PATH, "products (1).csv", "products")
import_csv(DB_PATH, "orders (1).csv", "orders")
print("\nVerifying data...")
verify_data(DB_PATH)
print("\n" + "=" * 50)
print("DATABASE SETUP COMPLETE!")
print("=" * 50)
"""## **Database Setup Summary**
The SQLite database was created successfully, and all tables were populated as expected.
- **Tables created:** customers, products, orders
- **Data imported:**
- 30 customer records
- 20 product records
- 100 order records
- **Total records:** 150 rows across all tables
The successful row counts confirm that the database schema and data import process worked correctly. The database is now ready for analytical queries in Part 2.
## **Data Analysis Queries**
## **Query 1: Basic SELECT with WHERE**
**Business Question:** Which customers are located in Boston for targeted local marketing?
This query uses a simple `SELECT` statement with a `WHERE` clause to filter customer records based on city. It demonstrates basic SQL filtering and serves as the introductory query in the analysis progression.
"""
def query1_customers_by_city(db_path, city):
"""
Find all customers from a specific city.
Business question:
Which customers are in Boston for local marketing
Args:
db_path
Path to the SQLite database file
city
Name of the city used for filtering
Returns:
A list of tuples containing customer records
"""
# Connect to the SQLite database
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Execute a parameterized SQL query to filter customers by city
results = cursor.execute(
"SELECT * FROM customers WHERE city = ?",
(city,)
).fetchall()
# Return the filtered customer records
return results
# Execute Query 1
print("=" * 60)
print("QUERY 1: Customers in Boston")
print("Business Question: Which customers are in Boston for local marketing?")
print("=" * 60)
# Call the query function with Boston as the city filter
results = query1_customers_by_city(DB_PATH, "Boston")
# Display the number of matching customers
print(f"\nFound {len(results)} customers in Boston:\n")
# Print table header for readable output
print(f"{'ID':<5} {'Name':<20} {'Email':<25} {'City':<12} {'Join Date'}")
# Print each customer record in formatted columns
for row in results:
print(f"{row[0]:<5} {row[1]:<20} {row[2]:<25} {row[3]:<12} {row[4]}")
"""## **Query 1 Result Interpretation**
The query identified **12 customers located in Boston**. These customers represent a clear target segment for local marketing campaigns, such as city-specific promotions or in-person events.
By filtering customer records using a simple `WHERE` clause, this query demonstrates how basic SQL can be used to extract actionable insights from the database.
## **Query 2: JOIN Tables**
**Business Question:** What are the complete order details, including customer and product information?
This query uses SQL `JOIN` operations to combine data from the `orders`, `customers`, and `products` tables. By linking these tables through their foreign key relationships, the query produces a complete view of each order, including who placed the order and which product was purchased.
"""
def query2_order_details(db_path, limit=10):
"""
Retrieve complete order details including customer and product information.
Business question:
What are the complete order details including customer and product information
Args:
db_path
Path to the SQLite database file
limit
Maximum number of order records to return
Returns:
A list of tuples containing detailed order information
"""
# Connect to the SQLite database
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Execute a SQL query that joins orders, customers, and products
results = cursor.execute("""
SELECT
o.order_id,
c.name AS customer_name,
c.city,
p.name AS product_name,
p.category,
o.quantity,
p.price,
ROUND(o.quantity * p.price, 2) AS total_amount,
o.order_date
FROM orders o
INNER JOIN customers c ON o.customer_id = c.customer_id
INNER JOIN products p ON o.product_id = p.product_id
ORDER BY o.order_date DESC
LIMIT ?
""", (limit,)).fetchall()
# Return the combined order records
return results
# Execute Query 2
print("=" * 60)
print("QUERY 2: Complete Order Details")
print("Business Question: What are the complete order details?")
print("=" * 60)
# Call the query function to retrieve recent orders
results = query2_order_details(DB_PATH, 10)
# Display the number of orders returned
print(f"\nShowing {len(results)} most recent orders:\n")
# Print column headers for readable output
print(f"{'ID':<5} {'Customer':<18} {'City':<12} {'Product':<18} {'Qty':<5} {'Price':<8} {'Total':<10} {'Date'}")
# Print each order record in a formatted row
for row in results:
print(
f"{row[0]:<5} "
f"{row[1]:<18} "
f"{row[2]:<12} "
f"{row[3]:<18} "
f"{row[5]:<5} "
f"${row[6]:<7} "
f"${row[7]:<9} "
f"{row[8]}"
)
"""## **Query 2 Result Interpretation**
This query returns the **most recent order transactions** with complete details by joining customer, product, and order information. Each record shows who placed the order, where the customer is located, what product was purchased, the quantity, and the total order value.
By using SQL `JOIN` operations, this query demonstrates how data from multiple related tables can be combined to produce a comprehensive, transaction-level view of business activity.
## **Query 3: Revenue by Category (SQL + Python Versions)**
**Business Question:** Which product categories generate the most revenue?
This analysis calculates total revenue by product category to identify the strongest revenue drivers in the product portfolio.
To demonstrate both database-side and application-side data processing, this query is implemented in **two ways**:
1. **SQL Version**
Uses SQL `GROUP BY` and `SUM` to aggregate revenue directly within the database.
2. **Python Version**
Retrieves detailed order and product data using a SQL query with joins, then performs all grouping, aggregation, and sorting in Python using loops, dictionaries, and built-in functions.
Both implementations are expected to return the same results, confirming consistency between SQL-based and Python-based aggregation approaches.
## **Query 3.1: Revenue by Category — SQL Version**
This implementation calculates total revenue by product category using SQL aggregation functions.
The query performs all grouping and summation directly within the database using `GROUP BY` and `SUM`.
"""
def query3_revenue_by_category_sql(db_path):
"""
Calculate total revenue by product category using SQL aggregation.
Business question:
Which product categories generate the most revenue
This version performs all grouping and aggregation directly in SQL.
Returns:
A list of tuples containing
category
total number of orders
total quantity sold
total revenue
"""
# Connect to the SQLite database
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Execute SQL query that aggregates revenue by product category
results = cursor.execute("""
SELECT
p.category,
COUNT(o.order_id) AS total_orders,
SUM(o.quantity) AS total_quantity,
ROUND(SUM(o.quantity * p.price), 2) AS total_revenue
FROM orders o
INNER JOIN products p
ON o.product_id = p.product_id
GROUP BY p.category
ORDER BY total_revenue DESC
""").fetchall()
# Return aggregated results
return results
# Execute Query 3 using the SQL version
print("=" * 60)
print("QUERY 3 (SQL VERSION): Revenue by Category")
print("Business Question: Which product categories generate the most revenue?")
print("=" * 60)
# Call the SQL aggregation function
results_sql = query3_revenue_by_category_sql(DB_PATH)
# Print formatted output header
print(f"\n{'Category':<20} {'Total Orders':<15} {'Total Qty':<12} {'Total Revenue'}")
# Display aggregated results for each category
for row in results_sql:
print(f"{row[0]:<20} {row[1]:<15} {row[2]:<12} ${row[3]}")
"""## **Query 3 SQL Result Interpretation**
The SQL analysis shows that the **Electronics** category generates the highest revenue by a significant margin, driven by both a larger number of orders and higher total quantities sold. Accessories and Office Supplies contribute substantially less revenue in comparison.
This result highlights Electronics as the primary revenue driver in the product portfolio and suggests that strategic focus on this category could have the greatest impact on overall sales performance.
## **Query 3.2: Revenue by Category — Python Version**
This implementation retrieves detailed order and product data using a SQL join, then performs all grouping, aggregation, and sorting in Python. Dictionaries and loops are used to compute total orders, total quantity, and total revenue by category.
"""
def query3_revenue_by_category_python(db_path):
"""
Calculate total revenue by product category using Python processing.
Business question:
Which product categories generate the most revenue
This version fetches raw data using SQL joins and performs
all grouping, aggregation, and sorting in Python.
Returns:
A list of tuples containing
category
total number of orders
total quantity sold
total revenue
"""
# Fetch raw order and product data using SQL joins
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
raw_data = cursor.execute("""
SELECT
p.category,
o.quantity,
p.price
FROM orders o
INNER JOIN products p
ON o.product_id = p.product_id
""").fetchall()
# Initialize dictionary to store aggregated statistics by category
category_stats = {}
# Loop through each row and aggregate values in Python
for row in raw_data:
category = row[0]
quantity = row[1]
price = row[2]
# Compute revenue for the current row
revenue = quantity * price
# Initialize category entry if it does not exist
if category not in category_stats:
category_stats[category] = {
"total_orders": 0,
"total_quantity": 0,
"total_revenue": 0
}
# Update aggregation values
category_stats[category]["total_orders"] += 1
category_stats[category]["total_quantity"] += quantity
category_stats[category]["total_revenue"] += revenue
# Convert aggregated dictionary into a list of tuples
results = []
for category, stats in category_stats.items():
results.append((
category,
stats["total_orders"],
stats["total_quantity"],
round(stats["total_revenue"], 2)
))
# Sort results by total revenue in descending order
results = sorted(results, key=lambda x: x[3], reverse=True)
return results
# Execute Query 3 using the Python version
print("=" * 60)
print("QUERY 3 (PYTHON VERSION): Revenue by Category")
print("Business Question: Which product categories generate the most revenue?")
print("=" * 60)
# Call the Python aggregation function
results_python = query3_revenue_by_category_python(DB_PATH)
# Print formatted output header
print(f"\n{'Category':<20} {'Total Orders':<15} {'Total Qty':<12} {'Total Revenue'}")
# Display aggregated results for each category
for row in results_python:
print(f"{row[0]:<20} {row[1]:<15} {row[2]:<12} ${row[3]}")
# Confirm that SQL and Python implementations produce identical results
print("\nVerification: SQL and Python results match:", results_sql == results_python)
"""## **Query 3 Python Result Interpretation**
The Python-based aggregation produces the **same results as the SQL version**, confirming that both database-side and application-side processing lead to consistent outcomes.
Electronics remains the highest revenue-generating category, followed by Accessories and Office Supplies. The successful verification demonstrates a correct implementation of grouping, aggregation, and sorting logic in Python using loops and dictionaries.
**Both the SQL and Python implementations produce identical results, confirming the correctness and consistency of the aggregation logic across database-side and application-side processing.**
## **Query 4: Top Customers by Spending (SQL + Python Versions)**
**Business Question:** Who are our most valuable customers?
This analysis identifies customers with the highest total spending by aggregating order values across all purchases. Understanding top customers helps prioritize retention efforts, personalized marketing, and loyalty initiatives.
To demonstrate both database-side and application-side processing, this query is implemented in **two ways**:
1. **SQL Version**
Uses SQL `JOIN`, `GROUP BY`, and aggregation functions to calculate total spending per customer directly in the database.
2. **Python Version**
Retrieves detailed order and product data using SQL joins, then performs grouping, aggregation, and sorting in Python using loops, dictionaries, and built-in functions.
Both implementations are expected to return identical results.
## **Query 4.1: Top Customers by Spending — SQL Version**
This implementation identifies the most valuable customers based on their total spending.
The calculation is performed entirely in SQL using table joins and aggregation functions to sum order revenue for each customer.
"""
def query4_top_customers_sql(db_path, limit=5):
"""
Identify the top customers based on total spending using SQL.
Business question:
Who are our most valuable customers
This version performs all aggregation and sorting in SQL.
Returns:
A list of tuples containing
customer ID
customer name
customer city
total number of orders
total amount spent
"""
# Connect to the SQLite database
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Execute SQL query to calculate total spending per customer
results = cursor.execute("""
SELECT
c.customer_id,
c.name,
c.city,
COUNT(o.order_id) AS total_orders,
ROUND(SUM(o.quantity * p.price), 2) AS total_spent
FROM customers c
INNER JOIN orders o
ON c.customer_id = o.customer_id
INNER JOIN products p
ON o.product_id = p.product_id
GROUP BY c.customer_id, c.name, c.city
ORDER BY total_spent DESC
LIMIT ?
""", (limit,)).fetchall()
# Return ranked customer spending results
return results
# Execute Query 4 using the SQL version
print("=" * 60)
print("QUERY 4 (SQL VERSION): Top Customers by Spending")
print("Business Question: Who are our most valuable customers?")
print("=" * 60)
# Call the SQL function
results_sql = query4_top_customers_sql(DB_PATH, 5)
# Display results in ranked format
print(f"\n{'Rank':<6} {'ID':<5} {'Name':<20} {'City':<15} {'Orders':<10} {'Total Spent'}")
for i, row in enumerate(results_sql, 1):
print(f"{i:<6} {row[0]:<5} {row[1]:<20} {row[2]:<15} {row[3]:<10} ${row[4]}")
"""## **Query 4 SQL Result Interpretation**
The results identify the **top five customers by total spending**, highlighting those who contribute the most revenue to the business. These customers represent high-value segments that are strong candidates for retention strategies, loyalty programs, and personalized offers.
The ranking shows variation across cities, indicating that high-value customers are distributed geographically rather than concentrated in a single location.
## **Query 4.2: Top Customers by Spending — Python Version**
This implementation calculates total customer spending using Python-based aggregation.
Order and product data are retrieved using a SQL join, and all grouping, summation, sorting, and ranking are performed in Python using dictionaries and loops.
"""
def query4_top_customers_python(db_path, limit=5):
"""
Identify the top customers based on total spending using Python.
Business question:
Who are our most valuable customers
This version retrieves raw data using SQL joins and performs
all grouping, aggregation, and sorting in Python.
Returns:
A list of tuples containing
customer ID
customer name
customer city
total number of orders
total amount spent
"""
# Connect to the SQLite database
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Fetch raw customer, order, and product data
raw_data = cursor.execute("""
SELECT
c.customer_id,
c.name,
c.city,
o.quantity,
p.price
FROM customers c
INNER JOIN orders o
ON c.customer_id = o.customer_id
INNER JOIN products p
ON o.product_id = p.product_id
""").fetchall()
# Dictionary to store aggregated spending per customer
customer_stats = {}
# Loop through raw data and aggregate values
for row in raw_data:
customer_id = row[0]
name = row[1]
city = row[2]
quantity = row[3]
price = row[4]
spent = quantity * price
if customer_id not in customer_stats:
customer_stats[customer_id] = {
"name": name,
"city": city,
"total_orders": 0,
"total_spent": 0
}
customer_stats[customer_id]["total_orders"] += 1
customer_stats[customer_id]["total_spent"] += spent
# Convert dictionary to list of tuples
results = []
for customer_id, stats in customer_stats.items():
results.append((
customer_id,
stats["name"],
stats["city"],
stats["total_orders"],
round(stats["total_spent"], 2)
))
# Sort customers by total spending in descending order
results = sorted(results, key=lambda x: x[4], reverse=True)
# Return top N customers
return results[:limit]
# Execute Query 4 using the Python version
print("=" * 60)
print("QUERY 4 (PYTHON VERSION): Top Customers by Spending")
print("Business Question: Who are our most valuable customers?")
print("=" * 60)
# Call the Python function
results_python = query4_top_customers_python(DB_PATH, 5)
# Display ranked customer results
print(f"\n{'Rank':<6} {'ID':<5} {'Name':<20} {'City':<15} {'Orders':<10} {'Total Spent'}")
for i, row in enumerate(results_python, 1):
print(f"{i:<6} {row[0]:<5} {row[1]:<20} {row[2]:<15} {row[3]:<10} ${row[4]}")
# Verify that SQL and Python implementations match
print("\nVerification: SQL and Python results match:", results_sql == results_python)
"""## **Query 4 Python Result Interpretation**
The Python-based analysis produces the **same ranking and spending totals as the SQL version**, confirming that both implementations are consistent and correct.
The results identify a small group of high-value customers who contribute a disproportionately large share of revenue. These customers are strong candidates for targeted retention strategies, loyalty programs, and personalized engagement efforts.
**Both the SQL and Python implementations return identical results, confirming the accuracy and consistency of the customer spending analysis.**
## **Query 5: Monthly Sales Trend (SQL + Python Versions)**
**Business Question:** How are our sales trending over time?
This analysis examines total sales on a monthly basis to identify overall trends, seasonality, and changes in customer purchasing behavior over time.
To demonstrate both database-side and application-side processing, this query is implemented in **two ways**:
1. **SQL Version**
Uses SQL date functions along with `GROUP BY` and aggregation to calculate monthly sales directly in the database.
2. **Python Version**
Retrieves detailed order and product data using a SQL join, then performs date grouping, aggregation, and sorting in Python using loops, dictionaries, and built-in functions.
Both implementations are expected to return identical results.
## **Query 5.1: Monthly Sales Trend — SQL Version**
This implementation analyzes sales performance over time by aggregating order data at a monthly level.
The calculation is performed entirely in SQL using date functions, grouping, and aggregation to identify trends in order volume and revenue.
"""
def query5_monthly_sales_sql(db_path):
"""
Calculate monthly sales trends using SQL.
Business question:
How are our sales trending over time
This version performs all date grouping and aggregation
directly within the SQL query.
Returns:
A list of tuples containing
month
total number of orders
total quantity sold
total revenue
"""
# Connect to the SQLite database
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Execute SQL query to aggregate sales by month
results = cursor.execute("""
SELECT
strftime('%Y-%m', o.order_date) AS month,
COUNT(o.order_id) AS total_orders,
SUM(o.quantity) AS total_quantity,
ROUND(SUM(o.quantity * p.price), 2) AS total_revenue
FROM orders o
INNER JOIN products p
ON o.product_id = p.product_id
GROUP BY strftime('%Y-%m', o.order_date)
ORDER BY month
""").fetchall()
# Return monthly sales results
return results
# Execute Query 5 using the SQL version
print("=" * 60)
print("QUERY 5 (SQL VERSION): Monthly Sales Trend")
print("Business Question: How are our sales trending over time?")
print("=" * 60)
# Call the SQL function
results_sql = query5_monthly_sales_sql(DB_PATH)
# Display results in tabular format
print(f"\n{'Month':<12} {'Orders':<10} {'Quantity':<12} {'Revenue'}")
for row in results_sql:
print(f"{row[0]:<12} {row[1]:<10} {row[2]:<12} ${row[3]}")
"""## **Query 5 SQL Result Interpretation**
The monthly sales data shows a generally upward trend over time, with noticeable increases in revenue during later months. Periodic fluctuations suggest seasonality, while higher order volume and revenue in recent months indicate growing customer demand and business growth.
## **Query 5.2: Monthly Sales Trend — Python Version**
This implementation analyzes monthly sales trends using Python-based aggregation.
Raw order and product data are retrieved using a SQL join, while all date grouping, aggregation, and sorting are performed in Python using dictionaries, loops, and built-in functions.
"""
def query5_monthly_sales_python(db_path):
"""
Calculate monthly sales trends using Python.
Business question:
How are our sales trending over time
This version retrieves raw order and product data using SQL joins
and performs all grouping, aggregation, and sorting in Python.
Returns:
A list of tuples containing
month
total number of orders
total quantity sold
total revenue
"""
# Connect to the SQLite database
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Fetch raw order date, quantity, and price data
raw_data = cursor.execute("""
SELECT
o.order_date,
o.quantity,
p.price
FROM orders o
INNER JOIN products p
ON o.product_id = p.product_id
""").fetchall()
# Dictionary to store aggregated monthly statistics
monthly_stats = {}
# Loop through raw data and aggregate by month
for row in raw_data:
order_date = row[0]
quantity = row[1]
price = row[2]
revenue = quantity * price
# Extract year and month from date string
month = order_date[:7]
if month not in monthly_stats:
monthly_stats[month] = {
"total_orders": 0,
"total_quantity": 0,
"total_revenue": 0
}
monthly_stats[month]["total_orders"] += 1
monthly_stats[month]["total_quantity"] += quantity
monthly_stats[month]["total_revenue"] += revenue
# Convert dictionary to sorted list of tuples
results = []
for month, stats in monthly_stats.items():
results.append((
month,
stats["total_orders"],
stats["total_quantity"],
round(stats["total_revenue"], 2)
))
# Sort results chronologically by month
results = sorted(results, key=lambda x: x[0])
return results
# Execute Query 5 using the Python version
print("=" * 60)
print("QUERY 5 (PYTHON VERSION): Monthly Sales Trend")
print("Business Question: How are our sales trending over time?")
print("=" * 60)
# Call the Python function
results_python = query5_monthly_sales_python(DB_PATH)
# Display results in tabular format
print(f"\n{'Month':<12} {'Orders':<10} {'Quantity':<12} {'Revenue'}")
for row in results_python:
print(f"{row[0]:<12} {row[1]:<10} {row[2]:<12} ${row[3]}")
# Verify SQL and Python results match
print("\nVerification: SQL and Python results match:", results_sql == results_python)
"""## **Query 5 Python Result Interpretation**
The Python-based analysis shows how monthly sales evolve over time by grouping orders at the application level. The results highlight an overall upward trend in revenue, with some month-to-month variability, indicating steady growth and mild seasonal fluctuations in customer demand.
**Both the SQL and Python implementations produce identical monthly sales results, confirming the accuracy and consistency of the trend analysis across database-side and application-side processing.**
**Overall, the results indicate a gradual increase in sales over time with periodic fluctuations, suggesting steady growth alongside mild seasonality in customer purchasing behavior.**
## **Main Function: Run All Queries**
This section executes all five analytical queries in sequence and displays their results in a structured format.
Running all queries together provides a comprehensive overview of customer behavior, product performance, revenue distribution, and sales trends across time.
Together, these analyses offer actionable business insights that support data-driven decision-making in marketing, sales strategy, and customer retention.
"""
def main():
"""
Main function to run all analytical queries together.
This function executes all five queries sequentially and
prints a concise summary of results for each analysis.
"""
print("=" * 70)
print("E-COMMERCE DATA ANALYSIS - ALL QUERIES")
print("=" * 70)
# Run Query 1 to find customers from a specific city
print("\n" + "=" * 70)
print("QUERY 1: Customers by City")
print("=" * 70)
results = query1_customers_by_city(DB_PATH, "Boston")
print(f"Found {len(results)} customers in Boston")
for row in results[:3]:
print(f" {row[0]}: {row[1]} - {row[2]}")
if len(results) > 3:
print(f" ... and {len(results) - 3} more customers")
# Run Query 2 to display order details using joins
print("\n" + "=" * 70)
print("QUERY 2: Order Details")
print("=" * 70)
results = query2_order_details(DB_PATH, 3)
for row in results:
print(f" Order {row[0]}: {row[1]} bought {row[3]} x{row[5]} = ${row[7]}")
# Run Query 3 to analyze revenue by category
print("\n" + "=" * 70)
print("QUERY 3: Revenue by Category")
print("=" * 70)
sql_results = query3_revenue_by_category_sql(DB_PATH)
python_results = query3_revenue_by_category_python(DB_PATH)
for row in sql_results:
print(f" {row[0]}: ${row[3]} revenue")