instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the average landfill capacity in Japan and Australia?
CREATE TABLE landfill_capacity (country VARCHAR(255),capacity FLOAT); INSERT INTO landfill_capacity (country,capacity) VALUES ('Japan',9.2),('Australia',13.5); CREATE VIEW avg_landfill_capacity AS SELECT country,capacity/1000000 AS capacity_megatons FROM landfill_capacity;
SELECT AVG(capacity_megatons) FROM avg_landfill_capacity WHERE country IN ('Japan', 'Australia');
What is the number of employees hired in each quarter, ordered by hire date?
CREATE TABLE Employees (EmployeeID int,FirstName varchar(50),LastName varchar(50),HireDate date); INSERT INTO Employees (EmployeeID,FirstName,LastName,HireDate) VALUES (1,'John','Doe','2020-01-01'); INSERT INTO Employees (EmployeeID,FirstName,LastName,HireDate) VALUES (2,'Jane','Smith','2020-04-01');
SELECT DATEPART(quarter, HireDate) as HireQuarter, COUNT(*) as HireCount FROM Employees GROUP BY DATEPART(quarter, HireDate) ORDER BY HireQuarter;
What is the total revenue generated by the Tate from Cubist paintings between 1910 and 1920?
CREATE TABLE Artworks (artwork_id INT,name VARCHAR(255),artist_id INT,date_sold DATE,price DECIMAL(10,2),museum_id INT); CREATE TABLE Artists (artist_id INT,name VARCHAR(255),nationality VARCHAR(255),gender VARCHAR(255)); CREATE TABLE Museums (museum_id INT,name VARCHAR(255));
SELECT SUM(Artworks.price) FROM Artworks INNER JOIN Artists ON Artworks.artist_id = Artists.artist_id INNER JOIN Museums ON Artworks.museum_id = Museums.museum_id WHERE Artists.nationality = 'Cubist' AND Museums.name = 'The Tate' AND YEAR(Artworks.date_sold) BETWEEN 1910 AND 1920;
What is the average delivery time for recycled packaging orders?
CREATE TABLE OrderDetails (order_id INT,product_id INT,delivery_date DATE,packaging_type VARCHAR(255)); CREATE TABLE PackagingInfo (packaging_id INT,packaging_type VARCHAR(255),is_recycled BOOLEAN,avg_delivery_time INT); INSERT INTO PackagingInfo (packaging_id,packaging_type,is_recycled,avg_delivery_time) VALUES (1,'Re...
SELECT AVG(PackagingInfo.avg_delivery_time) FROM PackagingInfo INNER JOIN OrderDetails ON PackagingInfo.packaging_type = OrderDetails.packaging_type WHERE PackagingInfo.is_recycled = true;
What is the total revenue generated from wheelchair accessible taxi rides in London?
CREATE TABLE taxi_trips (trip_id INT,start_time TIMESTAMP,end_time TIMESTAMP,trip_distance FLOAT,fare FLOAT,wheelchair_accessible BOOLEAN);
SELECT SUM(fare) FROM taxi_trips WHERE wheelchair_accessible = TRUE;
Delete the records of all professors who have not published any papers.
CREATE TABLE professors (id INT,name VARCHAR(50),department VARCHAR(50),research_interest VARCHAR(50),num_papers INT); INSERT INTO professors (id,name,department,research_interest,num_papers) VALUES (1,'John Doe','Computer Science','Machine Learning',6),(2,'Jane Smith','Computer Science','Data Science',3),(3,'Alice Joh...
DELETE FROM professors WHERE num_papers = 0;
List all projects and their completion dates from organizations located in 'CA'?
CREATE TABLE Organizations (OrgID INT,OrgName TEXT,OrgState TEXT,ProjectID INT,ProjectCompletionDate DATE);
SELECT p.ProjectID, p.ProjectCompletionDate FROM Projects p INNER JOIN Organizations o ON p.OrgID = o.OrgID WHERE o.OrgState = 'CA';
What is the minimum natural gas production in the Niger Delta for 2018?
CREATE TABLE niger_delta_platforms (platform_id INT,platform_name VARCHAR(50),location VARCHAR(50),operational_status VARCHAR(15)); INSERT INTO niger_delta_platforms VALUES (1,'Shell 1','Niger Delta','Active'); INSERT INTO niger_delta_platforms VALUES (2,'Chevron 1','Niger Delta','Active'); CREATE TABLE gas_production ...
SELECT MIN(production) FROM gas_production WHERE year = 2018 AND location = 'Niger Delta';
What is the minimum safety score for each AI application in the 'explainable_ai' database?
CREATE TABLE explainable_ai.ai_applications (ai_application_id INT PRIMARY KEY,ai_algorithm_id INT,application_name VARCHAR(255),safety_score FLOAT); INSERT INTO explainable_ai.ai_applications (ai_application_id,ai_algorithm_id,application_name,safety_score) VALUES (1,1,'AI-generated art',0.8),(2,1,'AI-generated music'...
SELECT a.application_name, MIN(safety_score) as min_safety_score FROM explainable_ai.ai_applications a GROUP BY a.application_name;
Find the number of sensors in each field.
CREATE TABLE field_sensors (id INT,field_id INT,sensor_id INT);
SELECT field_id, COUNT(DISTINCT sensor_id) as sensor_count FROM field_sensors GROUP BY field_id;
What is the total revenue generated by FPS games in the last quarter?
CREATE TABLE GameSales (GameID INT,GameType VARCHAR(10),Revenue INT,SaleDate DATE); INSERT INTO GameSales (GameID,GameType,Revenue,SaleDate) VALUES (1,'FPS',1000,'2022-01-01'),(2,'RPG',2000,'2022-01-02');
SELECT SUM(Revenue) FROM GameSales WHERE GameType = 'FPS' AND SaleDate >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
Which intelligence operations have been conducted in country 'X'?
CREATE TABLE Intelligence_Operations (Operation_Name VARCHAR(255),Country VARCHAR(255),Year INT); INSERT INTO Intelligence_Operations (Operation_Name,Country,Year) VALUES ('Operation Red Sparrow','Russia',2015),('Operation Nightfall','China',2018),('Operation Black Swan','X',2020);
SELECT Operation_Name FROM Intelligence_Operations WHERE Country = 'X';
How many community health workers have been added to the system in the last month?
CREATE TABLE community_health_workers (id INT PRIMARY KEY,name TEXT,hired_date DATE,language TEXT,cultural_competency_score INT);
SELECT COUNT(*) FROM community_health_workers WHERE hired_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
What is the average budget for rural infrastructure projects in each country?
CREATE TABLE rural_infrastructure (id INT,country VARCHAR(50),project_type VARCHAR(50),budget INT); INSERT INTO rural_infrastructure (id,country,project_type,budget) VALUES (1,'Kenya','Roads',5000000),(2,'Kenya','Irrigation',7000000),(3,'Tanzania','Roads',6000000),(4,'Uganda','Rural Electrification',8000000);
SELECT country, AVG(budget) as avg_budget FROM rural_infrastructure GROUP BY country;
What is the average improvement score of patients by age group?
CREATE TABLE age_improvement (age INT,improvement_score INT); INSERT INTO age_improvement (age,improvement_score) VALUES (18,10);
SELECT age_groups.age_group_name, AVG(age_improvement.improvement_score) FROM age_groups INNER JOIN age_improvement ON age_groups.age BETWEEN age_improvement.age - 5 AND age_improvement.age + 5 GROUP BY age_groups.age_group_name;
How many pharmacies are there in each city, ordered by the number of pharmacies?
CREATE TABLE Pharmacies (ID INT,Name VARCHAR(50),City VARCHAR(50)); INSERT INTO Pharmacies (ID,Name,City) VALUES (1,'CVS','New York');
SELECT City, COUNT(*) AS NumPharmacies FROM Pharmacies GROUP BY City ORDER BY NumPharmacies DESC;
How many regions have wildlife habitats?
CREATE TABLE regions (region_id INT,region_name TEXT);CREATE TABLE wildlife_habitat (habitat_id INT,region_id INT); INSERT INTO regions (region_id,region_name) VALUES (1,'Region A'),(2,'Region B'),(3,'Region C'); INSERT INTO wildlife_habitat (habitat_id,region_id) VALUES (1,1),(2,1),(3,2),(4,3),(5,3);
SELECT region_id, region_name, COUNT(*) FROM regions JOIN wildlife_habitat ON regions.region_id = wildlife_habitat.region_id GROUP BY region_id, region_name HAVING COUNT(*) > 0;
What is the total number of unique genes analyzed in the biosensor project?
CREATE SCHEMA if not exists biosensor; USE biosensor; CREATE TABLE if not exists genes_analyzed (gene_name VARCHAR(255)); INSERT INTO genes_analyzed (gene_name) VALUES ('ABC'),('DEF'),('GHI'),('JKL'),('MNO'),('PQR'),('ABC'),('STU');
SELECT COUNT(DISTINCT gene_name) FROM biosensor.genes_analyzed;
What is the average salary of workers in the 'Transportation' industry who are not members of a union?
CREATE TABLE Workers (EmployeeID INT,Industry VARCHAR(20),UnionMember BOOLEAN,Salary FLOAT); INSERT INTO Workers (EmployeeID,Industry,UnionMember,Salary) VALUES (1,'Transportation',false,58000.0),(2,'Transportation',true,60000.0),(3,'Transportation',false,56000.0);
SELECT AVG(Salary) FROM Workers WHERE Industry = 'Transportation' AND UnionMember = false;
What is the total number of crime incidents per month in the 'Central' precinct?
CREATE TABLE precinct (id INT,name VARCHAR(50)); INSERT INTO precinct (id,name) VALUES (1,'Central'); CREATE TABLE incident (id INT,precinct_id INT,incident_date DATE);
SELECT DATEPART(year, incident_date) as year, DATEPART(month, incident_date) as month, COUNT(*) as total_incidents FROM incident WHERE precinct_id = 1 GROUP BY DATEPART(year, incident_date), DATEPART(month, incident_date);
What is the maximum volume of timber produced in a single year?
CREATE TABLE yearly_timber (year INT,volume_m3 INT); INSERT INTO yearly_timber (year,volume_m3) VALUES (2010,2000),(2011,2200),(2012,2500),(2013,2700),(2014,3000);
SELECT MAX(volume_m3) FROM yearly_timber;
How many unique strains were grown in Oregon in 2020?
CREATE TABLE Farms (id INT,name TEXT,state TEXT); INSERT INTO Farms (id,name,state) VALUES (1,'Farm A','Oregon'),(2,'Farm B','Oregon'); CREATE TABLE Strains (id INT,farm_id INT,name TEXT); INSERT INTO Strains (id,farm_id,name) VALUES (1,1,'Strain X'),(2,1,'Strain Y'),(3,2,'Strain Z');
SELECT COUNT(DISTINCT s.name) as unique_strains FROM Strains s INNER JOIN Farms f ON s.farm_id = f.id WHERE f.state = 'Oregon' AND s.date BETWEEN '2020-01-01' AND '2020-12-31';
How many patients in Texas received medication for depression?
CREATE TABLE patients (patient_id INT,age INT,gender TEXT,state TEXT,condition TEXT,medication TEXT); INSERT INTO patients (patient_id,age,gender,state,condition,medication) VALUES (1,30,'Female','Texas','Depression','Yes'); INSERT INTO patients (patient_id,age,gender,state,condition,medication) VALUES (2,45,'Male','Te...
SELECT COUNT(*) FROM patients WHERE state = 'Texas' AND condition = 'Depression' AND medication = 'Yes';
Insert a new aircraft into the database
CREATE SCHEMA if not exists aerospace;CREATE TABLE if not exists aerospace.aircraft (id INT,name VARCHAR(255),manufacture_country VARCHAR(255),manufacture_date DATE);
INSERT INTO aerospace.aircraft (id, name, manufacture_country, manufacture_date) VALUES (3, 'Air3', 'Germany', '2022-02-01');
What is the maximum price of products in the 'clothing' category that are made in the USA?
CREATE TABLE products (product_id INT,product_name VARCHAR(50),price DECIMAL(5,2),category VARCHAR(50),country_of_manufacture VARCHAR(50)); INSERT INTO products (product_id,product_name,price,category,country_of_manufacture) VALUES (1,'T-Shirt',20.99,'clothing','USA'),(2,'Jeans',55.99,'clothing','USA'),(3,'Sneakers',79...
SELECT MAX(price) FROM products WHERE category = 'clothing' AND country_of_manufacture = 'USA';
Get players who have never played 'RPG' games
player (player_id,name,email,age,gender,country,total_games_played); game (game_id,name,genre,release_year); player_game (player_id,game_id,last_played)
SELECT DISTINCT p.player_id, p.name, p.email, p.age, p.gender, p.country, p.total_games_played FROM player p LEFT JOIN player_game pg ON p.player_id = pg.player_id LEFT JOIN game g ON pg.game_id = g.game_id WHERE g.genre != 'RPG' OR g.game_id IS NULL
What is the minimum water consumption in a single day for all wastewater treatment plants in 'Africa'?
CREATE TABLE wastewater_treatment_plants_by_region (plant_id INT,daily_consumption FLOAT,consumption_date DATE,plant_location VARCHAR(20)); INSERT INTO wastewater_treatment_plants_by_region (plant_id,daily_consumption,consumption_date,plant_location) VALUES (1,1000,'2022-03-01','Africa'),(2,1500,'2022-03-02','Asia'),(3...
SELECT MIN(daily_consumption) FROM wastewater_treatment_plants_by_region WHERE plant_location = 'Africa';
What is the distribution of cruelty-free certifications by year for cosmetics products in the makeup category?
CREATE TABLE certifications(certification_id INT,product_id INT,certification_type VARCHAR(50),certified_date DATE);
SELECT YEAR(certified_date) as certification_year, COUNT(*) as cruelty_free_count FROM certifications JOIN cosmetics_products ON certifications.product_id = cosmetics_products.product_id WHERE certifications.certification_type = 'cruelty-free' AND cosmetics_products.category = 'makeup' GROUP BY certification_year;
Find the trench with the maximum depth in the Indian Ocean and display the trench name and maximum depth
CREATE TABLE marine_trenches (ocean TEXT,trench TEXT,max_depth INTEGER);INSERT INTO marine_trenches (ocean,trench,max_depth) VALUES ('Pacific','Mariana Trench',10994),('Indian','Java Trench',7725);
SELECT trench, max_depth FROM marine_trenches WHERE ocean = 'Indian' AND max_depth = (SELECT MAX(max_depth) FROM marine_trenches WHERE ocean = 'Indian');
List all safety protocol violations by employees in the past 6 months, grouped by month.
CREATE TABLE Violations (id INT,employee VARCHAR(255),violation_date DATE); INSERT INTO Violations (id,employee,violation_date) VALUES (1,'John Doe','2022-01-15'),(2,'Jane Smith','2022-02-20');
SELECT DATE_FORMAT(violation_date, '%Y-%m') as Month, employee, COUNT(*) FROM Violations WHERE violation_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY Month, employee
Who are the top contributors to explainable AI on GitHub?
CREATE TABLE GitHub (username TEXT,repos INT,domain TEXT); INSERT INTO GitHub VALUES ('Octocat',10,'Explainable AI'),('AI-Guru',20,'Explainable AI');
SELECT username FROM GitHub WHERE domain = 'Explainable AI' ORDER BY repos DESC LIMIT 1;
How many decentralized applications are built on the EOS blockchain, and what is their total token supply?
CREATE TABLE eos_dapps (dapp_id INT,name VARCHAR(255),token_supply DECIMAL(30,0)); INSERT INTO eos_dapps (dapp_id,name,token_supply) VALUES (1,'Dapp1',100000000),(2,'Dapp2',200000000),(3,'Dapp3',300000000);
SELECT COUNT(*), SUM(token_supply) FROM eos_dapps;
List all access to justice cases resolved in Los Angeles in 2021.
CREATE TABLE cases (case_id INT,resolution_date DATE,city VARCHAR(20)); INSERT INTO cases (case_id,resolution_date,city) VALUES (1,'2021-01-01','Los Angeles'); INSERT INTO cases (case_id,resolution_date,city) VALUES (2,'2020-01-01','New York');
SELECT case_id FROM cases WHERE resolution_date BETWEEN '2021-01-01' AND '2021-12-31' AND city = 'Los Angeles';
Find the difference between the highest and lowest safety ratings in the creative_ai table.
CREATE TABLE creative_ai (app_id INT,app_name TEXT,safety_rating REAL); INSERT INTO creative_ai VALUES (1,'Dalle',4.3,'USA'),(2,'GTP-3',4.5,'Canada'),(3,'Midjourney',4.7,'Australia');
SELECT MAX(safety_rating) - MIN(safety_rating) as safety_rating_diff FROM creative_ai;
What is the maximum number of defense contracts signed per month in 2021?
CREATE TABLE DefenseContracts (Id INT,ContractName VARCHAR(50),Timestamp DATETIME); INSERT INTO DefenseContracts (Id,ContractName,Timestamp) VALUES (1,'Contract A','2021-01-01 09:00:00'),(2,'Contract B','2021-02-15 12:30:00'),(3,'Contract C','2021-12-31 16:45:00');
SELECT MAX(MonthlyContractCount) FROM (SELECT COUNT(*) AS MonthlyContractCount, YEAR(Timestamp) AS ContractYear, MONTH(Timestamp) AS ContractMonth FROM DefenseContracts GROUP BY YEAR(Timestamp), MONTH(Timestamp)) AS ContractCounts WHERE ContractYear = 2021;
Which players from the 'players' table have the highest average scores in the 'scores' table, and how many high scores did they achieve?
CREATE TABLE players (player_id INT,name VARCHAR(50)); INSERT INTO players VALUES (1,'John'); INSERT INTO players VALUES (2,'Jane'); CREATE TABLE scores (score_id INT,player_id INT,score INT); INSERT INTO scores VALUES (1,1,90); INSERT INTO scores VALUES (2,1,95); INSERT INTO scores VALUES (3,2,85); INSERT INTO scores ...
SELECT p.name, AVG(s.score) as avg_score, COUNT(*) as high_scores FROM players p JOIN scores s ON p.player_id = s.player_id WHERE s.score >= (SELECT AVG(score) FROM scores) GROUP BY p.player_id ORDER BY avg_score DESC, high_scores DESC;
Calculate the average REE market trends for each year since 2017, excluding China.
CREATE TABLE market_trends (year INT,market_trend VARCHAR(255),country VARCHAR(255)); INSERT INTO market_trends (year,market_trend,country) VALUES (2017,'Increase','China'),(2017,'Decrease','USA'),(2018,'Stable','China'),(2018,'Increase','USA'),(2019,'Decrease','China'),(2019,'Stable','USA');
SELECT AVG(market_trend = 'Increase') AS avg_increase, AVG(market_trend = 'Decrease') AS avg_decrease, AVG(market_trend = 'Stable') AS avg_stable FROM market_trends WHERE year >= 2017 AND country != 'China';
What is the average response time for fire incidents?
CREATE TABLE FireIncidents (id INT,incident_type VARCHAR(20),location VARCHAR(50),date DATE,time TIME,response_time INT); INSERT INTO FireIncidents (id,incident_type,location,date,time,response_time) VALUES (1,'Building fire','City H','2022-05-05','08:15:00',25);
SELECT AVG(response_time) FROM FireIncidents WHERE incident_type = 'Building fire';
Identify the top 3 marine species with the largest population size.
CREATE TABLE marine_species (species_id INTEGER,species_name TEXT,avg_population_size FLOAT);
SELECT species_name, avg_population_size FROM marine_species ORDER BY avg_population_size DESC LIMIT 3;
What is the total number of pallets shipped from Italy to Spain?
CREATE TABLE Pallets_2 (id INT,item VARCHAR(50),quantity INT,country VARCHAR(50)); INSERT INTO Pallets_2 (id,item,quantity,country) VALUES (1,'Baz',50,'Italy'),(2,'Qux',75,'Spain');
SELECT SUM(quantity) FROM Pallets_2 WHERE country = 'Italy' AND EXISTS (SELECT 1 FROM Pallets_2 p2 WHERE p2.country = 'Spain');
What is the average R&D expenditure for 'DrugB' and 'DrugC' in the first quarter of 2019?
CREATE TABLE r_and_d_expenditures (drug_name VARCHAR(255),expenditure DECIMAL(10,2),expenditure_date DATE); INSERT INTO r_and_d_expenditures (drug_name,expenditure,expenditure_date) VALUES ('DrugB',50000,'2019-01-01');
SELECT AVG(expenditure) FROM r_and_d_expenditures WHERE drug_name IN ('DrugB', 'DrugC') AND QUARTER(expenditure_date) = 1 AND YEAR(expenditure_date) = 2019;
Delete records where the 'Pine' species population is less than 5,500,000.
CREATE TABLE regions (id INT PRIMARY KEY,name VARCHAR(255)); INSERT INTO regions (id,name) VALUES (1,'Europe'); INSERT INTO regions (id,name) VALUES (2,'North America'); CREATE TABLE population_by_region (region_id INT,species_id INT,population INT); INSERT INTO population_by_region (region_id,species_id,population) VA...
DELETE FROM population_by_region WHERE species_id = 2 AND population < 5500000;
List all vendors that supply ingredients for dishes with a calorie count above the average.
CREATE TABLE Vendors (vid INT,name TEXT);CREATE TABLE Dishes (did INT,name TEXT,calorie_content INT);CREATE TABLE Ingredients (iid INT,dish_id INT,vendor_id INT);INSERT INTO Vendors VALUES (1,'VendorA'),(2,'VendorB'),(3,'VendorC');INSERT INTO Dishes VALUES (1,'DishA',500),(2,'DishB',1500),(3,'DishC',800);INSERT INTO In...
SELECT DISTINCT Vendors.name FROM Vendors INNER JOIN Ingredients ON Vendors.vid = Ingredients.vendor_id INNER JOIN Dishes ON Ingredients.dish_id = Dishes.did WHERE Dishes.calorie_content > (SELECT AVG(calorie_content) FROM Dishes);
Count the number of fish species farmed in Norway with a survival rate greater than 85%?
CREATE TABLE fish_species (species_id INT,species_name TEXT,country TEXT,survival_rate FLOAT); INSERT INTO fish_species (species_id,species_name,country,survival_rate) VALUES (1,'Salmon','Norway',0.87),(2,'Cod','Norway',0.82),(3,'Tilapia','Norway',0.88);
SELECT COUNT(*) FROM fish_species WHERE country = 'Norway' AND survival_rate > 0.85;
What was the total military equipment sales value to Japan in 2018?
CREATE TABLE Military_Equipment_Sales (sale_id INT,year INT,country VARCHAR(50),value FLOAT); INSERT INTO Military_Equipment_Sales (sale_id,year,country,value) VALUES (1,2018,'Japan',1200000),(2,2019,'Japan',1500000);
SELECT YEAR(assessment_date), SUM(value) FROM Military_Equipment_Sales WHERE country = 'Japan' AND year = 2018 GROUP BY YEAR(assessment_date);
List all revenue records for the month of January 2022
CREATE TABLE Revenue (revenue_id INT,revenue_date DATE,revenue_amount DECIMAL(10,2)); INSERT INTO Revenue (revenue_id,revenue_date,revenue_amount) VALUES (1,'2022-01-01',1500); INSERT INTO Revenue (revenue_id,revenue_date,revenue_amount) VALUES (2,'2022-01-02',2000);
SELECT * FROM Revenue WHERE revenue_date BETWEEN '2022-01-01' AND '2022-01-31';
How many sculptures are there in the 'contemporary' museum?
CREATE TABLE museums (id INT,name TEXT,type TEXT); INSERT INTO museums (id,name,type) VALUES (1,'contemporary','museum'),(2,'modernart','museum'); CREATE TABLE artworks (id INT,museum_id INT,title TEXT,medium TEXT); INSERT INTO artworks (id,museum_id,title,medium) VALUES (1,1,'Untitled','Sculpture'),(2,1,'The Weather P...
SELECT COUNT(*) FROM artworks WHERE museum_id = 1 AND medium = 'Sculpture';
Get the product with the lowest price from each material category.
CREATE TABLE product (product_id INT,name VARCHAR(255),price DECIMAL(5,2),material VARCHAR(255)); INSERT INTO product (product_id,name,price,material) VALUES (1,'Organic Cotton T-Shirt',20.99,'organic cotton'),(2,'Polyester Hoodie',15.99,'polyester'),(3,'Bamboo Socks',7.99,'bamboo');
SELECT product_id, name, price, material FROM (SELECT product_id, name, price, material, NTILE(3) OVER (PARTITION BY material ORDER BY price) AS tier FROM product) AS tiered_products WHERE tier = 1;
Show the total budget allocated for defense contracts in each region
CREATE TABLE defense_contracts (contract_id INT,contract_name VARCHAR(100),budget INT,region VARCHAR(50));
SELECT region, SUM(budget) FROM defense_contracts GROUP BY region;
How many total items were delivered in disaster-affected areas in the year 2021?
CREATE TABLE delivery (delivery_id INT,delivery_date DATE,num_items INT,disaster_affected BOOLEAN); INSERT INTO delivery (delivery_id,delivery_date,num_items,disaster_affected) VALUES (1,'2021-01-01',5,true),(2,'2021-01-02',10,false),(3,'2021-02-01',15,true);
SELECT SUM(num_items) FROM delivery WHERE disaster_affected = true AND delivery_date BETWEEN '2021-01-01' AND '2021-12-31';
What is the total value of military equipment sales to Taiwan and Mexico combined in 2020 and 2021?
CREATE TABLE MilitaryEquipmentSales (id INT PRIMARY KEY,sale_year INT,equipment_type VARCHAR(50),country VARCHAR(50),sale_value FLOAT); INSERT INTO MilitaryEquipmentSales (id,sale_year,equipment_type,country,sale_value) VALUES (1,2020,'Aircraft','United States',12000000),(2,2021,'Vehicles','United States',8000000),(3,2...
SELECT SUM(sale_value) FROM MilitaryEquipmentSales WHERE (country = 'Taiwan' OR country = 'Mexico') AND sale_year IN (2020, 2021);
What is the distribution of mental health resource access by gender?
CREATE TABLE gender (gender_code CHAR(1),gender_name VARCHAR(10)); INSERT INTO gender VALUES ('F','Female'),('M','Male'),('N','Non-binary'); CREATE TABLE students (student_id INT,gender_code CHAR(1),mental_health_resource_access DATE); INSERT INTO students VALUES (1,'F','2021-09-15'),(2,'M','2021-10-01'),(3,'N','2021-1...
SELECT g.gender_name, COUNT(DISTINCT students.student_id) AS student_count FROM gender g JOIN students ON g.gender_code = students.gender_code WHERE students.mental_health_resource_access >= DATEADD(month, -1, GETDATE()) GROUP BY g.gender_name;
How many public service requests were fulfilled for persons with disabilities in Q1 and Q2 of 2022?
CREATE TABLE Requests(Quarter INT,Group VARCHAR(20),Requests INT); INSERT INTO Requests VALUES (1,'Persons with Disabilities',120),(1,'Seniors',150),(2,'Persons with Disabilities',130),(2,'Seniors',140),(3,'Persons with Disabilities',125),(3,'Seniors',160),(4,'Persons with Disabilities',110),(4,'Seniors',145);
SELECT SUM(Requests) FROM Requests WHERE Quarter IN (1, 2) AND Group = 'Persons with Disabilities';
What is the average time taken for each train line in Paris to complete a route?
CREATE TABLE trains (route_id INT,time INT,line VARCHAR(10)); CREATE TABLE routes (route_id INT,line VARCHAR(10));
SELECT r.line, AVG(t.time) FROM trains t JOIN routes r ON t.route_id = r.route_id GROUP BY r.line;
What is the population size in Oceania countries in 2018?
CREATE TABLE Population (Country VARCHAR(50),Continent VARCHAR(50),Year INT,PopulationSize INT); INSERT INTO Population (Country,Continent,Year,PopulationSize) VALUES ('Australia','Oceania',2018,25000000),('New Zealand','Oceania',2018,4900000);
SELECT Country, Continent, PopulationSize FROM Population WHERE Continent = 'Oceania' AND Year = 2018;
Update the safety certifications of products manufactured in France to true.
CREATE TABLE products (product_id TEXT,country TEXT,safety_certified BOOLEAN); INSERT INTO products (product_id,country,safety_certified) VALUES ('XYZ-123','France',FALSE),('ABC-456','Germany',TRUE);
UPDATE products SET safety_certified = TRUE WHERE country = 'France';
What is the total revenue for 'non-AI' hotel bookings on 'Booking.com' in 'Paris'?
CREATE TABLE Revenue (booking_id INT,ota TEXT,city TEXT,booking_type TEXT,revenue FLOAT); INSERT INTO Revenue (booking_id,ota,city,booking_type,revenue) VALUES (1,'Booking.com','Paris','non-AI',100),(2,'Booking.com','Paris','AI',120),(3,'Booking.com','Paris','non-AI',80);
SELECT SUM(revenue) FROM Revenue WHERE ota = 'Booking.com' AND city = 'Paris' AND booking_type = 'non-AI';
Find the average ESG score for investments in the technology sector in Q1 2021
CREATE TABLE investments (id INT,sector VARCHAR(20),esg_score FLOAT,investment_date DATE); INSERT INTO investments (id,sector,esg_score,investment_date) VALUES (1,'technology',78.5,'2021-01-10'); INSERT INTO investments (id,sector,esg_score,investment_date) VALUES (2,'technology',82.3,'2021-03-22');
SELECT AVG(esg_score) FROM investments WHERE sector = 'technology' AND investment_date BETWEEN '2021-01-01' AND '2021-03-31';
Delete all records of stations without wheelchair accessibility from the Red Line.
CREATE TABLE Stations (line VARCHAR(20),station VARCHAR(20),accessibility BOOLEAN); INSERT INTO Stations (line,station,accessibility) VALUES ('Red Line','Park Street',true),('Red Line','Downtown Crossing',false);
DELETE FROM Stations WHERE line = 'Red Line' AND accessibility = false;
What is the minimum textile sourcing cost for a specific fabric type?
CREATE TABLE textile_sourcing (id INT,item_id INT,fabric TEXT,cost DECIMAL);
SELECT MIN(cost) FROM textile_sourcing WHERE fabric = 'silk';
What is the maximum number of astronauts carried by each spacecraft to the International Space Station?
CREATE TABLE iss_spacecraft (spacecraft_name VARCHAR(255),max_astronauts INT); INSERT INTO iss_spacecraft (spacecraft_name,max_astronauts) VALUES ('Space Shuttle',8); INSERT INTO iss_spacecraft (spacecraft_name,max_astronauts) VALUES ('Soyuz',3);
SELECT spacecraft_name, MAX(max_astronauts) FROM iss_spacecraft;
Delete all records of traditional shared bikes in Los Angeles from the shared_bikes table.
CREATE TABLE shared_bikes (bike_id INT,city VARCHAR(20),is_electric BOOLEAN); INSERT INTO shared_bikes (bike_id,city,is_electric) VALUES (1,'New York',true),(2,'Chicago',true),(3,'Los Angeles',false);
DELETE FROM shared_bikes WHERE city = 'Los Angeles' AND is_electric = false;
Who are the community health workers serving the Hispanic population?
CREATE TABLE community_health_workers (worker_id INT,name VARCHAR(50),ethnicity VARCHAR(20)); INSERT INTO community_health_workers (worker_id,name,ethnicity) VALUES (1,'Ana Garcia','Hispanic'),(2,'Juan Hernandez','Hispanic'),(3,'Mark Johnson','Non-Hispanic');
SELECT * FROM community_health_workers WHERE ethnicity = 'Hispanic';
How many marine protected areas are there in the Atlantic Ocean?
CREATE TABLE marine_protected_areas (name text,location text); INSERT INTO marine_protected_areas (name,location) VALUES ('Galapagos Islands','Pacific Ocean'),('Great Barrier Reef','Atlantic Ocean');
SELECT COUNT(*) FROM marine_protected_areas WHERE location = 'Atlantic Ocean';
What is the total donation amount by week for the last year?
CREATE TABLE donations (id INT,donation_amount DECIMAL,donation_date DATE); INSERT INTO donations (id,donation_amount,donation_date) VALUES (1,100.00,'2022-01-01'),(2,200.00,'2022-05-05');
SELECT DATE_FORMAT(donation_date, '%Y-%u') as donation_week, SUM(donation_amount) as total_donations FROM donations WHERE donation_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY donation_week ORDER BY donation_week;
Update the category of artwork with ID 3 to 'Drawing'
CREATE TABLE artworks (id INT,artist TEXT,category TEXT); INSERT INTO artworks (id,artist,category) VALUES (1,'Van Gogh','Painting'),(2,'Van Gogh','Drawing'),(3,'Monet','Painting'),(4,'Monet','Painting');
UPDATE artworks SET category = 'Drawing' WHERE id = 3;
List the names and delivery times of all shipments that were sent by air from China to the United Kingdom.
CREATE TABLE Shipments(id INT,mode VARCHAR(50),source VARCHAR(50),destination VARCHAR(50),delivery_time DATE); INSERT INTO Shipments(id,mode,source,destination,delivery_time) VALUES (1,'air','China','United Kingdom','2022-02-01');
SELECT Shipments.mode, Shipments.source, Shipments.destination, Shipments.delivery_time FROM Shipments WHERE Shipments.mode = 'air' AND Shipments.source = 'China' AND Shipments.destination = 'United Kingdom';
Who are the top 5 most prolific female authors?
CREATE TABLE author (author_id INT,author_name VARCHAR(50),gender VARCHAR(10)); INSERT INTO author (author_id,author_name,gender) VALUES (1,'Alice Johnson','Female'),(2,'Bob Smith','Male'),(3,'Carla Garcia','Female'); CREATE TABLE book (book_id INT,author_id INT,book_name VARCHAR(50)); INSERT INTO book (book_id,author_...
SELECT author_name, COUNT(*) as num_books FROM book JOIN author ON book.author_id = author.author_id WHERE gender = 'Female' GROUP BY author_name ORDER BY num_books DESC LIMIT 5;
How many cases were handled by attorney 'Carlos García'?
CREATE TABLE cases (case_id INT,attorney_id INT,category VARCHAR(50),billing_amount INT); INSERT INTO cases (case_id,attorney_id,category,billing_amount) VALUES (1,1,'Personal Injury',5000),(2,2,'Civil Litigation',7000),(3,3,'Personal Injury',6000),(4,3,'Civil Litigation',8000);
SELECT SUM(billing_amount) FROM cases WHERE attorney_id = (SELECT attorney_id FROM attorneys WHERE name = 'Carlos García');
Insert new records into the traditional_foods table with the following data: (1, 'Potato', 'Peru'), (2, 'Ramen', 'Japan'), (3, 'Tacos', 'Mexico').
CREATE TABLE traditional_foods (id INT,food VARCHAR(50),country VARCHAR(50));
INSERT INTO traditional_foods (id, food, country) VALUES (1, 'Potato', 'Peru'), (2, 'Ramen', 'Japan'), (3, 'Tacos', 'Mexico');
Update the name of renewable energy projects with 'Plant' in the name to 'Renewable Energy Plant'.
CREATE TABLE Renewable_Energy_Projects (id INT,project_name VARCHAR(50),country VARCHAR(50)); INSERT INTO Renewable_Energy_Projects (id,project_name,country) VALUES (1,'Solar Plant','USA'),(2,'Wind Farm','Canada'),(3,'Hydroelectric Dam','Mexico');
UPDATE Renewable_Energy_Projects SET project_name = 'Renewable Energy Plant' WHERE project_name LIKE '%Plant%';
Find the top 3 states with the highest number of hospitals.
CREATE TABLE Hospitals (HospitalID INT,HospitalName VARCHAR(50),State VARCHAR(20),NumberOfBeds INT); INSERT INTO Hospitals (HospitalID,HospitalName,State,NumberOfBeds) VALUES (1,'Rural General Hospital','California',75); INSERT INTO Hospitals (HospitalID,HospitalName,State,NumberOfBeds) VALUES (2,'Mountain View Medical...
SELECT State, COUNT(*) AS NumberOfHospitals FROM Hospitals GROUP BY State ORDER BY NumberOfHospitals DESC LIMIT 3;
What is the total number of certified eco-friendly accommodations in each continent?
CREATE TABLE certifications (id INT,accommodation_id INT,continent TEXT); INSERT INTO certifications (id,accommodation_id,continent) VALUES (1,1,'Americas'),(2,2,'Europe'); CREATE TABLE accommodations (id INT,name TEXT,continent TEXT); INSERT INTO accommodations (id,name,continent) VALUES (1,'Eco Lodge','North America'...
SELECT c.continent, COUNT(*) FROM certifications c JOIN accommodations a ON c.accommodation_id = a.id GROUP BY c.continent;
Insert a new record for the heritage site 'Taj Mahal' into the HeritageSites table.
CREATE TABLE HeritageSites (SiteID INT,SiteName VARCHAR(100),Location VARCHAR(100),Visits INT);
INSERT INTO HeritageSites (SiteID, SiteName, Location, Visits) VALUES (2, 'Taj Mahal', 'India', 8000000);
What is the average age of patients who received dental care in 2021 in the state of Alabama?
CREATE TABLE DentalCare (patientID INT,age INT,state VARCHAR(20)); INSERT INTO DentalCare (patientID,age,state) VALUES (1,45,'Alabama'),(2,32,'Alabama'),(3,50,'Alabama');
SELECT AVG(age) FROM DentalCare WHERE state = 'Alabama' AND YEAR(datetime) = 2021 AND type_of_care = 'dental';
How many vessels have a type of 'Cargo' and have been inspected in the last month?
CREATE TABLE Vessel (vessel_id INT,name VARCHAR(255),type VARCHAR(255),max_speed DECIMAL(5,2)); CREATE TABLE Inspection (inspection_id INT,vessel_id INT,inspection_time TIMESTAMP); INSERT INTO Vessel (vessel_id,name,type,max_speed) VALUES (1,'Test Vessel 1','Cargo',20.5),(2,'Test Vessel 2','Tanker',15.2),(3,'Test Vesse...
SELECT COUNT(*) FROM Vessel v INNER JOIN Inspection i ON v.vessel_id = i.vessel_id WHERE v.type = 'Cargo' AND i.inspection_time >= NOW() - INTERVAL '1 month';
List the names, ZIP codes, and average account balances for customers who have a socially responsible loan?
CREATE TABLE socially_responsible_loans (loan_id INT,customer_name TEXT,customer_zip INT,account_balance DECIMAL); CREATE TABLE socially_responsible_lending (lending_id INT,loan_id INT);
SELECT srl.customer_name, srl.customer_zip, AVG(srl.account_balance) FROM socially_responsible_loans srl JOIN socially_responsible_lending srlg ON srl.loan_id = srlg.loan_id GROUP BY srl.customer_name, srl.customer_zip;
List the names of startups that have not yet had an exit event and were founded by underrepresented racial/ethnic groups.
CREATE TABLE Startups (id INT,name VARCHAR(100),exit_event BOOLEAN); CREATE TABLE Founders (id INT,startup_id INT,race VARCHAR(50)); INSERT INTO Startups (id,name,exit_event) VALUES (1,'Heal',FALSE),(2,'VirtuSense',TRUE),(3,'Clinico',FALSE); INSERT INTO Founders (id,startup_id,race) VALUES (1,1,'African American'),(2,1...
SELECT s.name FROM Startups s JOIN Founders f ON s.id = f.startup_id WHERE s.exit_event = FALSE AND f.race IN ('African American', 'Hispanic', 'Native American', 'Pacific Islander', 'South Asian', 'Other');
Find the destination with the lowest carbon footprint in Asia.
CREATE TABLE IF NOT EXISTS carbon_footprint (id INT PRIMARY KEY,name TEXT,region TEXT,carbon_footprint FLOAT); INSERT INTO carbon_footprint (id,name,region,carbon_footprint) VALUES (1,'EcoResort','Asia',12.5),(2,'GreenParadise','Asia',11.3),(3,'SustainableCity','Europe',10.9);
SELECT name FROM carbon_footprint WHERE region = 'Asia' ORDER BY carbon_footprint ASC LIMIT 1;
What is the total amount of transactions per client for clients from Spain?
CREATE TABLE clients (client_id INT,client_name VARCHAR(100),country VARCHAR(50)); INSERT INTO clients (client_id,client_name,country) VALUES (1,'John Doe','Spain'); INSERT INTO clients (client_id,client_name,country) VALUES (2,'Jane Doe','France'); CREATE TABLE transactions (transaction_id INT,client_id INT,amount DEC...
SELECT c.client_name, SUM(t.amount) FROM clients c JOIN transactions t ON c.client_id = t.client_id WHERE c.country = 'Spain' GROUP BY c.client_name;
What is the total construction cost and the number of permits issued for each project type per month in the 'Projects', 'BuildingPermits', and 'GreenBuildings' tables?
CREATE TABLE Projects (projectID INT,projectType VARCHAR(50),totalCost DECIMAL(10,2),sqft DECIMAL(10,2));CREATE TABLE BuildingPermits (permitID INT,projectID INT,permitDate DATE);CREATE TABLE GreenBuildings (projectID INT,sustainableMaterial VARCHAR(50),sustainableMaterialCost DECIMAL(10,2));
SELECT P.projectType, DATE_FORMAT(permitDate, '%Y-%m') AS Month, SUM(P.totalCost)/SUM(P.sqft) AS CostPerSqft, COUNT(B.permitID) AS PermitsIssued FROM Projects P INNER JOIN BuildingPermits B ON P.projectID = B.projectID LEFT JOIN GreenBuildings GB ON P.projectID = GB.projectID GROUP BY P.projectType, Month;
What is the total number of meals served in the last month, broken down by day of the week?
CREATE TABLE orders (id INT,date DATE,meals INT);
SELECT DATE_FORMAT(date, '%W') as day_of_week, SUM(meals) as total_meals FROM orders WHERE date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND CURRENT_DATE GROUP BY day_of_week;
Delete all records from the 'activities' table that are over 2 years old.
CREATE TABLE activities (id INT,volunteer_id INT,activity_date DATE); INSERT INTO activities (id,volunteer_id,activity_date) VALUES (1,1,'2020-01-01'),(2,1,'2019-12-31'),(3,2,'2021-06-01'),(4,2,'2020-12-31');
DELETE FROM activities WHERE activity_date < (CURRENT_DATE - INTERVAL '2 years');
What is the maximum price of a product made with recycled materials?
CREATE TABLE products (product_id INT,is_recycled BOOLEAN,price DECIMAL(5,2)); INSERT INTO products (product_id,is_recycled,price) VALUES (1,true,75.99),(2,false,60.00),(3,true,85.00);
SELECT MAX(price) FROM products WHERE is_recycled = true;
How many individuals have participated in restorative justice programs in the past year, grouped by their age and gender?
CREATE TABLE restorative_justice_participants (id INT,age INT,gender TEXT,program_date DATE);
SELECT age, gender, COUNT(*) FROM restorative_justice_participants WHERE program_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY age, gender;
How many fish were harvested from marine fish farms in each country in the last month?
CREATE TABLE country_codes (country TEXT,code TEXT); INSERT INTO country_codes (country,code) VALUES ('Norway','NO'),('Canada','CA'); CREATE TABLE fish_harvest (id INT,name TEXT,type TEXT,location TEXT,harvest_quantity INT,country TEXT); INSERT INTO fish_harvest (id,name,type,location,harvest_quantity,country) VALUES (...
SELECT country, COUNT(*) FROM fish_harvest JOIN country_codes ON fish_harvest.country = country_codes.code GROUP BY country;
Find the maximum number of attendees in virtual tours across Asian countries, in the last 6 months.
CREATE TABLE virtual_tours (id INT,location TEXT,attendees INT,tour_date DATE); INSERT INTO virtual_tours (id,location,attendees,tour_date) VALUES (1,'Tokyo',25,'2022-01-01'),(2,'Seoul',30,'2022-02-10');
SELECT MAX(attendees) FROM virtual_tours WHERE location LIKE '%Asia%' AND tour_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH);
What is the average temperature change in the Arctic per year since 1990?
CREATE TABLE weather_data (year INT,location VARCHAR(50),temperature FLOAT);
SELECT AVG(temperature_change) FROM (SELECT (temperature - LAG(temperature) OVER (ORDER BY year)) AS temperature_change FROM weather_data WHERE year >= 1990) AS subquery;
Update the names of players who are from 'Japan' and use PlayStation VR to 'PSVR Japanese Players'.
CREATE TABLE Players (PlayerID INT,Name VARCHAR(20),Country VARCHAR(20),VRPlatform VARCHAR(10)); INSERT INTO Players (PlayerID,Name,Country,VRPlatform) VALUES (1,'Hiroshi','Japan','PlayStation VR');
UPDATE Players SET Name = 'PSVR Japanese Players' WHERE Country = 'Japan' AND VRPlatform = 'PlayStation VR';
How many bridges are there in the region of Andalusia, Spain?
CREATE TABLE Bridges (BridgeID INT,Name TEXT,Length FLOAT,Region TEXT,Country TEXT); INSERT INTO Bridges (BridgeID,Name,Length,Region,Country) VALUES (1,'Bridge1',500.5,'Andalusia','Spain'); INSERT INTO Bridges (BridgeID,Name,Length,Region,Country) VALUES (2,'Bridge2',600.6,'Andalusia','Spain'); INSERT INTO Bridges (Br...
SELECT COUNT(*) FROM Bridges WHERE Region = 'Andalusia';
List the conditions treated in Community Center A that required medication for more than 30% of the patients.
CREATE TABLE conditions (id INT,name VARCHAR(255)); INSERT INTO conditions (id,name) VALUES (1,'Anxiety'),(2,'Depression'),(3,'Bipolar Disorder'); CREATE TABLE treatments (id INT,community_center_id INT,patient_id INT,condition_id INT,type VARCHAR(255)); INSERT INTO treatments (id,community_center_id,patient_id,conditi...
SELECT c.name, AVG(t.type = 'medication') as medication_percentage FROM treatments t JOIN conditions c ON t.condition_id = c.id WHERE t.community_center_id = 1 GROUP BY c.name HAVING AVG(t.type = 'medication') > 0.3;
List all sustainable building practices in the state of Washington
CREATE TABLE sustainable_practices (practice_id INT,building_type VARCHAR(20),state VARCHAR(20),description TEXT); INSERT INTO sustainable_practices (practice_id,building_type,state,description) VALUES (1,'Residential','WA','Use of recycled materials');
SELECT * FROM sustainable_practices WHERE state = 'WA';
Identify the top 3 customers with the highest total freight costs in Africa.
CREATE TABLE Customer_Freight_Costs (id INT,freight_date DATETIME,freight_country VARCHAR(50),customer_id INT,freight_cost DECIMAL(10,2)); INSERT INTO Customer_Freight_Costs (id,freight_date,freight_country,customer_id,freight_cost) VALUES (1,'2022-01-01','South Africa',1,500.00),(2,'2022-01-02','Egypt',2,600.00),(3,'2...
SELECT customer_id, SUM(freight_cost) AS total_cost FROM Customer_Freight_Costs WHERE freight_country IN ('South Africa', 'Egypt', 'Nigeria', 'Algeria', 'Morocco') GROUP BY customer_id ORDER BY total_cost DESC LIMIT 3;
What is the maximum speed in knots for the vessel 'OceanWanderer'?
CREATE TABLE Vessels(Id INT,Name VARCHAR(255),AverageSpeed DECIMAL(5,2)); INSERT INTO Vessels VALUES (1,'VesselA',15.5),(2,'VesselB',18.3),(3,'OceanWanderer',20.2);
SELECT MAX(v.AverageSpeed) FROM Vessels v WHERE v.Name = 'OceanWanderer';
What is the total cost of ingredients for the 'Veggie Burger' for the month of April 2022?
CREATE TABLE Ingredients (ingredient_id INT,ingredient_name TEXT,dish_id INT,cost FLOAT); INSERT INTO Ingredients (ingredient_id,ingredient_name,dish_id,cost) VALUES (1,'Veggie Patty',2,2.5);
SELECT SUM(cost) FROM Ingredients WHERE dish_id IN (SELECT dish_id FROM Dishes WHERE dish_name = 'Veggie Burger') AND ingredient_name NOT IN ('Lettuce', 'Tomato', 'Bun');
What is the average number of disaster response incidents in the Middle East?
CREATE TABLE disasters (id INT,type TEXT,location TEXT,year INT); INSERT INTO disasters (id,type,location,year) VALUES (1,'Flood','South America',2020),(2,'Earthquake','Asia',2019),(3,'Tornado','North America',2020),(4,'Disaster Response','Middle East',2018),(5,'Disaster Response','Middle East',2019),(6,'Disaster Respo...
SELECT AVG(total_disasters) FROM (SELECT location, COUNT(*) AS total_disasters FROM disasters WHERE type = 'Disaster Response' AND location = 'Middle East' GROUP BY location, year) AS disaster_counts GROUP BY location;
What is the sum of the scores for players who joined before 2021 in the game 'Retro Racers'?
CREATE TABLE Retro_Racers (player_id INT,player_name VARCHAR(50),score INT,join_date DATE); INSERT INTO Retro_Racers (player_id,player_name,score,join_date) VALUES (1,'Anna Nguyen',100,'2020-05-05'),(2,'Ben Park',120,'2021-01-01'),(3,'Clara Lee',90,'2019-12-31');
SELECT SUM(score) FROM Retro_Racers WHERE join_date < '2021-01-01';
Show the average energy efficiency rating for each building type in the buildings and energy_efficiency tables.
CREATE TABLE buildings(id INT,building_name VARCHAR(50),building_type VARCHAR(50));CREATE TABLE energy_efficiency(building_id INT,rating INT);
SELECT b.building_type, AVG(e.rating) AS avg_rating FROM buildings b INNER JOIN energy_efficiency e ON b.id = e.building_id GROUP BY b.building_type;
How many fans attended basketball games in the Southeast in Q1 2022?
CREATE TABLE quarters (id INT,name VARCHAR(255)); INSERT INTO quarters (id,name) VALUES (1,'Q1'),(2,'Q2'),(3,'Q3'),(4,'Q4'); CREATE TABLE regions (id INT,name VARCHAR(255)); INSERT INTO regions (id,name) VALUES (1,'Northeast'),(2,'Southeast'),(3,'Midwest'),(4,'West'); CREATE TABLE games (id INT,region_id INT,quarter_id...
SELECT SUM(g.attendees) as total_attendees FROM games g JOIN regions r ON g.region_id = r.id JOIN quarters q ON g.quarter_id = q.id WHERE g.sport_id = 1 AND r.name = 'Southeast' AND q.name = 'Q1';
What is the average response time to security incidents for non-profit organizations in Q2 2022, grouped by region?
CREATE TABLE security_incidents (id INT,organization TEXT,region TEXT,incident_date DATE,response_time INT); INSERT INTO security_incidents (id,organization,region,incident_date,response_time) VALUES (1,'Non-profit A','Asia','2022-06-20',150); INSERT INTO security_incidents (id,organization,region,incident_date,respons...
SELECT region, AVG(response_time) FROM security_incidents WHERE organization LIKE '%Non-profit%' AND incident_date >= '2022-04-01' AND incident_date < '2022-07-01' GROUP BY region;