diff --git a/SQL lab 7.ipynb b/SQL lab 7.ipynb new file mode 100644 index 0000000..9bbc3a8 --- /dev/null +++ b/SQL lab 7.ipynb @@ -0,0 +1,35 @@ +{ + "metadata": { + "kernelspec": { + "name": "python", + "display_name": "Python (Pyodide)", + "language": "python" + }, + "language_info": { + "codemirror_mode": { + "name": "python", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8" + } + }, + "nbformat_minor": 5, + "nbformat": 4, + "cells": [ + { + "id": "6c0a67d3-de8f-4b6a-b51d-9fe737ee5ab3", + "cell_type": "code", + "source": "import pandas as pd\nfrom sqlalchemy import create_engine\nimport getpass\n\npassword = getpass.getpass(\"Enter MySQL password: \")\nuser = \"root\"\nhost = \"localhost\"\ndb = \"sakila\"\n\nconnection_string = f\"mysql+pymysql://{user}:{password}@{host}/{db}\"\nengine = create_engine(connection_string)\n\nwith engine.connecction() as conn:\n print(\"Connection successfully!\")\n\ndef rentals_month(engine, month, year):\n query = f\"\"\"\n SELECT *\n FROM rental\n WHERE MONTH(rental_date) = {month}\n AND YEAR(rental_date) = {year}\n \"\"\"\n df = pd.read_sql(query, engine)\n return df\n\ndef rental_count_month(df, month, year):\n col_name = f\"rentals_{month:02d}_{year}\"\n\n result = (\n df.groupby(\"customer_id\")\n .size()\n .reset_index(name=col_name)\n )\n return result\n\ndef compare_rentals(df1, df2):\n combined = pd.merge(df1, df2, on=\"customer_id\", how=\"outer\")\n combined = combined.fillna(0)\n\n rental_cols = [c for c in combined.columns if c != \"customer_id\"]\n combined[\"difference\"] = combined[rental_cols[0]] - combined[rental_cols[1]]\n\n return combined\n\nmay_df = rentals_month(engine, 5, 2005)\njune_df = rentals_month(engine, 6, 2005)\n\nmay_counts = rental_count_month(may_df, 5, 2005)\njune_counts = rental_count_month(june_df, 6,2005)\n\ncomparison = compare_rentals(may_counts, june_counts)\ncomparison.head()", + "metadata": { + "trusted": true + }, + "outputs": [], + "execution_count": null + } + ] +} \ No newline at end of file