instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the total budget for programs with a program type of 'Youth' or 'Education', ordered by the total budget in descending order.
CREATE TABLE programs (id INT,budget INT,program_type VARCHAR(20)); INSERT INTO programs (id,budget,program_type) VALUES (1,120000,'Education'),(2,50000,'Health'),(3,80000,'Arts'),(4,90000,'Youth');
SELECT ROW_NUMBER() OVER (ORDER BY SUM(budget) DESC) AS record_id, SUM(budget) AS total_budget FROM programs WHERE program_type IN ('Youth', 'Education') GROUP BY program_type;
What is the total military equipment sale value for each sales representative in Q1 2020, ranked by total sales?
CREATE TABLE Sales_Data (sales_rep VARCHAR(255),sale_date DATE,equipment_type VARCHAR(255),country VARCHAR(255),sale_value FLOAT); INSERT INTO Sales_Data (sales_rep,sale_date,equipment_type,country,sale_value) VALUES ('Alex Garcia','2020-01-02','Aircraft','Brazil',7000000),('Alex Garcia','2020-01-15','Armored Vehicles','Brazil',2000000),('Taylor Lee','2020-01-05','Naval Vessels','South Korea',9000000),('Taylor Lee','2020-01-25','Missiles','South Korea',4000000);
SELECT sales_rep, SUM(sale_value) AS total_sales, RANK() OVER (ORDER BY SUM(sale_value) DESC) AS sales_rank FROM Sales_Data WHERE sale_date BETWEEN '2020-01-01' AND '2020-03-31' GROUP BY sales_rep;
What is the average donation amount per volunteer for the 'Helping Hands' program?
CREATE TABLE Donations (id INT,donor_name VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE,donor_program VARCHAR(50));
SELECT AVG(Donations.donation_amount) FROM Donations INNER JOIN (SELECT id, total_volunteers FROM Programs WHERE program_name = 'Helping Hands') AS ProgramVolunteers ON 1=1 WHERE Donations.donor_program = ProgramVolunteers.id;
Show the total revenue for each game in 'InGamePurchases' table
CREATE TABLE InGamePurchases (GameID INT,GameName VARCHAR(50),PurchaseAmount DECIMAL(10,2));
SELECT GameID, SUM(PurchaseAmount) as TotalRevenue FROM InGamePurchases GROUP BY GameID;
What is the maximum number of mental health parity cases by state?
CREATE TABLE mental_health_parity (state VARCHAR(255),cases INT); INSERT INTO mental_health_parity (state,cases) VALUES ('California',500),('New York',600),('Texas',450),('Florida',400);
SELECT state, MAX(cases) FROM mental_health_parity GROUP BY state;
How many crime incidents were reported per month in Seattle in 2021?"
CREATE TABLE crime_incidents (id INT,incident_type VARCHAR(255),city VARCHAR(255),incident_date DATE); INSERT INTO crime_incidents (id,incident_type,city,incident_date) VALUES (1,'Theft','Seattle','2021-01-15');
SELECT DATE_FORMAT(incident_date, '%Y-%m') AS Month, COUNT(*) as total FROM crime_incidents WHERE city = 'Seattle' AND incident_date >= '2021-01-01' AND incident_date < '2022-01-01' GROUP BY Month;
Find the maximum financial wellbeing score for Latin America.
CREATE TABLE financial_wellbeing (id INT,person_id INT,country VARCHAR(255),score FLOAT); INSERT INTO financial_wellbeing (id,person_id,country,score) VALUES (1,123,'Brazil',78.5),(2,456,'Mexico',82.3),(3,789,'Colombia',65.4);
SELECT MAX(score) FROM financial_wellbeing WHERE country = 'Latin America';
What is the average volume of timber produced per country by species in 2020?
CREATE TABLE country (id INT,name VARCHAR(255)); INSERT INTO country (id,name) VALUES (1,'USA'),(2,'Canada'),(3,'Brazil'); CREATE TABLE species (id INT,name VARCHAR(255)); INSERT INTO species (id,name) VALUES (1,'Pine'),(2,'Oak'),(3,'Maple'); CREATE TABLE timber_production (country_id INT,species_id INT,year INT,volume INT); INSERT INTO timber_production (country_id,species_id,year,volume) VALUES (1,1,2020,1200),(1,2,2020,1500),(2,1,2020,1800),(2,3,2020,900),(3,2,2020,1200),(3,3,2020,1000);
SELECT c.name as country, s.name as species, AVG(tp.volume) as avg_volume FROM timber_production tp JOIN country c ON tp.country_id = c.id JOIN species s ON tp.species_id = s.id WHERE tp.year = 2020 GROUP BY c.name, s.name;
What is the maximum ocean acidification level recorded in the Arctic Ocean?
CREATE TABLE ocean_acidification (location_id INT,location VARCHAR(100),level FLOAT); INSERT INTO ocean_acidification (location_id,location,level) VALUES (1,'Pacific Ocean',8.2); INSERT INTO ocean_acidification (location_id,location,level) VALUES (2,'Atlantic Ocean',7.9); INSERT INTO ocean_acidification (location_id,location,level) VALUES (3,'Arctic Ocean',7.8);
SELECT MAX(level) FROM ocean_acidification WHERE location = 'Arctic Ocean';
Update the address of a customer in the 'customers' table
CREATE TABLE customers (customer_id INT,first_name VARCHAR(255),last_name VARCHAR(255),email VARCHAR(255),address VARCHAR(255));
UPDATE customers SET address = '123 Maple Street, Apt. 4' WHERE customer_id = 1001;
What's the average budget for comedy movies released between 2010 and 2015?
CREATE TABLE movies (title VARCHAR(255),genre VARCHAR(50),budget INT,release_year INT); INSERT INTO movies (title,genre,budget,release_year) VALUES ('Movie1','Comedy',20000000,2010),('Movie2','Comedy',30000000,2012),('Movie3','Drama',40000000,2015);
SELECT AVG(budget) FROM movies WHERE genre = 'Comedy' AND release_year BETWEEN 2010 AND 2015;
What is the average cost of sustainable building materials in the 'west' region?
CREATE TABLE sustainable_materials (id INT,material_name TEXT,cost FLOAT,region TEXT); INSERT INTO sustainable_materials (id,material_name,cost,region) VALUES (1,'Bamboo Flooring',12.50,'west'),(2,'Recycled Steel',35.00,'east');
SELECT AVG(cost) FROM sustainable_materials WHERE region = 'west';
What are the names and quantities of weapons sold to Canada in the year 2020?
CREATE TABLE WeaponsSales (id INT,weapon VARCHAR(255),quantity INT,country VARCHAR(255),sale_date DATE);
SELECT weapon, quantity FROM WeaponsSales WHERE country = 'Canada' AND sale_date BETWEEN '2020-01-01' AND '2020-12-31';
What is the average food safety inspection score for restaurants in NYC?
CREATE TABLE food_safety_inspections (restaurant_id INT,restaurant_name VARCHAR(255),city VARCHAR(255),inspection_score INT); INSERT INTO food_safety_inspections (restaurant_id,restaurant_name,city,inspection_score) VALUES (1,'Pizzeria Roma','NYC',95),(2,'Taqueria Mexico','LA',85);
SELECT AVG(inspection_score) as avg_inspection_score FROM food_safety_inspections WHERE city = 'NYC';
What is the moving average of sales revenue for each region, partitioned by the region and ordered by the date of the sales?
CREATE TABLE Regions (RegionID INT,RegionName VARCHAR(255));CREATE TABLE Garments (GarmentID INT,RegionID INT,SalePrice DECIMAL(10,2));CREATE TABLE Sales (SaleID INT,GarmentID INT,SaleDate DATE,Quantity INT);
SELECT r.RegionName, AVG(g.SalePrice * s.Quantity) OVER (PARTITION BY r.RegionName ORDER BY s.SaleDate ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS MovingAverageRevenue FROM Regions r JOIN Garments g ON r.RegionID = g.RegionID JOIN Sales s ON g.GarmentID = s.GarmentID ORDER BY s.SaleDate;
What is the average block time on the Solana network?
CREATE TABLE solana_network (network_name VARCHAR(20),block_time TIME); INSERT INTO solana_network (network_name,block_time) VALUES ('Solana','0.427s');
SELECT AVG(TIME_TO_SEC(block_time)) FROM solana_network WHERE network_name = 'Solana';
What is the total installed capacity in MW for wind energy projects in the 'renewables' schema, for projects with a capacity greater than or equal to 100 MW?
CREATE SCHEMA renewables; CREATE TABLE wind_projects (id INT,technology VARCHAR(50),capacity FLOAT,status VARCHAR(50)); INSERT INTO renewables.wind_projects (id,technology,capacity,status) VALUES (1,'Wind Turbine',120.0,'Operational'),(2,'Wind Farm',150.0,'Operational'),(3,'Offshore Wind',200.0,'Operational'),(4,'Wind Turbine',90.0,'Under Construction'),(5,'Wind Farm',110.0,'Under Construction');
SELECT SUM(capacity) as total_capacity FROM renewables.wind_projects WHERE capacity >= 100;
What is the average professional development course rating by teachers in the same country?
CREATE TABLE teachers (teacher_id INT,name VARCHAR(20),country_id INT); INSERT INTO teachers (teacher_id,name,country_id) VALUES (1,'John',1),(2,'Sarah',1),(3,'Pedro',2),(4,'Ana',2); CREATE TABLE courses (course_id INT,name VARCHAR(20),rating INT,professional_development BOOLEAN); INSERT INTO courses (course_id,name,rating,professional_development) VALUES (1,'Python',4,true),(2,'Data Science',5,true),(3,'History',3,false); CREATE TABLE teacher_courses (teacher_id INT,course_id INT,rating INT); INSERT INTO teacher_courses (teacher_id,course_id,rating) VALUES (1,1,4),(1,2,5),(2,1,5),(2,2,5),(3,1,4),(3,2,4),(4,1,3),(4,2,3); CREATE TABLE countries (country_id INT,name VARCHAR(20)); INSERT INTO countries (country_id,name) VALUES (1,'USA'),(2,'Brazil');
SELECT AVG(tc.rating) as avg_rating, t.country_id, c.name as country_name FROM teacher_courses tc JOIN teachers t ON tc.teacher_id = t.teacher_id JOIN courses c ON tc.course_id = c.course_id JOIN countries ON t.country_id = countries.country_id WHERE c.professional_development = true GROUP BY t.country_id, c.name;
What is the total fare collected for each month?
CREATE TABLE trip (trip_id INT,fare DECIMAL(10,2),trip_date DATE); INSERT INTO trip (trip_id,fare,trip_date) VALUES (1,2.00,'2022-01-01'),(2,3.00,'2022-01-02'),(3,4.00,'2022-02-01'),(4,5.00,'2022-02-02');
SELECT EXTRACT(MONTH FROM trip_date) AS month, SUM(fare) AS total_fare FROM trip GROUP BY month;
How many units were sold in each product category, by month?
CREATE TABLE product_sales (id INT,category VARCHAR(255),year INT,month INT,units_sold INT); INSERT INTO product_sales (id,category,year,month,units_sold) VALUES (1,'Electronics',2022,1,200),(2,'Clothing',2022,1,300),(3,'Books',2022,1,100),(4,'Toys',2022,1,400),(1,'Electronics',2022,2,300),(2,'Clothing',2022,2,400),(3,'Books',2022,2,200),(4,'Toys',2022,2,500);
SELECT category, month, SUM(units_sold) FROM product_sales GROUP BY category, month;
How many students have improved their mental health scores by at least 10 points in the past 6 months?
CREATE TABLE students (student_id INT,mental_health_score INT,improvement_6months INT); INSERT INTO students (student_id,mental_health_score,improvement_6months) VALUES (1,60,15),(2,70,0),(3,50,8),(4,80,-3),(5,40,12);
SELECT COUNT(student_id) FROM students WHERE improvement_6months >= 10;
Find the total installed solar capacity (MW) in Texas and Alaska as of 2020-01-01.
CREATE TABLE solar_farms (name TEXT,state TEXT,capacity FLOAT,install_date DATE); INSERT INTO solar_farms (name,state,capacity,install_date) VALUES ('Permian Energy Center','Texas',250.0,'2019-12-31'),('Solrenova Solar Farm','Alaska',50.0,'2020-01-02');
SELECT SUM(capacity) FROM solar_farms WHERE state IN ('Texas', 'Alaska') AND install_date <= '2020-01-01';
Find the number of projects and their total cost for each scheme, excluding the "Mitigation" scheme.
CREATE TABLE Projects (scheme VARCHAR(255),cost FLOAT); INSERT INTO Projects VALUES ('Mitigation',1000.0),('Adaptation',1500.0),('Finance',2000.0),('Communication',2500.0);
SELECT scheme, COUNT(*), SUM(cost) FROM Projects WHERE scheme != 'Mitigation' GROUP BY scheme
What is the average playtime for games in the 'Strategy' genre that were released in 2020?
CREATE TABLE GamePlayTimes (PlayerID INT,GameID INT,PlayTime INT); INSERT INTO GamePlayTimes (PlayerID,GameID,PlayTime) VALUES (1,1,60),(1,2,90),(2,3,120),(2,4,150),(3,5,180),(3,1,210),(3,6,240);
SELECT AVG(PlayTime) FROM GamePlayTimes INNER JOIN Games ON GamePlayTimes.GameID = Games.GameID WHERE ReleaseDate >= '2020-01-01' AND ReleaseDate < '2021-01-01' AND Category = 'Strategy';
What is the average data usage for each region in the last week?
CREATE TABLE mobile_subscribers (subscriber_id INT,data_usage FLOAT,plan_type VARCHAR(10),region VARCHAR(20),data_usage_date DATE); INSERT INTO mobile_subscribers (subscriber_id,data_usage,plan_type,region,data_usage_date) VALUES (1,3.5,'postpaid','Urban','2022-04-15'),(2,6.2,'postpaid','Rural','2022-04-16'),(3,8.1,'prepaid','Rural','2022-04-17'),(4,12.3,'postpaid','Urban','2022-04-18'),(5,18.5,'postpaid','Urban','2022-04-19');
SELECT region, AVG(data_usage) FROM mobile_subscribers WHERE data_usage_date BETWEEN DATEADD(day, -7, CURRENT_DATE) AND CURRENT_DATE GROUP BY region;
Delete all articles with a word count greater than 500 and published before 2010 in the 'Investigative Journalism' category.
CREATE TABLE articles (id INT,title TEXT,word_count INT,published DATE,category TEXT); INSERT INTO articles (id,title,word_count,published,category) VALUES (1,'Article 1',400,'2009-01-01','Investigative Journalism');
DELETE FROM articles WHERE word_count > 500 AND published < '2010-01-01' AND category = 'Investigative Journalism';
Which countries have the highest annual Dysprosium production?
CREATE TABLE DysprosiumProduction(country VARCHAR(50),year INT,production INT); INSERT INTO DysprosiumProduction(country,year,production) VALUES ('China',2018,1200),('USA',2018,350),('Australia',2018,200),('China',2019,1250),('USA',2019,400),('Australia',2019,220);
SELECT country, SUM(production) FROM DysprosiumProduction GROUP BY country ORDER BY SUM(production) DESC LIMIT 3;
Find the total number of temperature measurements taken for each species in the species_measurements table.
CREATE TABLE species_measurements (species_id INT,measurement_date DATE);
SELECT species_id, COUNT(*) FROM species_measurements GROUP BY species_id;
What are the top 5 most common allergens in cosmetic products sold in the Brazilian market, and how many products contain each allergen?
CREATE TABLE cosmetics_ingredients (product_id INT,ingredient TEXT,is_allergen BOOLEAN,country TEXT);
SELECT ingredient, COUNT(*) as num_products_with_allergen FROM cosmetics_ingredients WHERE is_allergen = TRUE AND country = 'Brazil' GROUP BY ingredient ORDER BY num_products_with_allergen DESC LIMIT 5;
Insert records into the 'drought_impact' table for the 'Northeast' region with a 'severity' rating of 'high' and a 'year' of 2022
CREATE TABLE drought_impact (region VARCHAR(20),severity VARCHAR(10),year INT);
INSERT INTO drought_impact (region, severity, year) VALUES ('Northeast', 'high', 2022);
What are the articles and podcasts with the word 'inequality' in the title in the 'media_database'?
CREATE TABLE media_database (id INT,type VARCHAR(10),title VARCHAR(50),length FLOAT,source VARCHAR(50)); INSERT INTO media_database (id,type,title,length,source) VALUES (1,'article','Sample Article on Inequality',5.5,'NPR'); INSERT INTO media_database (id,type,title,length,source) VALUES (2,'podcast','Sample Podcast on Inequality',35.2,'BBC');
SELECT * FROM media_database WHERE (type = 'article' OR type = 'podcast') AND title LIKE '%inequality%';
What are the launch dates of space missions having duration greater than 500 days?
CREATE TABLE space_missions (id INT,name VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO space_missions VALUES (1,'Apollo 11','1969-07-16','1969-07-24'),(2,'Apollo 13','1970-04-11','1970-04-17'),(3,'Mars Pathfinder','1996-12-04','1997-09-27'),(4,'Cassini-Huygens','1997-10-15','2017-09-15');
SELECT name, start_date FROM space_missions WHERE DATEDIFF(end_date, start_date) > 500;
Show the top 3 states with the highest number of Tuberculosis cases in 2019.
CREATE TABLE TBStats (Year INT,State VARCHAR(20),Cases INT); INSERT INTO TBStats (Year,State,Cases) VALUES (2017,'California',1200); INSERT INTO TBStats (Year,State,Cases) VALUES (2019,'Texas',1800); INSERT INTO TBStats (Year,State,Cases) VALUES (2019,'New York',2100);
SELECT State, SUM(Cases) FROM TBStats WHERE Year = 2019 GROUP BY State ORDER BY SUM(Cases) DESC LIMIT 3;
What was the average exhibition duration for artworks in Gallery A, partitioned by artwork type?
CREATE TABLE GalleryA (artwork_ID INT,artwork_type VARCHAR(20),exhibition_duration INT); INSERT INTO GalleryA (artwork_ID,artwork_type,exhibition_duration) VALUES (1,'Painting',45),(2,'Sculpture',60),(3,'Drawing',30);
SELECT artwork_type, AVG(exhibition_duration) as avg_duration FROM (SELECT artwork_ID, artwork_type, exhibition_duration, ROW_NUMBER() OVER (PARTITION BY artwork_type ORDER BY artwork_ID) as rn FROM GalleryA) tmp WHERE rn = 1 GROUP BY artwork_type;
List the programs with budgets that have decreased for at least two consecutive months.
CREATE TABLE programs (program_id INT,program_name VARCHAR(50),budget DECIMAL(10,2),category VARCHAR(50),budget_date DATE);
SELECT program_id, program_name, budget_date FROM (SELECT program_id, program_name, budget, category, budget_date, COUNT(CASE WHEN budget < LAG(budget) OVER (PARTITION BY program_id ORDER BY budget_date) THEN 1 END) OVER (PARTITION BY program_id ORDER BY budget_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as consecutive_decreases FROM programs) t WHERE consecutive_decreases >= 2;
What is the total number of games released in each year, and what is the year with the most game releases?
CREATE TABLE Games (GameID int,GameName varchar(20),Genre varchar(10),ReleaseYear int,VR boolean); INSERT INTO Games (GameID,GameName,Genre,ReleaseYear,VR) VALUES (3,'Game3','Strategy',2015,false); INSERT INTO Games (GameID,GameName,Genre,ReleaseYear,VR) VALUES (4,'Game4','Simulation',2017,true);
SELECT ReleaseYear, COUNT(*) AS GameCount, RANK() OVER (ORDER BY COUNT(*) DESC) AS Rank FROM Games GROUP BY ReleaseYear;
Delete all records from the 'energy_efficiency_stats' table where the 'year' is before 2000
CREATE TABLE energy_efficiency_stats (id INT,year INT,primary_energy_consumption FLOAT,final_energy_consumption FLOAT,primary_energy_production FLOAT,co2_emissions FLOAT);
DELETE FROM energy_efficiency_stats WHERE year < 2000;
List the restaurants that have not been sustainably sourced.
CREATE TABLE sustainable_sourcing (restaurant_id INT,sustainability_rating INT);
SELECT r.restaurant_id, r.name FROM restaurants r LEFT JOIN sustainable_sourcing s ON r.restaurant_id = s.restaurant_id WHERE s.restaurant_id IS NULL;
What are the average hourly wages for construction jobs by gender?
CREATE TABLE labor_stats (id INT,job VARCHAR(50),gender VARCHAR(10),hourly_wage DECIMAL(5,2)); INSERT INTO labor_stats (id,job,gender,hourly_wage) VALUES (1,'Carpenter','Male',25.50),(2,'Electrician','Female',30.00),(3,'Plumber','Male',35.50),(4,'Carpenter','Female',22.00);
SELECT job, AVG(hourly_wage) FROM labor_stats GROUP BY job;
Increase the 'salary' of members in the 'manufacturing' union by 3% who have been part of the union for over 3 years.
CREATE TABLE unions (id INT,name TEXT,industry TEXT); CREATE TABLE members (id INT,union_id INT,joining_date DATE,salary FLOAT); CREATE TABLE union_memberships (member_id INT,union_id INT);
UPDATE members SET salary = salary * 1.03 WHERE union_id IN (SELECT id FROM unions WHERE industry = 'manufacturing') AND joining_date <= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR);
Create a table for storing climate finance data and insert records for international climate finance contributions
CREATE TABLE climate_finance (donor VARCHAR(100),year INT,amount INT);
INSERT INTO climate_finance (donor, year, amount) VALUES ('Germany', 2020, 4000000), ('France', 2019, 3500000), ('Sweden', 2021, 4500000), ('Norway', 2018, 3000000), ('Finland', 2020, 3750000);
What is the carbon sequestration for each forest plot?
CREATE TABLE ForestPlots (PlotID int,PlotName varchar(50)); INSERT INTO ForestPlots VALUES (1,'Plot1'),(2,'Plot2'); CREATE TABLE CarbonSequestration (PlotID int,Sequestration float); INSERT INTO CarbonSequestration VALUES (1,500),(2,600);
SELECT ForestPlots.PlotName, CarbonSequestration.Sequestration FROM ForestPlots INNER JOIN CarbonSequestration ON ForestPlots.PlotID = CarbonSequestration.PlotID;
List the stations that have a passenger count greater than 1500 and a fare greater than 2, based on the 'passenger_counts' and 'route_segments' tables.
CREATE TABLE passenger_counts (station VARCHAR(255),passenger_count INT); CREATE TABLE route_segments (route_id INT,segment_id INT,start_station VARCHAR(255),end_station VARCHAR(255),fare FLOAT,departure_time TIMESTAMP);
SELECT start_station FROM route_segments JOIN passenger_counts ON start_station = station WHERE passenger_count > 1500 AND fare > 2;
What is the total amount donated by donors from the Asia-Pacific region?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,DonationAmount DECIMAL(10,2),Country TEXT); INSERT INTO Donors (DonorID,DonorName,DonationAmount,Country) VALUES (1,'Siti Nurhaliza',100.00,'Malaysia'); INSERT INTO Donors (DonorID,DonorName,DonationAmount,Country) VALUES (2,'Jack Ma',500.00,'China'); INSERT INTO Donors (DonorID,DonorName,DonationAmount,Country) VALUES (3,'Akira Miyazawa',75.00,'Japan');
SELECT SUM(DonationAmount) FROM Donors WHERE Country IN ('Asia-Pacific Region Countries');
What is the sum of balance for clients with savings accounts in the Boston branch?
CREATE TABLE clients (client_id INT,name TEXT,dob DATE,branch TEXT);CREATE TABLE accounts (account_id INT,client_id INT,account_type TEXT,balance DECIMAL);INSERT INTO clients VALUES (3,'Daniel Kim','1985-11-09','Boston');INSERT INTO accounts VALUES (103,3,'Savings',5000);
SELECT SUM(accounts.balance) FROM clients INNER JOIN accounts ON clients.client_id = accounts.client_id WHERE accounts.account_type = 'Savings' AND clients.branch = 'Boston';
List the top 3 districts with the highest emergency call volume, excluding the Park district.
CREATE TABLE Districts (district_name TEXT,calls INTEGER); INSERT INTO Districts (district_name,calls) VALUES ('Downtown',450),('Uptown',500),('Central',300),('Westside',250),('Park',100);
SELECT district_name, calls FROM Districts WHERE district_name != 'Park' ORDER BY calls DESC LIMIT 3;
What are the top 3 genres by number of songs in the music streaming platform?
CREATE TABLE music_platform (id INT,song_title VARCHAR(100),genre VARCHAR(50));
SELECT genre, COUNT(*) FROM music_platform GROUP BY genre LIMIT 3;
Health equity metrics for each state in the last year?
CREATE TABLE HealthEquityMetrics (ID INT,State VARCHAR(50),Metric VARCHAR(50),Date DATE); INSERT INTO HealthEquityMetrics (ID,State,Metric,Date) VALUES (1,'California','AccessToCare','2022-01-01'),(2,'Texas','QualityOfCare','2022-02-15'),(3,'NewYork','AccessToCare','2022-03-05');
SELECT State, Metric, AVG(Date) as AvgDate FROM HealthEquityMetrics WHERE Date >= DATEADD(year, -1, GETDATE()) GROUP BY State, Metric;
What is the average age of players who play esports games on PC?
CREATE TABLE player (player_id INT,name VARCHAR(50),age INT,platform VARCHAR(10),esports_game VARCHAR(50)); INSERT INTO player (player_id,name,age,platform,esports_game) VALUES (1,'Jamie Chen',25,'PC','League of Legends'); INSERT INTO player (player_id,name,age,platform,esports_game) VALUES (2,'Alexander Lee',30,'Console','Call of Duty'); INSERT INTO player (player_id,name,age,platform,esports_game) VALUES (3,'Avery Wang',35,'PC','Dota 2');
SELECT AVG(age) FROM player WHERE platform = 'PC' AND esports_game IS NOT NULL;
What is the average price of sculptures in the 'Post-Impressionist' period?
CREATE TABLE Artworks (id INT,artist_name VARCHAR(100),period VARCHAR(50),artwork_name VARCHAR(100),price FLOAT); INSERT INTO Artworks (id,artist_name,period,artwork_name,price) VALUES (1,'Vincent van Gogh','Post-Impressionist','Starry Night',1000.0); INSERT INTO Artworks (id,artist_name,period,artwork_name,price) VALUES (2,'Paul Gauguin','Post-Impressionist','Where Do We Come From? What Are We? Where Are We Going?',1200.0); INSERT INTO Artworks (id,artist_name,period,artwork_name,price) VALUES (3,'Georges Seurat','Post-Impressionist','A Sunday Afternoon on the Island of La Grande Jatte',1500.0);
SELECT AVG(price) as avg_price FROM Artworks WHERE period = 'Post-Impressionist' AND artwork_type = 'sculpture';
What are the total number of threat indicators and their types added in the last month?
CREATE TABLE ThreatIntel (indicator_id INT,indicator VARCHAR(50),type VARCHAR(20),timestamp TIMESTAMP); INSERT INTO ThreatIntel (indicator_id,indicator,type,timestamp) VALUES (1,'192.168.1.1','IP','2022-01-01 10:00:00');
SELECT type, COUNT(indicator_id) as total_indicators FROM ThreatIntel WHERE timestamp BETWEEN DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) AND CURRENT_TIMESTAMP GROUP BY type;
What is the total value of Impressionist art exhibited in Paris in the 19th century?
CREATE TABLE Artworks (artwork_id INT,name VARCHAR(255),artist_id INT,date_sold DATE,price DECIMAL(10,2),exhibition_id INT); CREATE TABLE Artists (artist_id INT,name VARCHAR(255),nationality VARCHAR(255)); CREATE TABLE Exhibitions (exhibition_id INT,city VARCHAR(255),start_date DATE,end_date DATE,art_movement VARCHAR(255));
SELECT SUM(Artworks.price) FROM Artworks INNER JOIN Exhibitions ON Artworks.exhibition_id = Exhibitions.exhibition_id INNER JOIN Artists ON Artworks.artist_id = Artists.artist_id WHERE Artists.nationality = 'Impressionist' AND Exhibitions.city = 'Paris' AND Exhibitions.start_date < '1900-01-01' AND Exhibitions.end_date > '1800-01-01';
What is the percentage of the population with access to clean water in Brazil?
CREATE TABLE clean_water_access (country VARCHAR(20),pct_population FLOAT); INSERT INTO clean_water_access (country,pct_population) VALUES ('Brazil',92.5);
SELECT pct_population FROM clean_water_access WHERE country = 'Brazil';
What is the average budget of horror movies released between 2015 and 2020?
CREATE TABLE Genres (id INT,genre VARCHAR(50)); CREATE TABLE Movies (id INT,title VARCHAR(100),genre_id INT,budget INT,release_year INT); INSERT INTO Genres (id,genre) VALUES (1,'Horror'),(2,'Comedy'); INSERT INTO Movies (id,title,genre_id,budget,release_year) VALUES (1,'Movie1',1,5000000,2016),(2,'Movie2',1,7000000,2017),(3,'Movie3',2,8000000,2018);
SELECT AVG(budget) FROM Movies WHERE genre_id = (SELECT id FROM Genres WHERE genre = 'Horror') AND release_year BETWEEN 2015 AND 2020;
Who is the officer who has handled the most emergency calls in the last week?
CREATE TABLE officers (id INT,name VARCHAR(255),division VARCHAR(255)); INSERT INTO officers (id,name,division) VALUES (1,'Maria Garcia','NYPD'),(2,'Ahmed Khan','NYPD'); CREATE TABLE emergency_calls (id INT,officer_id INT,call_time TIMESTAMP); INSERT INTO emergency_calls (id,officer_id,call_time) VALUES (1,1,'2022-03-20 12:00:00'),(2,2,'2022-03-22 13:00:00');
SELECT o.name, COUNT(ec.id) as total_calls FROM emergency_calls ec JOIN officers o ON ec.officer_id = o.id WHERE ec.call_time >= DATEADD(week, -1, CURRENT_TIMESTAMP) GROUP BY o.name ORDER BY total_calls DESC;
List all cities where "Private Donors" and "Government" both funded events
CREATE TABLE events (event_id INT,event_name VARCHAR(50),city VARCHAR(30),funding_source VARCHAR(30)); INSERT INTO events (event_id,event_name,city,funding_source) VALUES (1,'Theater Play','New York','Government'),(2,'Art Exhibit','Los Angeles','Private Donors'),(3,'Music Festival','New York','Government'),(4,'Dance Performance','New York','Private Donors');
SELECT city FROM events WHERE funding_source IN ('Government', 'Private Donors') GROUP BY city HAVING COUNT(DISTINCT funding_source) = 2;
How many unique garment types are there in the unsold_garments table?
CREATE TABLE unsold_garments (id INT,garment_type VARCHAR(20),color VARCHAR(20),quantity INT);
SELECT COUNT(DISTINCT garment_type) AS num_unique_garment_types FROM unsold_garments;
What is the average environmental impact score and total number of mining sites for each company?
CREATE TABLE companies (id INT,name VARCHAR(50)); CREATE TABLE mining_sites (id INT,company_id INT,name VARCHAR(50),location VARCHAR(50),environmental_impact_score DECIMAL(5,2));
SELECT c.name AS company, AVG(ms.environmental_impact_score) AS avg_score, COUNT(ms.id) AS total_sites FROM companies c INNER JOIN mining_sites ms ON c.id = ms.company_id GROUP BY c.name;
List all the unique program outcomes for each program.
CREATE TABLE Programs (id INT,name TEXT,outcome TEXT); INSERT INTO Programs (id,name,outcome) VALUES (1,'Education','Literacy'),(2,'Health','Wellness');
SELECT DISTINCT name, outcome FROM Programs;
What is the total revenue generated by vendors practicing ethical labor in California?
CREATE TABLE vendors (vendor_id INT,vendor_name VARCHAR(50),state VARCHAR(50),ethical_labor BOOLEAN); INSERT INTO vendors VALUES (1,'VendorA','California',true); INSERT INTO vendors VALUES (2,'VendorB','Texas',false); CREATE TABLE sales (sale_id INT,product_id INT,vendor_id INT,sale_amount DECIMAL(5,2)); INSERT INTO sales VALUES (1,1,1,50); INSERT INTO sales VALUES (2,2,1,75); INSERT INTO sales VALUES (3,3,2,30); INSERT INTO sales VALUES (4,4,1,60);
SELECT SUM(sale_amount) FROM sales JOIN vendors ON sales.vendor_id = vendors.vendor_id WHERE vendors.ethical_labor = true AND vendors.state = 'California';
Delete all records in the 'suppliers' table with a 'country' of 'Brazil' and a 'supplier_name' ending with 'es'
CREATE TABLE suppliers (supplier_id INT,supplier_name VARCHAR(255),city VARCHAR(255),country VARCHAR(255));
DELETE FROM suppliers WHERE country = 'Brazil' AND supplier_name LIKE '%es';
Which country has the most fans?
CREATE TABLE fans (fan_id INT,fan_name VARCHAR(50),country VARCHAR(50));
SELECT country, COUNT(*) as fan_count FROM fans GROUP BY country ORDER BY fan_count DESC LIMIT 1;
List all UNESCO World Heritage Sites in Africa.
CREATE TABLE world_heritage_sites (site_name VARCHAR(255),location VARCHAR(255)); INSERT INTO world_heritage_sites (site_name,location) VALUES ('Mount Kilimanjaro','Africa'),('Virunga National Park','Africa');
SELECT site_name FROM world_heritage_sites WHERE location = 'Africa';
What is the total funding received by artists from government sources?
CREATE TABLE artists (id INT,name VARCHAR(255)); INSERT INTO artists (id,name) VALUES (1,'Picasso'),(2,'Van Gogh'); CREATE TABLE funding (artist_id INT,source VARCHAR(255),amount FLOAT); INSERT INTO funding (artist_id,source,amount) VALUES (1,'Private Donor',10000),(1,'Corporation',20000),(1,'Government',15000),(2,'Government',20000);
SELECT artist_id, SUM(amount) FROM funding WHERE source = 'Government' GROUP BY artist_id;
List the number of bridges constructed in California and Texas
CREATE TABLE bridges (id INT,name VARCHAR(50),state VARCHAR(50),length FLOAT,year_built INT); INSERT INTO bridges (id,name,state,length,year_built) VALUES (1,'Golden Gate Bridge','California',2737,1937); INSERT INTO bridges (id,name,state,length,year_built) VALUES (2,'Houston Ship Channel Bridge','Texas',7650,1952);
SELECT state, COUNT(*) FROM bridges GROUP BY state HAVING state IN ('California', 'Texas');
What is the total quantity of 'Sustainable Clothing' sold in 'Germany' for the 'Summer 2023' season?
CREATE TABLE StoreSales (StoreID INT,ProductID INT,QuantitySold INT,StoreCountry VARCHAR(50),SaleDate DATE); INSERT INTO StoreSales (StoreID,ProductID,QuantitySold,StoreCountry,SaleDate) VALUES (1,4,80,'Germany','2023-06-21'),(2,5,60,'Germany','2023-06-03'),(3,4,90,'Germany','2023-07-15'); CREATE TABLE Products (ProductID INT,ProductType VARCHAR(20),Sustainable BOOLEAN); INSERT INTO Products (ProductID,ProductType,Sustainable) VALUES (4,'Sustainable Clothing',TRUE),(5,'Regular Clothing',FALSE);
SELECT StoreCountry, ProductType, SUM(QuantitySold) as TotalQuantitySold FROM StoreSales S JOIN Products P ON S.ProductID = P.ProductID WHERE P.ProductType = 'Sustainable Clothing' AND StoreCountry = 'Germany' AND SaleDate BETWEEN '2023-06-01' AND '2023-08-31' GROUP BY StoreCountry, ProductType;
How many songs were released per month in 2020?
CREATE TABLE song_release (id INT,title TEXT,release_month INT,release_year INT,genre TEXT); INSERT INTO song_release (id,title,release_month,release_year,genre) VALUES (1,'Song4',1,2020,'Pop'); INSERT INTO song_release (id,title,release_month,release_year,genre) VALUES (2,'Song5',3,2020,'Rock'); INSERT INTO song_release (id,title,release_month,release_year,genre) VALUES (3,'Song6',12,2020,'Jazz');
SELECT release_month, COUNT(*) as songs_released FROM song_release WHERE release_year = 2020 GROUP BY release_month;
What is the average weight of packages shipped from each warehouse, excluding shipments over 100 kg?
CREATE TABLE warehouse (id INT,location VARCHAR(255)); INSERT INTO warehouse (id,location) VALUES (1,'Chicago'),(2,'Houston'); CREATE TABLE packages (id INT,warehouse_id INT,weight FLOAT); INSERT INTO packages (id,warehouse_id,weight) VALUES (1,1,50.3),(2,1,30.1),(3,2,70.0),(4,2,150.0);
SELECT warehouse_id, AVG(weight) as avg_weight FROM packages WHERE weight < 100 GROUP BY warehouse_id;
What is the number of patients who have had a flu shot in each county in California, and what is the percentage of patients who have had a flu shot in each county?
CREATE TABLE patients (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),city VARCHAR(50),county VARCHAR(50)); INSERT INTO patients (id,name,age,gender,city,county) VALUES (1,'John Doe',34,'Male','San Francisco','San Francisco'); CREATE TABLE flu_shots (id INT,patient_id INT,shot_date DATE,state VARCHAR(20)); INSERT INTO flu_shots (id,patient_id,shot_date,state) VALUES (1,1,'2022-01-01','California');
SELECT patients.county, COUNT(DISTINCT patients.id) AS total_patients, SUM(CASE WHEN flu_shots.id IS NOT NULL THEN 1 ELSE 0 END) AS flu_shots, ROUND(100.0 * SUM(CASE WHEN flu_shots.id IS NOT NULL THEN 1 ELSE 0 END) / COUNT(DISTINCT patients.id), 2) AS flu_shot_percentage FROM patients LEFT JOIN flu_shots ON patients.id = flu_shots.patient_id WHERE patients.county IS NOT NULL GROUP BY patients.county ORDER BY total_patients DESC;
What is the total number of workplace safety incidents in the Transportation sector?
CREATE TABLE workplace_safety (safety_id INT,union_name VARCHAR(50),incident_date DATE,incident_type VARCHAR(50),sector VARCHAR(50));
SELECT COUNT(*) as total_incidents FROM workplace_safety WHERE sector = 'Transportation';
What is the average population size of all marine species?
CREATE TABLE marine_species (species_id INTEGER,species_name TEXT,avg_population_size FLOAT);
SELECT AVG(avg_population_size) FROM marine_species;
What is the minimum acidity level in the ocean?
CREATE TABLE ocean_acidification (location TEXT,acidity FLOAT); INSERT INTO ocean_acidification (location,acidity) VALUES ('Caribbean Sea',8.2),('Pacific Ocean',8.1),('Atlantic Ocean',8.0);
SELECT MIN(acidity) FROM ocean_acidification;
What is the total number of ad impressions and clicks for each advertiser, and what is the difference between them?
CREATE TABLE advertisers (id INT,name VARCHAR(50)); CREATE TABLE ad_impressions (advertiser_id INT,impression_time TIMESTAMP); CREATE TABLE ad_clicks (advertiser_id INT,click_time TIMESTAMP);
SELECT advertisers.name, COUNT(ad_impressions.advertiser_id) as total_impressions, COUNT(ad_clicks.advertiser_id) as total_clicks, COUNT(ad_impressions.advertiser_id) - COUNT(ad_clicks.advertiser_id) as difference FROM advertisers LEFT JOIN ad_impressions ON advertisers.id = ad_impressions.advertiser_id LEFT JOIN ad_clicks ON advertisers.id = ad_clicks.advertiser_id GROUP BY advertisers.name;
What is the total salary cost of employees in the IT department?
CREATE TABLE employees (id INT PRIMARY KEY,name VARCHAR(50),position VARCHAR(50),department VARCHAR(50),salary DECIMAL(5,2)); CREATE TABLE departments (id INT PRIMARY KEY,name VARCHAR(50),manager_id INT,FOREIGN KEY (manager_id) REFERENCES employees(id));
SELECT SUM(employees.salary) AS total_salary_cost FROM employees INNER JOIN departments ON employees.department = departments.name WHERE departments.name = 'IT';
What is the number of companies in each country?
CREATE TABLE companies (id INT,name TEXT,country TEXT); INSERT INTO companies (id,name,country) VALUES (1,'ABC Manufacturing','USA'); INSERT INTO companies (id,name,country) VALUES (2,'XYZ Production','Canada'); INSERT INTO companies (id,name,country) VALUES (3,'LMN Industry','Mexico'); INSERT INTO companies (id,name,country) VALUES (4,'PQR Enterprise','Brazil');
SELECT country, COUNT(*) AS company_count FROM companies GROUP BY country;
what is the percentage of the total population of each animal species in the 'animal_population' table?
CREATE TABLE animal_population (species VARCHAR(50),population INT); INSERT INTO animal_population (species,population) VALUES ('Tiger',200),('Lion',300),('Elephant',400);
SELECT species, ROUND(population * 100.0 / (SELECT SUM(population) FROM animal_population), 2) AS percentage FROM animal_population;
What is the minimum production quantity of Erbium in the last 2 years?
CREATE TABLE ErbiumProduction (id INT PRIMARY KEY,year INT,production_quantity INT);
SELECT MIN(production_quantity) FROM ErbiumProduction WHERE year BETWEEN (YEAR(CURRENT_DATE) - 2) AND YEAR(CURRENT_DATE);
What is the average donation amount by each donor in the last month?
CREATE TABLE donations (id INT,donor_id INT,donation_date DATE,amount DECIMAL); INSERT INTO donations (id,donor_id,donation_date,amount) VALUES (1,1,'2022-03-01',50.00),(2,1,'2022-03-05',75.00),(3,2,'2022-03-07',100.00);
SELECT donor_id, AVG(amount) FROM donations WHERE donation_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY donor_id;
Delete 'product_transparency' records with a 'recycled_content' lower than 30% and 'country' as 'Brazil'.
CREATE TABLE product_transparency (product_id INT,product_name VARCHAR(50),circular_supply_chain BOOLEAN,recycled_content DECIMAL(4,2),COUNTRY VARCHAR(50));
DELETE FROM product_transparency WHERE recycled_content < 0.3 AND country = 'Brazil';
How many defense contracts were signed in Germany with a cost greater than €1,000,000?
CREATE TABLE defense_contracts (id INT,country VARCHAR(50),cost FLOAT); INSERT INTO defense_contracts (id,country,cost) VALUES (1,'Germany',1500000),(2,'Germany',850000),(3,'France',920000);
SELECT COUNT(*) FROM defense_contracts WHERE country = 'Germany' AND cost > 1000000;
How many graduate students are there in total, and how many of them are from the 'Electrical Engineering' department?
CREATE TABLE graduate_students (id INT,name VARCHAR(50),department VARCHAR(50)); INSERT INTO graduate_students (id,name,department) VALUES (1,'Alice','Computer Science'),(2,'Bob','Computer Science'),(3,'Charlie','Electrical Engineering');
SELECT (SELECT COUNT(*) FROM graduate_students) AS total_students, (SELECT COUNT(*) FROM graduate_students WHERE department = 'Electrical Engineering') AS ee_students;
What was the total fuel consumption for 'VesselC' in January 2021?
CREATE TABLE vessel_fuel_consumption (vessel_name TEXT,fuel_consumption_litres INTEGER,consumption_date DATE); INSERT INTO vessel_fuel_consumption (vessel_name,fuel_consumption_litres,consumption_date) VALUES ('VesselC',300,'2021-01-01'); INSERT INTO vessel_fuel_consumption (vessel_name,fuel_consumption_litres,consumption_date) VALUES ('VesselC',400,'2021-01-03');
SELECT SUM(fuel_consumption_litres) FROM vessel_fuel_consumption WHERE vessel_name = 'VesselC' AND consumption_date BETWEEN '2021-01-01' AND '2021-01-31';
How many graduate students are enrolled in the Art and Design program?
CREATE TABLE program (id INT,name TEXT);CREATE TABLE student (id INT,program_id INT,enrollment_status TEXT);
SELECT COUNT(s.id) FROM student s JOIN program p ON s.program_id = p.id WHERE p.name = 'Art and Design' AND s.enrollment_status = 'enrolled';
What is the total amount donated by each donor in the 'donors' table, joined with the 'donations' table?
CREATE TABLE donors (id INT,name TEXT,email TEXT);CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL(10,2),donation_date DATE);
SELECT donors.name, SUM(donations.amount) FROM donors INNER JOIN donations ON donors.id = donations.donor_id GROUP BY donors.name;
What is the maximum and minimum economic diversification investments in the 'economic_diversification' schema?
CREATE TABLE economic_diversification.investments (id INT,investment_type VARCHAR(50),amount FLOAT); INSERT INTO economic_diversification.investments (id,investment_type,amount) VALUES (1,'Renewable Energy',500000),(2,'Tourism',750000),(3,'Manufacturing',1000000);
SELECT MAX(amount), MIN(amount) FROM economic_diversification.investments;
What is the combined number of goals and assists for forwards from the soccer_players and hockey_players tables?
CREATE TABLE soccer_players (player_id INT,name VARCHAR(50),position VARCHAR(20),goals INT); CREATE TABLE hockey_players (player_id INT,name VARCHAR(50),position VARCHAR(20),assists INT);
SELECT SUM(goals) + SUM(assists) FROM (SELECT position, SUM(goals) as goals, 0 as assists FROM soccer_players WHERE position = 'forward' GROUP BY position UNION ALL SELECT position, 0 as goals, SUM(assists) as assists FROM hockey_players WHERE position = 'forward' GROUP BY position);
What is the minimum number of members in a union based in Ontario?
CREATE TABLE unions (id INT,name TEXT,state TEXT,members INT); INSERT INTO unions (id,name,state,members) VALUES (1,'Union A','Ontario',500),(2,'Union B','Ontario',450),(3,'Union C','British Columbia',300);
SELECT MIN(members) FROM unions WHERE state = 'Ontario';
List all cybersecurity strategies that were implemented in the last 3 years, including the strategy type and implementation date.
CREATE TABLE cyber_strategies (id INT,strategy_type TEXT,strategy_implementation_date DATE); INSERT INTO cyber_strategies (id,strategy_type,strategy_implementation_date) VALUES (1,'Incident Response','2020-01-01'),(2,'Risk Management','2019-12-15');
SELECT cs.strategy_type, cs.strategy_implementation_date FROM cyber_strategies cs WHERE cs.strategy_implementation_date >= '2018-01-01';
What is the average performance score of models trained on dataset C, for each country, excluding the United States?
CREATE TABLE models (id INT,dataset VARCHAR(20),performance FLOAT,country VARCHAR(20)); INSERT INTO models VALUES (1,'datasetA',4.3,'Canada'),(2,'datasetA',4.5,'Mexico'),(3,'datasetB',3.9,'Brazil'),(4,'datasetB',4.1,'Brazil'),(5,'datasetA',4.2,'USA'),(6,'datasetB',3.7,'USA');
SELECT country, AVG(performance) FROM models WHERE dataset = 'datasetC' AND country != 'USA' GROUP BY country;
Find the earliest health equity metric by state in the Southeast region.
CREATE TABLE HealthEquityMetrics (HEMId INT,Metric VARCHAR(255),State VARCHAR(50),MetricDate DATE,RegionID INT); INSERT INTO HealthEquityMetrics (HEMId,Metric,State,MetricDate,RegionID) VALUES (1,'Health Equity Index','Georgia','2021-01-01',2),(2,'Equity Score','North Carolina','2021-02-01',2),(3,'Health Equity Report','South Carolina','2021-03-01',2),(4,'Health Equity Indicator','Tennessee','2021-04-01',2);
SELECT State, Metric, MetricDate FROM HealthEquityMetrics WHERE MetricDate = (SELECT MIN(MetricDate) FROM HealthEquityMetrics WHERE RegionID = 2) AND RegionID = 2;
What is the total number of trees in the young_forest and mature_forest tables, and how many of them are in the protected_zone table?
CREATE TABLE young_forest (tree_id INT,species VARCHAR(50),age INT,height INT,location VARCHAR(50));CREATE TABLE mature_forest (tree_id INT,species VARCHAR(50),age INT,height INT,location VARCHAR(50));CREATE TABLE protected_zone (tree_id INT,location VARCHAR(50));
SELECT COUNT(*) FROM young_forest UNION ALL SELECT COUNT(*) FROM mature_forest EXCEPT SELECT COUNT(*) FROM protected_zone;
What is the average number of visitors per day for the exhibition 'Women in Art' in the month of July?
CREATE TABLE daily_visitors (id INT,exhibition_name VARCHAR(50),visitors INT,visit_date DATE); INSERT INTO daily_visitors (id,exhibition_name,visitors,visit_date) VALUES (1,'Women in Art',120,'2022-07-01'); INSERT INTO daily_visitors (id,exhibition_name,visitors,visit_date) VALUES (2,'Women in Art',135,'2022-07-15');
SELECT AVG(visitors) FROM daily_visitors WHERE exhibition_name = 'Women in Art' AND visit_date >= '2022-07-01' AND visit_date <= LAST_DAY('2022-07-01');
What is the total weight of all spacecraft built by Orbital Outfitters?
CREATE TABLE spacecraft_weights (spacecraft_id INT,weight FLOAT); INSERT INTO spacecraft_weights (spacecraft_id,weight) VALUES (1,777.0),(2,1000.0); CREATE TABLE spacecraft (id INT,name VARCHAR(255),manufacturer VARCHAR(255)); INSERT INTO spacecraft (id,name,manufacturer) VALUES (1,'Juno','Orbital Outfitters'),(2,'Dart','Orbital Outfitters');
SELECT SUM(weight) FROM spacecraft_weights JOIN spacecraft ON spacecraft_weights.spacecraft_id = spacecraft.id WHERE manufacturer = 'Orbital Outfitters';
Find the number of startups founded by a specific founder
CREATE TABLE founders (id INT,name TEXT); INSERT INTO founders (id,name) VALUES (1,'Alice'),(2,'Bob'),(3,'Charlie'),(4,'David'),(5,'Eve'); CREATE TABLE companies (id INT,name TEXT,founder_id INT); INSERT INTO companies (id,name,founder_id) VALUES (1,'Foobar Inc',1),(2,'Gizmos Inc',1),(3,'Widgets Inc',3),(4,'Doodads Inc',4),(5,'Thingamajigs Inc',5),(6,'Whatchamacallits Inc',5);
SELECT COUNT(DISTINCT companies.id) as num_startups FROM companies WHERE companies.founder_id = 1;
What is the total number of hotels in North America?
CREATE TABLE hotels (id INT,name TEXT,country TEXT); INSERT INTO hotels (id,name,country) VALUES (1,'Hotel A','North America'),(2,'Hotel B','North America'),(3,'Hotel C','Europe');
SELECT COUNT(*) FROM hotels WHERE country = 'North America';
Find the total number of users who have posted about "veganism" in the "plantbased" schema.
CREATE TABLE users (id INT,username TEXT,posts TEXT);
SELECT COUNT(DISTINCT username) FROM users WHERE posts LIKE '%veganism%';
List the top 3 mines with the highest copper production in 2019, for mines located in Chile?
CREATE TABLE mine_details (mine_name VARCHAR(255),country VARCHAR(255),mineral VARCHAR(255),quantity INT,year INT); INSERT INTO mine_details (mine_name,country,mineral,quantity,year) VALUES ('Chuquicamata','Chile','Copper',1200000,2019),('Collahuasi','Chile','Copper',550000,2019),('Escondida','Chile','Copper',1500000,2019);
SELECT mine_name, quantity FROM (SELECT mine_name, quantity, ROW_NUMBER() OVER (PARTITION BY country ORDER BY quantity DESC) as row FROM mine_details WHERE country = 'Chile' AND mineral = 'Copper' AND year = 2019) t WHERE row <= 3;
How much water was treated in the wastewater treatment plant in the residential sector in January 2021?
CREATE TABLE wastewater_treatment (year INT,month INT,sector VARCHAR(20),treatment_volume FLOAT); INSERT INTO wastewater_treatment (year,month,sector,treatment_volume) VALUES (2021,1,'residential',12000);
SELECT treatment_volume FROM wastewater_treatment WHERE year = 2021 AND month = 1 AND sector = 'residential';
What is the average salary of female employees in the 'manufacturing' department?
CREATE TABLE salaries (id INT,name VARCHAR(50),gender VARCHAR(10),department VARCHAR(50),salary INT); INSERT INTO salaries (id,name,gender,department,salary) VALUES (1,'Jane Doe','Female','manufacturing',50000); INSERT INTO salaries (id,name,gender,department,salary) VALUES (2,'John Smith','Male','engineering',60000); INSERT INTO salaries (id,name,gender,department,salary) VALUES (3,'Alice Johnson','Female','manufacturing',55000);
SELECT AVG(salary) FROM salaries WHERE department = 'manufacturing' AND gender = 'Female';
What is the average age of patients who received therapy sessions in the state of California?
CREATE TABLE patients (patient_id INT,age INT,gender VARCHAR(20),state VARCHAR(20)); INSERT INTO patients (patient_id,age,gender,state) VALUES (1,35,'Female','California'); INSERT INTO patients (patient_id,age,gender,state) VALUES (2,42,'Male','Texas'); CREATE TABLE therapy_sessions (session_id INT,patient_id INT,therapist_id INT,session_date DATE); INSERT INTO therapy_sessions (session_id,patient_id,therapist_id,session_date) VALUES (1,1,3,'2021-03-15');
SELECT AVG(patients.age) FROM patients INNER JOIN therapy_sessions ON patients.patient_id = therapy_sessions.patient_id WHERE patients.state = 'California';