Resource Sharing

Share useful files, links, and learning materials.

[빅데이터개론/1분반] 10/16 SQL 수업 보충설명 자료

빅데이터개론 1분반, 10/16 SQL 수업 중, 아래 코드셀 내용에 대한 보충설명 자료입니다.




import sqlite3 connection = sqlite3.connect(":memory:") connection.execute(""" CREATE TABLE sales ( sale_id INTEGER PRIMARY KEY, product_name TEXT NOT NULL, category TEXT NOT NULL, quantity INTEGER NOT NULL, unit_price INTEGER NOT NULL, month INTEGER NOT NULL ) """) sales_rows = [ ("Mouse", "Accessory", 3, 25, 1), ("Keyboard", "Accessory", 2, 45, 1), ("Monitor", "Display", 1, 180, 2), ("Laptop Stand", "Accessory", 4, 30, 2), ("Tablet", "Device", 2, 220, 3), ] connection.executemany(""" INSERT INTO sales (product_name, category, quantity, unit_price, month) VALUES (?, ?, ?, ?, ?) """, sales_rows) connection.commit() print("Prepared sales:") for row in connection.execute("SELECT * FROM sales ORDER BY sale_id"): print(row)



첫번째 코드셀에서는 다음 정보가 저장된 SQL 데이터 베이스가 생성됩니다.


sale_idproduct_namecategoryquantityunit_pricemonth1MouseAccessory32512KeyboardAccessory24513MonitorDisplay118024Laptop standAccessory43025TabletDevice22203




print("Categories reaching 250 dollars in months 1 and 2:") for row in connection.execute(""" SELECT category, SUM(quantity * unit_price) AS total_revenue FROM sales WHERE month <= ? GROUP BY category HAVING SUM(quantity * unit_price) >= ? ORDER BY total_revenue DESC, category ASC """, (2, 250)): print(row)


두번째 코드셀에서는, 첫번째 코드셀에서 생성된 테이블에 대해,


  • WHERE month <= 2 로부터, 1,2,3,4 행을 선택합니다. 5행은 선택에서 제외됩니다.


  • GROP BY category 와 HAVING SUM(quantity * unit_price) >= 250로부터, 선택된 행을 category 값으로 그룹핑 합니다. 이 때, quantity 열과 unitprice 열을 요소별 곱한 새로운 피처의 값을 구하고, 이를 각 그룹별로 누적합한 값이 250 이상인 그룹만 남깁니다.
  • 이 때, Accessory 그룹은 3*25 + 2*45 + 4*30 = 285 값을 가지므로 남겨집니다.
  • 이 때, Display 그룹은 1*180 = 180 값을 가지므로 제외됩니다.


  • 이후 SELECT category, SUM(quantity * unit_price) AS total_revenue 로부터, 새로운 피쳐를 total_revenue라 하고, 각 그룹별로 category와 total_revenue만 선택합니다.


categorytotal_revenueAccessory3*25 + 2*45 + 4*30 = 285


  • 이후 total_revenue에 대해서 내림차순으로 정렬하고, 동점 항목에 대해서는 categoryt에 대해 오름차순으로 정렬합니다.


  • 마지막으로 최종 결과를 출력하면 다음의 결과를 확인하게 됩니다.

  (Accessory, 285)

No replies yet. Start the conversation.

Login

A six-digit login code will be sent by email.

Do not use this option on a shared or public device.

Sign up

필수 개인정보 수집·이용 안내 / Required Privacy Notice