instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many TV shows were produced in each country?
CREATE TABLE TV_Shows (id INT,title VARCHAR(255),country VARCHAR(255)); INSERT INTO TV_Shows (id,title,country) VALUES (1,'TV Show 1','USA'),(2,'TV Show 2','UK'),(3,'TV Show 3','Canada'),(4,'TV Show 4','Australia');
SELECT country, COUNT(*) FROM TV_Shows GROUP BY country;
What is the average number of hours spent on training for each employee in the 'HR' department?
CREATE TABLE Employee_Training (Employee_ID INT,Employee_Name VARCHAR(50),Department VARCHAR(50),Training_Type VARCHAR(50),Hours_Spent DECIMAL(5,2)); INSERT INTO Employee_Training (Employee_ID,Employee_Name,Department,Training_Type,Hours_Spent) VALUES (2,'Jane Doe','HR','Diversity and Inclusion',6.00),(2,'Jane Doe','HR','Leadership',5.00),(3,'Alberto Rodriguez','Finance','Technical Skills',8.00),(5,'Mei Liu','HR','Diversity and Inclusion',7.00),(5,'Mei Liu','HR','Leadership',4.00);
SELECT Department, AVG(Hours_Spent) FROM Employee_Training GROUP BY Department;
What is the average safety stock level for each chemical category, for chemical manufacturing in the Asia Pacific region?
CREATE TABLE chemicals (id INT,name VARCHAR(255),category VARCHAR(255),safety_stock_level FLOAT,region VARCHAR(255));
SELECT category, AVG(safety_stock_level) as avg_level FROM chemicals WHERE region = 'Asia Pacific' GROUP BY category;
What is the maximum number of military projects undertaken by GHI Inc in the Middle East in a single year?
CREATE TABLE Defense_Project_Timelines (contractor VARCHAR(255),region VARCHAR(255),project VARCHAR(255),start_date DATE,end_date DATE);
SELECT MAX(DATEDIFF(end_date, start_date)) FROM Defense_Project_Timelines WHERE contractor = 'GHI Inc' AND region = 'Middle East';
What is the average number of students in each 'school_district'?
CREATE TABLE schools (school_id INT,school_name VARCHAR(25),school_district VARCHAR(25)); INSERT INTO schools (school_id,school_name,school_district) VALUES (1,'Oak Grove High School','Central Riverland'),(2,'Pine Tree Elementary School','Eastern Shorelines'),(3,'Riverbend Middle School','Central Riverland'),(4,'Willow Creek High School','Western Hills');
SELECT school_district, AVG(COUNT(*)) FROM schools GROUP BY school_district;
What is the total number of crimes committed in each district, sorted by the number of crimes in descending order?
CREATE TABLE Districts (DId INT,Name VARCHAR(50)); CREATE TABLE Crimes (CrimeId INT,DId INT,Date DATE);
SELECT D.Name, COUNT(C.CrimeId) AS TotalCrimes FROM Districts D LEFT JOIN Crimes C ON D.DId = C.DId GROUP BY D.Name ORDER BY TotalCrimes DESC;
Show cricket matches with a tie score
CREATE TABLE cricket_matches (team1 VARCHAR(255),team2 VARCHAR(255),score1 INT,score2 INT);
SELECT * FROM cricket_matches WHERE score1 = score2;
What is the average ocean acidity level per year in the Arctic region?
CREATE TABLE ocean_acidity (region VARCHAR(255),year INT,acidity FLOAT); INSERT INTO ocean_acidity (region,year,acidity) VALUES ('Arctic',2010,8.1),('Arctic',2011,8.15),('Arctic',2012,8.2),('Atlantic',2010,8.05),('Atlantic',2011,8.08),('Atlantic',2012,8.1);
SELECT region, AVG(acidity) FROM ocean_acidity WHERE region = 'Arctic' GROUP BY region;
List all employees and their departments from the "finance" schema
CREATE TABLE finance.employees (id INT,name VARCHAR(50),department VARCHAR(50)); INSERT INTO finance.employees (id,name,department) VALUES (1,'Alice Johnson','Accounting'); INSERT INTO finance.employees (id,name,department) VALUES (2,'Bob Brown','Finance');
SELECT * FROM finance.employees;
What is the average age of users who engaged with investigative journalism pieces about immigration?
CREATE TABLE users (id INT,name TEXT,age INT,gender TEXT); INSERT INTO users (id,name,age,gender) VALUES (1,'Alicia Garcia',38,'female'),(2,'James Kim',42,'male'); CREATE TABLE articles (id INT,title TEXT,category TEXT,publish_date DATE); INSERT INTO articles (id,title,category,publish_date) VALUES (1,'Uncovering Exploitation','investigative_journalism','immigration','2022-06-01'),(2,'Following the Money Trail','investigative_journalism','politics','2022-06-05'); CREATE TABLE engagement (user_id INT,article_id INT); INSERT INTO engagement (user_id,article_id) VALUES (1,1),(2,1);
SELECT AVG(age) FROM users JOIN engagement ON users.id = engagement.user_id JOIN articles ON engagement.article_id = articles.id WHERE category = 'investigative_journalism' AND articles.category = 'immigration';
Delete fans who have not purchased tickets in the last 24 months from the Fans table.
CREATE TABLE Fans (FanID INT,FanName VARCHAR(100),Country VARCHAR(100),LastPurchaseDate DATE);
DELETE FROM Fans WHERE FanID IN (SELECT f.FanID FROM Fans f WHERE f.LastPurchaseDate < DATE_SUB(CURRENT_DATE, INTERVAL 24 MONTH));
Rank community health workers by their mental health scores within each state, and return the top 3.
CREATE TABLE community_health_workers (worker_id INT,worker_name TEXT,state TEXT,mental_health_score INT); INSERT INTO community_health_workers (worker_id,worker_name,state,mental_health_score) VALUES (1,'John Doe','NY',75),(2,'Jane Smith','CA',82),(3,'Alice Johnson','TX',68);
SELECT worker_id, worker_name, state, mental_health_score, RANK() OVER (PARTITION BY state ORDER BY mental_health_score DESC) as rank FROM community_health_workers WHERE rank <= 3;
Which health equity metrics are not present in California?
CREATE TABLE health_equity_metrics (metric_id INT,metric_name VARCHAR(50),state VARCHAR(20)); INSERT INTO health_equity_metrics (metric_id,metric_name,state) VALUES (1,'Metric 1','New York'),(2,'Metric 2','Texas'),(3,'Metric 3','New York'),(4,'Metric 4','Florida');
SELECT metric_name FROM health_equity_metrics WHERE state != 'California'
What is the average number of streams per day for 'Bad Guy' by Billie Eilish on Spotify?
CREATE TABLE Streams (StreamID INT,Song TEXT,Platform TEXT,Date DATE,Streams INT); INSERT INTO Streams (StreamID,Song,Platform,Date,Streams) VALUES (1,'Bad Guy','Spotify','2022-01-01',10000),(2,'Bad Guy','Spotify','2022-01-02',12000);
SELECT AVG(Streams/2) FROM Streams WHERE Song = 'Bad Guy' AND Platform = 'Spotify';
What is the total number of concert tickets sold in each city for artists from the Pop genre?
CREATE TABLE Concerts (id INT,city VARCHAR(255),tickets_sold INT); CREATE TABLE Artists (id INT,genre VARCHAR(255));
SELECT city, SUM(tickets_sold) as total_tickets_sold FROM Concerts INNER JOIN Artists ON Concerts.id = Artists.id WHERE genre = 'Pop' GROUP BY city;
Which country had the highest gas production increase between Q3 and Q4 2021?
CREATE TABLE country (country_id INT,country_name TEXT,gas_production_q3_2021 FLOAT,gas_production_q4_2021 FLOAT); INSERT INTO country (country_id,country_name,gas_production_q3_2021,gas_production_q4_2021) VALUES (1,'Canada',12000,12500),(2,'USA',16000,16800),(3,'Mexico',18000,18500);
SELECT country_name, (gas_production_q4_2021 - gas_production_q3_2021) as gas_production_increase FROM country ORDER BY gas_production_increase DESC;
Which health equity metrics have been collected for patients in the 'underserved' region?
CREATE TABLE HealthEquityMetrics (Patient_ID INT,Metric_Name VARCHAR(50),Metric_Value FLOAT,Region VARCHAR(50)); INSERT INTO HealthEquityMetrics (Patient_ID,Metric_Name,Metric_Value,Region) VALUES (1,'Income',25000,'underserved'); INSERT INTO HealthEquityMetrics (Patient_ID,Metric_Name,Metric_Value,Region) VALUES (2,'Education',12,'underserved');
SELECT Metric_Name, Metric_Value FROM HealthEquityMetrics WHERE Region = 'underserved';
What is the maximum wave height recorded in the Southern Ocean?
CREATE TABLE wave_height (location VARCHAR(255),height FLOAT); INSERT INTO wave_height (location,height) VALUES ('Southern Ocean',12.5),('North Sea',9.2);
SELECT MAX(height) FROM wave_height WHERE location = 'Southern Ocean';
What is the most common infectious disease in Asia?
CREATE TABLE Diseases (Disease TEXT,Continent TEXT,NumberOfCases INTEGER); INSERT INTO Diseases (Disease,Continent,NumberOfCases) VALUES ('Tuberculosis','Asia',9000000),('Malaria','Africa',20000000),('HIV','Europe',500000);
SELECT Disease FROM Diseases WHERE Continent = 'Asia' AND NumberOfCases = (SELECT MAX(NumberOfCases) FROM Diseases WHERE Continent = 'Asia');
How many cases were handled by attorneys who have more than 10 years of experience?
CREATE TABLE Attorneys (AttorneyID INT,LastName VARCHAR(255),YearsOfExperience INT); INSERT INTO Attorneys (AttorneyID,LastName,YearsOfExperience) VALUES (1,'Patel',15),(2,'Singh',12),(3,'Kim',8); CREATE TABLE Cases (CaseID INT,AttorneyID INT);
SELECT COUNT(*) FROM Cases INNER JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE Attorneys.YearsOfExperience > 10;
What is the total investment amount for organizations based in India with a positive ESG score?
CREATE TABLE organization (id INT PRIMARY KEY,name VARCHAR(255),sector VARCHAR(255),country VARCHAR(255)); CREATE TABLE investment (id INT PRIMARY KEY,organization_id INT,amount DECIMAL(10,2),date DATE,esg_score DECIMAL(3,2));
SELECT SUM(investment.amount) FROM investment INNER JOIN organization ON investment.organization_id = organization.id WHERE organization.country = 'India' AND investment.esg_score > 0;
Find the number of users who registered for 'Puzzle' games before making a transaction in the same genre.
CREATE TABLE Registrations (RegistrationID INT,UserID INT,RegistrationDate DATETIME,Game VARCHAR(50)); CREATE TABLE Transactions (TransactionID INT,UserID INT,TransactionDate DATETIME,TransactionValue DECIMAL(10,2),Game VARCHAR(50)); INSERT INTO Registrations (RegistrationID,UserID,RegistrationDate,Game) VALUES (1,1,'2022-02-01','Puzzle'),(2,2,'2022-03-01','Puzzle'); INSERT INTO Transactions (TransactionID,UserID,TransactionDate,TransactionValue,Game) VALUES (1,1,'2022-02-15',25.00,'Puzzle');
SELECT r.UserID, r.RegistrationDate, r.Game FROM Registrations r LEFT JOIN Transactions t ON r.UserID = t.UserID AND r.Game = t.Game WHERE r.Game = 'Puzzle' AND t.TransactionID IS NULL;
Display the usernames of users who have posted about traveling in the past month and have more than 5,000 followers, sorted by the number of followers in ascending order.
CREATE TABLE users (user_id INT,user_name VARCHAR(50),join_date DATE,follower_count INT);CREATE TABLE posts (post_id INT,user_id INT,post_content TEXT,post_date DATE);INSERT INTO users (user_id,user_name,join_date,follower_count) VALUES (1,'user1','2021-01-01',15000),(2,'user2','2021-02-01',12000),(3,'user3','2021-03-01',5000);
SELECT u.user_name FROM users u JOIN posts p ON u.user_id = p.user_id WHERE p.post_content LIKE '%travel%' AND p.post_date >= DATEADD(month, -1, GETDATE()) AND u.follower_count > 5000 ORDER BY u.follower_count ASC;
Find chemical manufacturers who have not updated their safety protocols in the past year.
CREATE TABLE chemical_manufacturers (manufacturer_id INT,name VARCHAR(255),last_updated_safety DATE); INSERT INTO chemical_manufacturers (manufacturer_id,name,last_updated_safety) VALUES (1,'ManufacturerA','2021-01-15'),(2,'ManufacturerB','2021-02-10'),(3,'ManufacturerC','2021-03-01');
SELECT name FROM chemical_manufacturers WHERE last_updated_safety BETWEEN DATEADD(year, -1, GETDATE()) AND GETDATE();
What is the percentage of days in the last month when each customer had data usage, and the total data usage in GB for each customer on those days?
CREATE TABLE daily_usage (customer_id INT,date DATE,data_usage FLOAT); INSERT INTO daily_usage VALUES (1,'2022-06-01',5),(1,'2022-06-02',7);
SELECT customer_id, COUNT(*)*100.0/DAY(DATEADD(month, -1, GETDATE())) as days_with_data_usage_percentage, SUM(data_usage)/1024/1024/1024 as total_data_usage_gb FROM daily_usage WHERE date >= DATEADD(month, -1, GETDATE()) GROUP BY customer_id;
What is the total transaction amount by customer and product category?
CREATE TABLE customers (id INT,name VARCHAR(50)); INSERT INTO customers (id,name) VALUES (1,'John Doe'); INSERT INTO customers (id,name) VALUES (2,'Jane Smith'); INSERT INTO customers (id,name) VALUES (3,'Jim Brown'); CREATE TABLE transactions (id INT,customer_id INT,product_category VARCHAR(50),amount DECIMAL(10,2)); INSERT INTO transactions (id,customer_id,product_category,amount) VALUES (1,1,'investment',500.00); INSERT INTO transactions (id,customer_id,product_category,amount) VALUES (2,1,'investment',200.00); INSERT INTO transactions (id,customer_id,product_category,amount) VALUES (3,2,'risk_management',100.00); INSERT INTO transactions (id,customer_id,product_category,amount) VALUES (4,3,'compliance',750.00); CREATE TABLE product_categories (id INT,category VARCHAR(50)); INSERT INTO product_categories (id,category) VALUES (1,'investment'); INSERT INTO product_categories (id,category) VALUES (2,'risk_management'); INSERT INTO product_categories (id,category) VALUES (3,'compliance');
SELECT c.name, p.category, SUM(t.amount) as total_amount FROM customers c INNER JOIN transactions t ON c.id = t.customer_id INNER JOIN product_categories p ON t.product_category = p.category GROUP BY c.name, p.category;
List all species and their average weight, grouped by habitat
CREATE TABLE species (id INT,name VARCHAR(255),weight INT);CREATE TABLE animals (id INT,species_id INT,habitat_id INT);CREATE TABLE habitats (id INT,name VARCHAR(255)); INSERT INTO species (id,name,weight) VALUES (1,'Tiger',150),(2,'Elephant',6000),(3,'Giraffe',1200),(4,'Zebra',350),(5,'Lion',200); INSERT INTO animals (id,species_id,habitat_id) VALUES (1,1,1),(2,2,2),(3,3,1),(4,4,3),(5,5,2); INSERT INTO habitats (id,name) VALUES (1,'Savannah'),(2,'Jungle'),(3,'Mountains');
SELECT h.name AS habitat_name, AVG(s.weight) AS avg_weight FROM species s INNER JOIN animals a ON s.id = a.species_id INNER JOIN habitats h ON a.habitat_id = h.id GROUP BY h.name;
What is the total number of police officers in the state of California?
CREATE TABLE police_officers (id INT,state VARCHAR(255),number_of_officers INT); INSERT INTO police_officers (id,state,number_of_officers) VALUES (1,'California',50000),(2,'New_York',35000);
SELECT SUM(number_of_officers) FROM police_officers WHERE state = 'California';
What is the average attendance at home games for each team this season?
CREATE TABLE games (team TEXT,location TEXT,attendeance INT); INSERT INTO games (team,location,attendeance) VALUES ('Team A','Home',15000),('Team B','Home',12000);
SELECT team, AVG(attendeance) OVER (PARTITION BY team) as avg_attendance FROM games WHERE location = 'Home';
How many properties are co-owned by people from different racial backgrounds?
CREATE TABLE Property_CoOwners (CoOwner1_ID INT,CoOwner1_Race VARCHAR(20),CoOwner2_ID INT,CoOwner2_Race VARCHAR(20)); INSERT INTO Property_CoOwners (CoOwner1_ID,CoOwner1_Race,CoOwner2_ID,CoOwner2_Race) VALUES (1,'White',2,'Black'),(3,'Asian',4,'Hispanic'),(5,'White',6,'Asian');
SELECT COUNT(*) FROM Property_CoOwners WHERE CoOwner1_Race != CoOwner2_Race;
Which products have the highest percentage of organic ingredients?
CREATE TABLE Products (Product_ID INT PRIMARY KEY,Product_Name TEXT,Brand_ID INT,Organic_Percentage FLOAT); INSERT INTO Products (Product_ID,Product_Name,Brand_ID,Organic_Percentage) VALUES (1,'Gentle Cleanser',1,95.0),(2,'Nourishing Moisturizer',1,70.0),(3,'Revitalizing Serum',2,98.0),(4,'Soothing Toner',2,85.0),(5,'Hydrating Mask',3,50.0),(6,'Balancing Mist',3,100.0);
SELECT Product_Name, Organic_Percentage FROM Products ORDER BY Organic_Percentage DESC;
How many construction workers were employed in Texas in 2019 and 2020?
CREATE TABLE employment_data (state VARCHAR(255),employees INT,year INT); INSERT INTO employment_data (state,employees,year) VALUES ('Texas',500000,2019),('Texas',550000,2020);
SELECT year, SUM(employees) FROM employment_data WHERE state = 'Texas' GROUP BY year;
What is the total water savings for each city in Florida on March 5, 2022 with savings greater than 100?
CREATE TABLE WaterConservation (Id INT PRIMARY KEY,City VARCHAR(255),Savings FLOAT,Date DATE); INSERT INTO WaterConservation (Id,City,Savings,Date) VALUES (1,'Miami',100,'2022-03-05'); INSERT INTO WaterConservation (Id,City,Savings,Date) VALUES (2,'Tampa',120,'2022-03-05'); INSERT INTO WaterConservation (Id,City,Savings,Date) VALUES (3,'Orlando',150,'2022-03-05');
SELECT City, SUM(Savings) FROM WaterConservation WHERE Date = '2022-03-05' AND City IN ('Miami', 'Tampa', 'Orlando') GROUP BY City HAVING SUM(Savings) > 100;
What is the total oil production for each country in 2020?
CREATE TABLE production_figures (year INT,country VARCHAR(50),oil_production_mbbl INT);
SELECT country, SUM(oil_production_mbbl) FROM production_figures WHERE year = 2020 GROUP BY country;
What is the maximum valuation for companies founded by veterans, in each industry category?
CREATE TABLE company (id INT,name TEXT,founder TEXT,industry TEXT,valuation INT); INSERT INTO company (id,name,founder,industry,valuation) VALUES (1,'Acme Inc','Veteran','Tech',5000000);
SELECT industry, MAX(valuation) FROM company WHERE founder LIKE '%Veteran%' GROUP BY industry;
List all campaigns in New York that started after 2018-01-01.
CREATE TABLE campaigns (campaign_id INT,name TEXT,start_date DATE,location TEXT); INSERT INTO campaigns (campaign_id,name,start_date,location) VALUES (1,'End Stigma','2017-12-01','New York'); INSERT INTO campaigns (campaign_id,name,start_date,location) VALUES (2,'Mental Health Matters','2019-06-01','California');
SELECT name, start_date FROM campaigns WHERE location = 'New York' AND start_date > '2018-01-01';
What is the average production rate for wells in the North Sea?
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),location VARCHAR(50),production_rate FLOAT); INSERT INTO wells (well_id,well_name,location,production_rate) VALUES (1,'Well A','North Sea',1000),(2,'Well B','North Sea',1500),(3,'Well C','Gulf of Mexico',2000);
SELECT AVG(production_rate) FROM wells WHERE location = 'North Sea';
Which companies have more than 10 non-compliant records?
CREATE TABLE LawCompliance (company TEXT,violation_status TEXT,violation_date DATE); INSERT INTO LawCompliance (company,violation_status,violation_date) VALUES ('Oceanic Inc','Non-compliant','2021-12-15');
SELECT company, COUNT(*) FROM LawCompliance WHERE violation_status = 'Non-compliant' GROUP BY company HAVING COUNT(*) > 10;
How many products have safety issues reported in the past year?
CREATE TABLE safety_reports (report_id INT,product_id INT,report_date DATE); INSERT INTO safety_reports (report_id,product_id,report_date) VALUES (1,1,'2022-01-01'),(2,3,'2021-12-31'),(3,2,'2020-01-01');
SELECT COUNT(*) FROM safety_reports WHERE report_date >= DATEADD(year, -1, GETDATE());
Find the total number of concerts performed by artists from the United States.
CREATE TABLE artists (id INT,name TEXT,country TEXT); INSERT INTO artists (id,name,country) VALUES (1,'Taylor Swift','United States');
SELECT COUNT(*) FROM artists WHERE country = 'United States' AND id IN (SELECT artist_id FROM concerts);
What is the total amount of climate finance invested in renewable energy projects by countries in the Asia Pacific region, grouped by year?
CREATE TABLE finance (year INT,region VARCHAR(255),project_type VARCHAR(255),amount INT); INSERT INTO finance (year,region,project_type,amount) VALUES (2015,'Asia Pacific','Renewable Energy',1000000); INSERT INTO finance (year,region,project_type,amount) VALUES (2016,'Asia Pacific','Renewable Energy',1500000);
SELECT year, SUM(amount) FROM finance WHERE project_type = 'Renewable Energy' AND region = 'Asia Pacific' GROUP BY year;
What are the product names and their respective hazard categories from the product_hazard table, excluding products with the hazard category 'Flammable'?
CREATE TABLE product_hazard (product_name VARCHAR(255),hazard_category VARCHAR(255)); INSERT INTO product_hazard (product_name,hazard_category) VALUES ('ProductA','Flammable'),('ProductB','Corrosive'),('ProductC','Toxic');
SELECT product_name, hazard_category FROM product_hazard WHERE hazard_category != 'Flammable';
Insert a new record of an OTA booking made through a desktop device in the LATAM region in Q4 2022.
CREATE TABLE ota_bookings (booking_id INT,hotel_id INT,booking_date DATE,booking_source TEXT,region TEXT);
INSERT INTO ota_bookings (booking_id, hotel_id, booking_date, booking_source, region) VALUES (12345, 67890, '2022-10-15', 'Desktop', 'LATAM');
What was the total number of travel advisories issued for India in 2019?
CREATE TABLE Advisories (id INT,country TEXT,year INT,advisories INT); INSERT INTO Advisories (id,country,year,advisories) VALUES (1,'India',2017,50),(2,'India',2018,60),(3,'India',2019,70),(4,'India',2020,80);
SELECT SUM(advisories) FROM Advisories WHERE country = 'India' AND year = 2019;
How many fishing vessels are registered in the North Pacific fishery?
CREATE TABLE fishing_vessels (vessel_name VARCHAR(255),fishery VARCHAR(255)); INSERT INTO fishing_vessels (vessel_name,fishery) VALUES ('Sea Serpent','North Pacific'),('Fish Hawk','North Pacific');
SELECT COUNT(*) FROM fishing_vessels WHERE fishery = 'North Pacific';
What are the names and budgets of all programs in the 'Transportation' sector?
CREATE TABLE Program (id INT,name VARCHAR(50),budget FLOAT,agency_id INT,FOREIGN KEY (agency_id) REFERENCES Agency(id)); INSERT INTO Program (id,name,budget,agency_id) VALUES (3,'Public Transportation',5670000,3); INSERT INTO Program (id,name,budget,agency_id) VALUES (4,'Road Infrastructure',9800000,4);
SELECT Program.name, Program.budget FROM Program INNER JOIN Agency ON Program.agency_id = Agency.id WHERE Agency.sector = 'Transportation';
What is the latest date each department submitted a report?
CREATE TABLE DepartmentReports (department VARCHAR(50),report_date DATE); INSERT INTO DepartmentReports (department,report_date) VALUES ('Health','2022-02-01'),('Education','2022-03-01'),('Transportation','2022-01-15'),('Health','2022-02-15');
SELECT department, MAX(report_date) AS latest_date FROM DepartmentReports GROUP BY department;
What is the total number of public schools in the city of Los Angeles?
CREATE TABLE public_schools (name VARCHAR(255),city VARCHAR(255),state VARCHAR(255),type VARCHAR(255)); INSERT INTO public_schools (name,city,state,type) VALUES ('John Adams Middle School','Los Angeles','CA','Public'); INSERT INTO public_schools (name,city,state,type) VALUES ('George Washington Middle School','Los Angeles','CA','Public');
SELECT COUNT(*) FROM public_schools WHERE city = 'Los Angeles' AND state = 'CA' AND type = 'Public';
What is the number of hospitals and the number of beds per hospital per state, ordered by the number of beds per hospital in descending order?
CREATE TABLE hospitals (state varchar(2),hospital_name varchar(25),num_beds int); INSERT INTO hospitals (state,hospital_name,num_beds) VALUES ('NY','NY Presbyterian',2001),('CA','UCLA Medical',1012),('TX','MD Anderson',1543),('FL','Mayo Clinic FL',1209);
SELECT state, hospital_name, AVG(num_beds) as avg_beds_per_hospital FROM hospitals GROUP BY state, hospital_name ORDER BY avg_beds_per_hospital DESC;
What is the total number of mental health parity violations in each state for the last 2 years, excluding the month of August?
CREATE TABLE MentalHealthParityViolations (ViolationID INT,State VARCHAR(255),ViolationDate DATE); INSERT INTO MentalHealthParityViolations (ViolationID,State,ViolationDate) VALUES (1,'California','2019-04-01'); INSERT INTO MentalHealthParityViolations (ViolationID,State,ViolationDate) VALUES (2,'Texas','2020-01-15'); INSERT INTO MentalHealthParityViolations (ViolationID,State,ViolationDate) VALUES (3,'California','2021-03-05');
SELECT State, SUM(CASE WHEN EXTRACT(MONTH FROM ViolationDate) IN (9,10,11,12,1,2,3,4,5,6,7,12) THEN 1 ELSE 0 END) as NumberOfViolations FROM MentalHealthParityViolations WHERE ViolationDate >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) GROUP BY State;
How many cases were opened in the last 3 months?
CREATE TABLE cases (id INT,opened_at TIMESTAMP); INSERT INTO cases (id,opened_at) VALUES (1,'2022-01-01 10:00:00'),(2,'2022-02-01 12:00:00'),(3,'2021-11-01 09:00:00');
SELECT COUNT(*) FROM cases WHERE opened_at >= NOW() - INTERVAL '3 months';
Add a new menu item 'Impossible Burger' to the 'Vegan' category with a price of $12.99
CREATE TABLE menu_items (menu_id INT PRIMARY KEY,item_name VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2),last_ordered TIMESTAMP);
INSERT INTO menu_items (menu_id, item_name, category, price, last_ordered) VALUES (NULL, 'Impossible Burger', 'Vegan', 12.99, NOW());
What is the average number of accommodations provided per region, for each accommodation type?
CREATE TABLE Accommodations (ID INT PRIMARY KEY,Region VARCHAR(50),AccommodationType VARCHAR(50),Quantity INT); INSERT INTO Accommodations (ID,Region,AccommodationType,Quantity) VALUES (1,'North America','Sign Language Interpretation',300),(2,'North America','Wheelchair Ramp',250),(3,'South America','Assistive Listening Devices',150),(4,'Asia','Mobility Assistance',200),(5,'Europe','Sign Language Interpretation',400),(6,'Africa','Wheelchair Ramp',100);
SELECT Region, AccommodationType, AVG(Quantity) as Average FROM Accommodations GROUP BY Region, AccommodationType;
Find the number of donors who have made donations in each quarter of the current year.
CREATE TABLE donor (don_id INT,donor_name VARCHAR(255)); CREATE TABLE donation (don_id INT,donor_id INT,donation_date DATE);
SELECT EXTRACT(QUARTER FROM donation_date) AS quarter, COUNT(DISTINCT donor_id) AS num_donors FROM donation WHERE EXTRACT(YEAR FROM donation_date) = EXTRACT(YEAR FROM CURRENT_DATE) GROUP BY quarter;
What is the maximum response time for emergency incidents in the city of New York, categorized by incident type?
CREATE TABLE emergency_responses (id INT,incident_id INT,response_time INT); CREATE TABLE emergency_incidents (id INT,incident_type VARCHAR(255),report_date DATE); INSERT INTO emergency_incidents (id,incident_type,report_date) VALUES (1,'Medical Emergency','2022-01-01'),(2,'Fire','2022-01-02'); INSERT INTO emergency_responses (id,incident_id,response_time) VALUES (1,1,10),(2,1,12),(3,2,20);
SELECT incident_type, MAX(response_time) FROM emergency_responses JOIN emergency_incidents ON emergency_responses.incident_id = emergency_incidents.id GROUP BY incident_type;
What is the sum of transportation emissions for all products in the Low_Transportation_Emissions view?
CREATE VIEW Low_Transportation_Emissions AS SELECT product_id,product_name,transportation_emissions FROM Products WHERE transportation_emissions < 5; INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions,labor_conditions_score,environmental_impact_score) VALUES (901,'Sunglasses',3,6,1,7,8); INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions,labor_conditions_score,environmental_impact_score) VALUES (902,'Keychain',2,4,0,8,7); INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions,labor_conditions_score,environmental_impact_score) VALUES (903,'Bracelet',1,3,0,9,6);
SELECT SUM(transportation_emissions) FROM Low_Transportation_Emissions;
How many fans identify as female or non-binary for each team in the NBA?
CREATE TABLE teams (team_id INT,team_name VARCHAR(50)); INSERT INTO teams (team_id,team_name) VALUES (1,'Cavaliers'),(2,'Knicks'),(3,'Sixers'); CREATE TABLE fans (fan_id INT,team_id INT,gender VARCHAR(50)); INSERT INTO fans (fan_id,team_id,gender) VALUES (1,1,'Female'),(2,1,'Non-binary'),(3,2,'Female'),(4,2,'Male'),(5,3,'Prefer not to say');
SELECT t.team_name, COUNT(CASE WHEN f.gender IN ('Female', 'Non-binary') THEN 1 END) as fan_count FROM teams t JOIN fans f ON t.team_id = f.team_id GROUP BY t.team_name;
Show the percentage of factories with a high labor satisfaction score
CREATE TABLE factory_labor_scores (factory_id INT,labor_satisfaction_score INT);
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM factory_labor_scores) as high_labor_satisfaction_score_percentage FROM factory_labor_scores WHERE labor_satisfaction_score >= 8;
Determine the daily average distance for freight shipped to 'Berlin'.
CREATE TABLE Freight (id INT PRIMARY KEY,shipment_id INT,origin VARCHAR(50),destination VARCHAR(50),distance INT,cost FLOAT); INSERT INTO Freight (id,shipment_id,origin,destination,distance,cost) VALUES (13,7,'Paris','Berlin',1200,5600.2),(14,8,'London','Berlin',1000,4800.5),(15,9,'Warsaw','Berlin',500,2400.0),(16,10,'Rome','Berlin',1300,6200.3),(17,11,'Brussels','Berlin',800,3600.0),(18,12,'Madrid','Berlin',1800,8100.0);
SELECT AVG(distance) FROM Freight WHERE destination = 'Berlin' GROUP BY destination HAVING COUNT(*) > 1;
What is the maximum packaging weight for products in the Packaging_Weights view?
CREATE VIEW Packaging_Weights AS SELECT product_id,product_name,packaging_weight FROM Products; INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions,packaging_weight) VALUES (701,'Book',1,2,1,0.3); INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions,packaging_weight) VALUES (702,'Water Bottle',2,3,1,0.5); INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions,packaging_weight) VALUES (703,'Lunch Box',3,4,2,0.8);
SELECT MAX(packaging_weight) FROM Packaging_Weights;
Count the number of crimes reported in each district in the "CrimeData" table, where the crime type is 'Theft'.
CREATE TABLE CrimeData (id INT,district INT,crime_type VARCHAR(50),reported_date DATE); INSERT INTO CrimeData (id,district,crime_type,reported_date) VALUES (1,1,'Theft','2022-01-01'),(2,2,'Burglary','2022-01-02'),(3,1,'Vandalism','2022-01-03'),(4,3,'Theft','2022-01-04'),(5,2,'Theft','2022-01-05'),(6,3,'Theft','2022-01-06');
SELECT district, COUNT(*) as num_crimes FROM CrimeData WHERE crime_type = 'Theft' GROUP BY district;
What is the total number of technology for social good projects in each region?
CREATE TABLE Social_Good (region VARCHAR(50),projects INT); INSERT INTO Social_Good (region,projects) VALUES ('Asia',1000),('Africa',700),('Europe',1500),('South America',800);
SELECT region, SUM(projects) FROM Social_Good GROUP BY region;
Display the names and production quantities of all wells that were active at any point during 2022, sorted by production quantity.
CREATE TABLE wells (well_id INT,well_name TEXT,production_qty INT,start_date DATE,end_date DATE); INSERT INTO wells (well_id,well_name,production_qty,start_date,end_date) VALUES (1,'Well A',500,'2020-01-01','2022-02-28'),(2,'Well B',700,'2021-01-01','2023-01-01'),(3,'Well C',300,'2021-06-01','2024-01-01');
SELECT well_name, production_qty FROM wells WHERE start_date <= '2022-12-31' AND end_date >= '2022-01-01' ORDER BY production_qty DESC;
Find the number of accessible and non-accessible vehicles in the fleet
CREATE TABLE vehicle_accessibility (vehicle_id INT,vehicle_type VARCHAR(10),accessible BOOLEAN); INSERT INTO vehicle_accessibility (vehicle_id,vehicle_type,accessible) VALUES (1,'Bus',true),(2,'Train',true),(3,'Bus',false),(4,'Tram',true);
SELECT vehicle_type, SUM(accessible) as number_of_accessible_vehicles, SUM(NOT accessible) as number_of_non_accessible_vehicles FROM vehicle_accessibility GROUP BY vehicle_type;
What are the names of all products that contain ingredients sourced from both 'Organic Farms' and 'Large Scale Producers'?
CREATE TABLE product_ingredients (product_name VARCHAR(50),ingredient VARCHAR(50),ingredient_source VARCHAR(50)); INSERT INTO product_ingredients (product_name,ingredient,ingredient_source) VALUES ('Clean Slate','Water','Organic Farms'),('Clean Slate','Mineral Powder','Organic Farms'),('Clean Slate','Water','Large Scale Producers'),('Eye Have You','Water','Large Scale Producers'),('Eye Have You','Mineral Powder','Large Scale Producers');
SELECT product_name FROM product_ingredients WHERE ingredient_source IN ('Organic Farms', 'Large Scale Producers') GROUP BY product_name HAVING COUNT(DISTINCT ingredient_source) = 2;
What is the total amount donated by large donors in the technology sector?
CREATE TABLE donations (id INT,donor_size VARCHAR(50),sector VARCHAR(50),amount DECIMAL(10,2)); INSERT INTO donations (id,donor_size,sector,amount) VALUES (1,'Large','Technology',50000.00),(2,'Small','Healthcare',10000.00),(3,'Medium','Education',25000.00),(4,'Large','Finance',75000.00);
SELECT sector, SUM(amount) as total_donations FROM donations WHERE donor_size = 'Large' AND sector = 'Technology';
List the rural infrastructure projects and their budgets for 'rural_area_1' from the 'rural_infrastructure' and 'community_development' tables
CREATE TABLE rural_infrastructure (project_id INT,project_type VARCHAR(50),budget INT,area_id INT); CREATE TABLE community_development (area_id INT,area_name VARCHAR(50));
SELECT r.project_type, r.budget FROM rural_infrastructure r INNER JOIN community_development c ON r.area_id = c.area_id WHERE c.area_name = 'rural_area_1';
What is the average transaction amount for customers living in the Southern region who made transactions in the past month?
CREATE TABLE transactions (transaction_id INT,customer_id INT,amount INT,transaction_date DATE); INSERT INTO transactions (transaction_id,customer_id,amount,transaction_date) VALUES (1,1,100,'2022-01-01'),(2,1,200,'2022-01-15'),(3,2,50,'2022-01-30');
SELECT AVG(t.amount) FROM transactions t INNER JOIN customers c ON t.customer_id = c.customer_id WHERE c.region = 'Southern' AND t.transaction_date >= DATEADD(month, -1, GETDATE());
Who are the teachers that have not yet participated in any professional development courses?
CREATE TABLE teachers (teacher_id INT,name VARCHAR(20)); INSERT INTO teachers (teacher_id,name) VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Maria Garcia'); CREATE TABLE teacher_pd (teacher_id INT,course VARCHAR(20),hours INT); INSERT INTO teacher_pd (teacher_id,course,hours) VALUES (1,'technology integration',12),(2,'classroom_management',10),(3,'diversity_equity_inclusion',15);
SELECT teachers.name FROM teachers LEFT JOIN teacher_pd ON teachers.teacher_id = teacher_pd.teacher_id WHERE teacher_pd.teacher_id IS NULL;
What is the total quantity of items shipped from China to the United States in January 2021?
CREATE TABLE Warehouse (id INT,country VARCHAR(255),items_quantity INT); INSERT INTO Warehouse (id,country,items_quantity) VALUES (1,'China',300),(2,'USA',400);
SELECT SUM(items_quantity) FROM Warehouse WHERE country = 'China';
Update the 'safety_protocol' table and set 'protocol_status' to 'active' for all records where 'department' is 'R&D'
CREATE TABLE safety_protocol (protocol_id INT,department VARCHAR(20),protocol_status VARCHAR(10));
UPDATE safety_protocol SET protocol_status = 'active' WHERE department = 'R&D';
Who are the top 5 lawyers with the highest number of cases in all courts?
CREATE TABLE cases_all_courts (lawyer_name VARCHAR(20),court_type VARCHAR(20),num_cases INT); INSERT INTO cases_all_courts (lawyer_name,court_type,num_cases) VALUES ('John Doe','Supreme Court',200),('Jane Smith','District Court',300),('Jim Brown','Supreme Court',400),('Jake White','Appellate Court',500),('Janet Black','District Court',600);
SELECT lawyer_name, SUM(num_cases) as total_cases FROM cases_all_courts GROUP BY lawyer_name ORDER BY total_cases DESC LIMIT 5;
Find the total installed capacity of renewable energy power plants for each country, excluding those with a total capacity of less than 100 MW.
CREATE TABLE power_plants (name TEXT,country TEXT,technology TEXT,capacity INTEGER,year_built INTEGER); INSERT INTO power_plants (name,country,technology,capacity,year_built) VALUES ('Solana','United States','Solar',280,2013); INSERT INTO power_plants (name,country,technology,capacity,year_built) VALUES ('Desert Sunlight','United States','Solar',550,2015);
SELECT country, SUM(capacity) FROM power_plants WHERE technology IN ('Wind', 'Solar', 'Hydro') GROUP BY country HAVING SUM(capacity) >= 100;
Delete records from 'Drilling' table where 'Country' is not 'USA'
CREATE TABLE Drilling (WellID INT,Country VARCHAR(20),StartDate DATE,EndDate DATE);
DELETE FROM Drilling WHERE Country != 'USA';
What is the total number of VR games released in 2021 and 2022?
CREATE TABLE GameReleases (id INT,game VARCHAR(100),year INT);
SELECT SUM(CASE WHEN year IN (2021, 2022) THEN 1 ELSE 0 END) FROM GameReleases WHERE game IN (SELECT DISTINCT game FROM VRGames);
What is the average quantity of Fair Trade certified products in the inventory?
CREATE TABLE products (product_id int,name varchar(255),quantity int,is_fair_trade boolean); INSERT INTO products (product_id,name,quantity,is_fair_trade) VALUES (1,'Organic Cotton T-Shirt',100,true),(2,'Regular Cotton T-Shirt',150,false),(3,'Reusable Water Bottle',200,false),(4,'Fair Trade Coffee',50,true);
SELECT AVG(quantity) FROM products WHERE is_fair_trade = true;
How many vegetarian options are available on the menu?
CREATE TABLE menu_items (item VARCHAR(255),vegetarian BOOLEAN); INSERT INTO menu_items (item,vegetarian) VALUES ('Burger',false),('Veggie Burger',true),('Pizza',false);
SELECT COUNT(*) FROM menu_items WHERE vegetarian = true;
What is the total number of farming equipment and tools, along with their respective categories, available in the 'agroecology' schema?
CREATE SCHEMA agroecology;CREATE TABLE equipment (id INT,name VARCHAR(50),category VARCHAR(50));INSERT INTO agroecology.equipment (id,name,category) VALUES (1,'Equipment A','Category A'),(2,'Equipment B','Category B'),(3,'Equipment C','Category A'),(4,'Equipment D','Category C');
SELECT category, COUNT(*) FROM agroecology.equipment GROUP BY category;
What is the percentage of students with visual impairments in the Central region who are enrolled in each program?
CREATE TABLE Students (ID INT,Name VARCHAR(50),Disability VARCHAR(50),Program VARCHAR(50),Region VARCHAR(50)); INSERT INTO Students (ID,Name,Disability,Program,Region) VALUES (1,'Jane Doe','Visual Impairment','Braille Literacy','Central'),(2,'John Doe','Learning Disability','Braille Literacy','Central'),(3,'Jim Smith','Visual Impairment','Accessible Technology','Central');
SELECT Program, (COUNT(*) FILTER (WHERE Disability = 'Visual Impairment')) * 100.0 / COUNT(*) FROM Students WHERE Region = 'Central' GROUP BY Program;
Which vessels have visited the 'Mediterranean' region?
CREATE TABLE vessel_visits (id INT,vessel_id INT,region TEXT,visit_date DATE); INSERT INTO vessel_visits (id,vessel_id,region,visit_date) VALUES (1,1,'Mediterranean','2022-01-01'); INSERT INTO vessel_visits (id,vessel_id,region,visit_date) VALUES (2,2,'Atlantic','2022-01-02');
SELECT DISTINCT vessel_id FROM vessel_visits WHERE region = 'Mediterranean'
What are the total number of safety incidents for each vessel in the Caribbean?
CREATE TABLE Vessels (VesselID INT,VesselName VARCHAR(50));CREATE TABLE SafetyIncidents (IncidentID INT,VesselID INT,IncidentLocation VARCHAR(50),IncidentDate DATE); INSERT INTO Vessels (VesselID,VesselName) VALUES (1,'VesselA'),(2,'VesselB'),(3,'VesselC'); INSERT INTO SafetyIncidents (IncidentID,VesselID,IncidentLocation,IncidentDate) VALUES (1,1,'Caribbean','2021-01-01'),(2,1,'Caribbean','2021-02-01'),(3,2,'Caribbean','2021-03-01'),(4,3,'Caribbean','2021-04-01'),(5,3,'Caribbean','2021-05-01');
SELECT Vessels.VesselName, COUNT(SafetyIncidents.IncidentID) AS TotalIncidents FROM Vessels INNER JOIN SafetyIncidents ON Vessels.VesselID = SafetyIncidents.VesselID WHERE SafetyIncidents.IncidentLocation = 'Caribbean' GROUP BY Vessels.VesselName;
What is the total number of spacecraft manufactured by all companies in the year 2023?
CREATE TABLE spacecraft_manufacturing (id INT,company TEXT,year INT,quantity INT); INSERT INTO spacecraft_manufacturing (id,company,year,quantity) VALUES (1,'SpaceY',2022,10),(2,'SpaceY',2023,12),(3,'Blue Origin',2023,8),(4,'SpaceX',2022,15);
SELECT SUM(quantity) FROM spacecraft_manufacturing WHERE year = 2023;
What's the average water consumption per mining site for the past year?
CREATE TABLE mining_sites (id INT,name VARCHAR(50)); CREATE TABLE water_consumption (site_id INT,consumption FLOAT,consumption_date DATE); INSERT INTO mining_sites (id,name) VALUES (1,'Site A'),(2,'Site B'),(3,'Site C'); INSERT INTO water_consumption (site_id,consumption,consumption_date) VALUES (1,200,'2022-01-01'),(1,300,'2022-02-01'),(2,150,'2022-01-01');
SELECT ms.name, AVG(wc.consumption) as avg_consumption FROM mining_sites ms INNER JOIN water_consumption wc ON ms.id = wc.site_id WHERE wc.consumption_date BETWEEN DATEADD(year, -1, GETDATE()) AND GETDATE() GROUP BY ms.name;
Calculate the average donation amount for each program.
CREATE TABLE donations (id INT,volunteer_id INT,program_id INT,amount DECIMAL(10,2)); INSERT INTO donations (id,volunteer_id,program_id,amount) VALUES (1,1,1,100),(2,2,2,200),(3,3,1,300);
SELECT program_id, AVG(amount) OVER (PARTITION BY program_id) AS avg_donation_amount FROM donations;
Determine the total quantity of 'Gluten-free' products in the 'Inventory' table
CREATE TABLE Inventory (id INT PRIMARY KEY,name VARCHAR(255),category VARCHAR(255),quantity INT); INSERT INTO Inventory (id,name,category,quantity) VALUES (1,'Bread','Gluten-free',25),(2,'Pasta','Gluten-free',50),(3,'Cereal','Gluten-free',75);
SELECT SUM(quantity) FROM Inventory WHERE category = 'Gluten-free';
Delete all records from the 'defense_diplomacy' table where the year is less than 2000
CREATE TABLE defense_diplomacy (id INT PRIMARY KEY,partnership VARCHAR(50),year INT); INSERT INTO defense_diplomacy (id,partnership,year) VALUES (1,'US-UK',2005); INSERT INTO defense_diplomacy (id,partnership,year) VALUES (2,'US-France',1999);
DELETE FROM defense_diplomacy WHERE year < 2000;
List policy numbers and policy types for policies with claims exceeding $5000 in the last 6 months, for policyholders over the age of 50.
CREATE TABLE InsurancePolicies (PolicyNumber INT,PolicyType VARCHAR(50),IssueDate DATE,PolicyHolderAge INT); CREATE TABLE Claims (ClaimID INT,PolicyNumber INT,ClaimAmount INT,ClaimDate DATE); INSERT INTO InsurancePolicies VALUES (1,'Auto','2020-01-01',55),(2,'Home','2019-12-01',45),(3,'Auto','2020-03-15',60); INSERT INTO Claims VALUES (1,1,7000,'2022-01-15'),(2,2,3000,'2022-02-10'),(3,3,4000,'2022-01-05');
SELECT InsurancePolicies.PolicyNumber, InsurancePolicies.PolicyType FROM InsurancePolicies JOIN Claims ON InsurancePolicies.PolicyNumber = Claims.PolicyNumber WHERE Claims.ClaimAmount > 5000 AND InsurancePolicies.PolicyHolderAge > 50 AND Claims.ClaimDate >= DATEADD(month, -6, GETDATE());
List the names and community service hours of offenders in Washington, sorted by the total hours (highest to lowest).
CREATE TABLE offenders (id INT,name TEXT,state TEXT,community_service_hours INT); INSERT INTO offenders (id,name,state,community_service_hours) VALUES (1,'John Doe','Washington',50); INSERT INTO offenders (id,name,state,community_service_hours) VALUES (2,'Jane Smith','Washington',75); INSERT INTO offenders (id,name,state,community_service_hours) VALUES (3,'Mike Brown','Washington',100);
SELECT name, community_service_hours FROM offenders WHERE state = 'Washington' ORDER BY community_service_hours DESC;
Add a record for anxiety disorders category
CREATE TABLE mental_health_condition_categories (id INT PRIMARY KEY,name VARCHAR(255),description TEXT);
INSERT INTO mental_health_condition_categories (id, name, description) VALUES (1, 'Anxiety Disorders', 'A category of mental health conditions characterized by feelings of anxiety and fear.');
List the games and the average number of effective kills for the top 3 players.
CREATE TABLE PlayerStats (PlayerID INT,Game VARCHAR(50),Kills INT,Deaths INT,Assists INT); INSERT INTO PlayerStats (PlayerID,Game,Kills,Deaths,Assists) VALUES (1,'FPS Game',50,30,15); INSERT INTO PlayerStats (PlayerID,Game,Kills,Deaths,Assists) VALUES (2,'RPG Game',20,10,30); INSERT INTO PlayerStats (PlayerID,Game,Kills,Deaths,Assists) VALUES (3,'FPS Game',60,20,20); INSERT INTO PlayerStats (PlayerID,Game,Kills,Deaths,Assists) VALUES (4,'RPG Game',30,5,40); INSERT INTO PlayerStats (PlayerID,Game,Kills,Deaths,Assists) VALUES (5,'FPS Game',70,25,25); INSERT INTO PlayerStats (PlayerID,Game,Kills,Deaths,Assists) VALUES (6,'RPG Game',40,10,50);
SELECT Game, AVG(EffectiveKills) AS AvgEffectiveKills FROM (SELECT PlayerID, Game, Kills + Assists - Deaths AS EffectiveKills, ROW_NUMBER() OVER (PARTITION BY Game ORDER BY Kills + Assists - Deaths DESC) AS Rank FROM PlayerStats) AS PlayerStatsRank WHERE Rank <= 3 GROUP BY Game;
How many satellites have been deployed by each country?
CREATE TABLE satellites (satellite_id INT,country VARCHAR(50));
SELECT country, COUNT(satellite_id) as num_satellites FROM satellites GROUP BY country;
How many museums are in Asia?
CREATE TABLE museums (id INT,name VARCHAR(50),region VARCHAR(50)); INSERT INTO museums (id,name,region) VALUES (1,'Metropolitan Museum','America'),(2,'British Museum','Europe'),(3,'Tokyo National Museum','Asia');
SELECT COUNT(*) FROM museums WHERE region = 'Asia';
What is the total value of all token transfers to and from exchanges in the last 7 days?
CREATE TABLE token_exchanges (token_name TEXT,from_exchange TEXT,to_exchange TEXT,transfer_amount REAL,timestamp TIMESTAMP); INSERT INTO token_exchanges (token_name,from_exchange,to_exchange,transfer_amount,timestamp) VALUES ('Uniswap','Tether',NULL,15000,'2022-01-10 10:45:22'); INSERT INTO token_exchanges (token_name,from_exchange,to_exchange,transfer_amount,timestamp) VALUES ('Sushiswap',NULL,'Binance',20000,'2022-01-11 11:18:35');
SELECT SUM(transfer_amount) as total_value FROM token_exchanges WHERE timestamp >= (SELECT timestamp FROM token_exchanges ORDER BY timestamp DESC LIMIT 1) - INTERVAL '7 days' AND (from_exchange IS NOT NULL OR to_exchange IS NOT NULL);
What is the minimum distance between two bus stops in Rome?
CREATE TABLE bus_stops (stop_id INT,stop_name VARCHAR(255),city VARCHAR(255),distance_to_next_stop INT);
SELECT MIN(distance_to_next_stop) FROM bus_stops WHERE city = 'Rome';
What is the distribution of clothing sizes sold to customers in Canada?
CREATE TABLE sizes (country VARCHAR(10),product VARCHAR(20),size DECIMAL(3,2)); INSERT INTO sizes (country,product,size) VALUES ('Canada','shirt',44.0),('Canada','shirt',46.0),('Canada','shirt',48.0),('Canada','pants',34.0),('Canada','pants',36.0),('Canada','pants',38.0);
SELECT size, COUNT(*) FROM sizes WHERE country = 'Canada' GROUP BY size;
What is the total number of autonomous vehicles in 'Autonomous Driving Research' table by status?
CREATE TABLE Autonomous_Driving_Research (vehicle_id INT,status VARCHAR(20),num_autonomous INT);
SELECT status, SUM(num_autonomous) FROM Autonomous_Driving_Research GROUP BY status;
How many unique IP addresses are associated with each threat category in the last week?
CREATE TABLE threats (id INT,category VARCHAR(50),ip_address VARCHAR(50),threat_date DATE); INSERT INTO threats (id,category,ip_address,threat_date) VALUES (1,'Malware','192.168.1.1','2022-01-01'),(2,'Phishing','192.168.1.2','2022-01-02');
SELECT category, COUNT(DISTINCT ip_address) as unique_ips FROM threats WHERE threat_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) GROUP BY category;
List the wells with the highest production volume in each state
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),production_volume FLOAT,state VARCHAR(5)); INSERT INTO wells VALUES (1,'Well A',1000,'TX'); INSERT INTO wells VALUES (2,'Well B',1500,'AK'); INSERT INTO wells VALUES (3,'Well C',1200,'TX'); INSERT INTO wells VALUES (4,'Well D',800,'LA'); INSERT INTO wells VALUES (5,'Well E',1800,'AK');
SELECT state, MAX(production_volume) FROM wells GROUP BY state;
What's the average word count of articles in the 'Politics' category?
CREATE TABLE articles (id INT,title TEXT,category TEXT,word_count INT); INSERT INTO articles (id,title,category,word_count) VALUES (1,'Article1','Politics',800),(2,'Article2','Sports',500);
SELECT AVG(word_count) FROM articles WHERE category = 'Politics';
Calculate the percentage of Holmium used in various industries.
CREATE TABLE holmium_usage (industry VARCHAR(50),usage FLOAT);
SELECT industry, usage * 100.0 / SUM(usage) OVER (PARTITION BY NULL) AS percentage FROM holmium_usage;