instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total revenue for each restaurant, including their sustainable sourcing cost, for the month of January 2021?'
CREATE TABLE Restaurants (RestaurantID int,Name varchar(50),SustainableCost decimal(5,2)); CREATE TABLE Revenue (RestaurantID int,Date date,Revenue decimal(5,2));
SELECT R.Name, SUM(Revenue + SustainableCost) as TotalRevenue FROM Restaurants R JOIN Revenue REV ON R.RestaurantID = REV.RestaurantID WHERE REV.Date >= '2021-01-01' AND REV.Date < '2021-02-01' GROUP BY R.Name;
What is the minimum construction labor cost per hour in Colorado for carpentry work?
CREATE TABLE labor_costs (id INT,task VARCHAR(50),cost FLOAT,state VARCHAR(50)); INSERT INTO labor_costs (id,task,cost,state) VALUES (1,'Carpentry Work',30.00,'Colorado'); INSERT INTO labor_costs (id,task,cost,state) VALUES (2,'Plumbing Work',40.00,'Colorado');
SELECT MIN(cost) FROM labor_costs WHERE state = 'Colorado' AND task = 'Carpentry Work'
What is the average temperature change in cities with a population over 1 million?
CREATE TABLE cities (name VARCHAR(255),population INT,avg_temp FLOAT); INSERT INTO cities (name,population,avg_temp) VALUES ('CityA',1200000,15.3),('CityB',1800000,12.8),('CityC',2500000,10.7);
SELECT AVG(avg_temp) FROM cities WHERE population > 1000000;
What is the total funding raised by startups in the e-commerce industry in 2019?
CREATE TABLE startups (id INT,name TEXT,industry TEXT,funding_raised INT,founding_year INT); CREATE TABLE investments (id INT,startup_id INT,funding_amount INT,investment_year INT);
SELECT SUM(investments.funding_amount) FROM startups JOIN investments ON startups.id = investments.startup_id WHERE startups.industry = 'E-commerce' AND startups.founding_year <= 2019 AND investments.investment_year = 2019;
What is the total number of hospital beds in each region?
CREATE TABLE hospital (hospital_id INT,region INT,beds INT); CREATE TABLE region (region_id INT,name VARCHAR(20));
SELECT region, SUM(beds) FROM hospital JOIN region ON hospital.region = region.region_id GROUP BY region;
What is the number of people in each age group (0-18, 19-35, 36-55, 56+) in the state of California?
CREATE TABLE age_groups (age_group VARCHAR(255),lower_bound INT,upper_bound INT); INSERT INTO age_groups (age_group,lower_bound,upper_bound) VALUES ('0-18',0,18),('19-35',19,35),('36-55',36,55),('56+',56,200); CREATE TABLE people (person_id INT,age INT,state_abbreviation VARCHAR(255)); INSERT INTO people (person_id,age,state_abbreviation) VALUES (1,10,'CA'),(2,30,'CA'),(3,40,'CA'),(4,60,'CA'),(5,70,'CA');
SELECT age_group, COUNT(*) FROM (SELECT CASE WHEN age <= 18 THEN '0-18' WHEN age <= 35 THEN '19-35' WHEN age <= 55 THEN '36-55' ELSE '56+' END AS age_group, person_id FROM people WHERE state_abbreviation = 'CA') subquery GROUP BY age_group;
What is the average heart rate of users who did more than 15000 steps?
CREATE TABLE steps (id INT,user_id INT,hr INT,steps INT); INSERT INTO steps (id,user_id,hr,steps) VALUES (1,13,145,18000); INSERT INTO steps (id,user_id,hr,steps) VALUES (2,14,135,12000);
SELECT AVG(hr) FROM steps WHERE steps > 15000;
How many unique public transportation systems are there for each country in the 'public_transportation' table?
CREATE TABLE transportation.public_transportation (country VARCHAR(50),system_type VARCHAR(50));
SELECT country, COUNT(DISTINCT system_type) FROM transportation.public_transportation GROUP BY country;
Which virtual reality devices were used by the most users in 2020?
CREATE TABLE VRDevices (UserID INT,Device VARCHAR(50),Year INT); INSERT INTO VRDevices (UserID,Device,Year) VALUES (1,'Oculus Rift',2019); INSERT INTO VRDevices (UserID,Device,Year) VALUES (2,'HTC Vive',2020); INSERT INTO VRDevices (UserID,Device,Year) VALUES (3,'Oculus Quest',2020);
SELECT Device, COUNT(*) as UserCount FROM VRDevices WHERE Year = 2020 GROUP BY Device ORDER BY UserCount DESC LIMIT 1;
What is the success rate of legal technology tools in rural areas?
CREATE TABLE LegalTechnology (ToolID INT,ToolName VARCHAR(50),Area VARCHAR(20),SuccessRate DECIMAL(3,1)); INSERT INTO LegalTechnology VALUES (1,'LT Tool 1','Rural',0.8); INSERT INTO LegalTechnology VALUES (2,'LT Tool 2','Rural',0.6); INSERT INTO LegalTechnology VALUES (3,'LT Tool 3','Urban',0.9);
SELECT AVG(SuccessRate) FROM LegalTechnology WHERE Area = 'Rural';
What is the total number of threat intelligence reports generated for the African continent?
CREATE TABLE threat_intelligence (ti_id INT,ti_report VARCHAR(50),ti_region VARCHAR(50),ti_date DATE); INSERT INTO threat_intelligence (ti_id,ti_report,ti_region,ti_date) VALUES (1,'Report A','Middle East','2022-01-01'),(2,'Report B','Africa','2022-02-01'),(3,'Report C','Middle East','2022-03-01');
SELECT COUNT(*) FROM threat_intelligence WHERE ti_region = 'Africa';
What is the total number of ingredients used in products that are not certified as cruelty-free and are sourced from 'Large Scale Producers'?
CREATE TABLE product_ingredients_lsp (product_name VARCHAR(50),ingredient VARCHAR(50),ingredient_source VARCHAR(50),is_cruelty_free BOOLEAN); INSERT INTO product_ingredients_lsp (product_name,ingredient,ingredient_source,is_cruelty_free) VALUES ('Clean Slate','Water','Organic Farms',true),('Clean Slate','Mineral Powder','Organic Farms',true),('Clean Slate','Water','Large Scale Producers',false),('Eye Have You','Water','Large Scale Producers',false),('Eye Have You','Mineral Powder','Large Scale Producers',false);
SELECT COUNT(DISTINCT ingredient) FROM product_ingredients_lsp WHERE is_cruelty_free = false AND ingredient_source = 'Large Scale Producers';
What is the rate of resource depletion by mine site in the last 6 months?
CREATE TABLE ResourceDepletion (Site VARCHAR(255),Date DATE,Depletion FLOAT); INSERT INTO ResourceDepletion (Site,Date,Depletion) VALUES ('Mine A','2022-01-01',0.05),('Mine A','2022-02-01',0.06),('Mine A','2022-03-01',0.07),('Mine B','2022-01-01',0.04),('Mine B','2022-02-01',0.05),('Mine B','2022-03-01',0.06);
SELECT Site, (Depletion - LAG(Depletion, 1, Depletion) OVER (PARTITION BY Site ORDER BY Date)) / NULLIF(DATEDIFF(DAY, LAG(Date, 1, Date) OVER (PARTITION BY Site ORDER BY Date), Date), 0) as Depletion_Rate FROM ResourceDepletion WHERE Date >= DATEADD(MONTH, -6, GETDATE()) ORDER BY Site, Date;
Which chemical plants have a safety score lower than 85?
CREATE TABLE chemical_plants (id INT,name TEXT,region TEXT,safety_score INT); INSERT INTO chemical_plants (id,name,region,safety_score) VALUES (1,'Plant A','Northeast',92),(2,'Plant B','Midwest',88),(3,'Plant C','West',95);
SELECT * FROM chemical_plants WHERE safety_score < 85;
What is the average food safety score for restaurants in each city?
CREATE TABLE food_safety_inspections(restaurant_id INT,city TEXT,score FLOAT); INSERT INTO food_safety_inspections(restaurant_id,city,score) VALUES (1,'New York',95.0),(2,'New York',90.0),(3,'Los Angeles',85.0),(4,'Los Angeles',92.0);
SELECT city, AVG(score) FROM food_safety_inspections GROUP BY city;
What is the average flight time for SpaceAirlines in the last year?
CREATE TABLE flights (flight_id INT,airline VARCHAR(255),flight_date DATE,flight_time INT); INSERT INTO flights (flight_id,airline,flight_date,flight_time) VALUES (1,'SpaceAirlines','2022-02-03',240),(2,'SpaceAirlines','2022-06-15',210),(3,'SpaceAirlines','2021-11-18',270),(4,'SpaceAirlines','2022-03-25',220),(5,'SpaceAirlines','2021-09-01',250);
SELECT AVG(flight_time) FROM flights WHERE airline = 'SpaceAirlines' AND flight_date >= DATEADD(year, -1, CURRENT_DATE);
What is the percentage of female workers in the mining industry in Canada?
CREATE TABLE employees (id INT,name TEXT,gender TEXT,location TEXT,position TEXT); INSERT INTO employees (id,name,gender,location,position) VALUES (1,'Jane Smith','female','Canada','engineer');
SELECT (COUNT(CASE WHEN gender = 'female' THEN 1 END) * 100.0 / COUNT(*)) AS female_percentage FROM employees WHERE location = 'Canada';
Who are the experts in agroecology in Africa?
CREATE TABLE Experts (id INT,name VARCHAR(50),location VARCHAR(50),specialization VARCHAR(50)); INSERT INTO Experts (id,name,location,specialization) VALUES (1,'Amina Mohamed','Africa','Agroecology');
SELECT * FROM Experts WHERE location = 'Africa' AND specialization = 'Agroecology';
What is the percentage of female patients who received medication for mental health in Brazil?
CREATE TABLE patients (patient_id INT,age INT,gender TEXT,country TEXT); INSERT INTO patients (patient_id,age,gender,country) VALUES (1,35,'Male','Brazil'); INSERT INTO patients (patient_id,age,gender,country) VALUES (2,42,'Female','Brazil'); CREATE TABLE treatments (treatment_id INT,patient_id INT,treatment_type TEXT); INSERT INTO treatments (treatment_id,patient_id,treatment_type) VALUES (1,1,'Medication'); INSERT INTO treatments (treatment_id,patient_id,treatment_type) VALUES (2,2,'Medication');
SELECT ROUND(100.0 * SUM(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) / COUNT(*), 2) AS percentage_of_female_patients FROM patients JOIN treatments ON patients.patient_id = treatments.patient_id WHERE patients.country = 'Brazil' AND treatments.treatment_type = 'Medication';
Calculate the moving average of carbon prices for the last 3 months.
CREATE TABLE carbon_prices (date DATE,price FLOAT); INSERT INTO carbon_prices (date,price) VALUES ('2021-01-01',25),('2021-01-02',26),('2021-01-03',27),('2021-02-01',28),('2021-02-02',29),('2021-02-03',30),('2021-03-01',31),('2021-03-02',32),('2021-03-03',33);
SELECT date, AVG(price) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as moving_avg FROM carbon_prices;
How many whale sharks are there in the marine_life_populations table?
CREATE TABLE marine_life_populations (species TEXT,population INTEGER); INSERT INTO marine_life_populations (species,population) VALUES ('Whale Shark',30000),('Dolphin',250000),('Clownfish',500000);
SELECT population FROM marine_life_populations WHERE species = 'Whale Shark';
What is the minimum funding amount for startups in the Renewable Energy industry with a founder from an underrepresented racial or ethnic group?
CREATE TABLE startup (id INT,name TEXT,industry TEXT,founder_race TEXT,funding_amount INT); INSERT INTO startup (id,name,industry,founder_race,funding_amount) VALUES (1,'Alpha Corp','Renewable Energy','Latinx',3000000); INSERT INTO startup (id,name,industry,founder_race,funding_amount) VALUES (2,'Beta Inc','Renewable Energy','Asian',2500000); INSERT INTO startup (id,name,industry,founder_race,funding_amount) VALUES (3,'Gamma Ltd','Healthcare','Male',1000000);
SELECT MIN(s.funding_amount) FROM startup s WHERE s.industry = 'Renewable Energy' AND s.founder_race IN ('African American', 'Latinx', 'Native American', 'Pacific Islander');
What is the total number of volunteers for each organization, excluding those with less than 50 volunteers?
CREATE TABLE organizations (org_id INT,org_name TEXT);CREATE TABLE volunteers (vol_id INT,org_id INT,vol_country TEXT);
SELECT o.org_name, COUNT(v.vol_id) AS total_volunteers FROM organizations o JOIN volunteers v ON o.org_id = v.org_id GROUP BY o.org_name HAVING total_volunteers >= 50;
Update the sustainable_sourcing table, setting the organic_certified flag to 0 where the country_of_origin is not 'Italy'
CREATE TABLE sustainable_sourcing (ingredient_name VARCHAR(50),country_of_origin VARCHAR(50),organic_certified INT);
UPDATE sustainable_sourcing SET organic_certified = 0 WHERE country_of_origin != 'Italy';
What is the percentage of extended size clothing in the latest fashion trends?
CREATE TABLE fashion_trends_extended (trend_id INT,clothing_size VARCHAR(20),popularity INT); INSERT INTO fashion_trends_extended (trend_id,clothing_size,popularity) VALUES (1,'XS',1000),(2,'S',2000),(3,'M',3000),(4,'L',2500),(5,'XL',2000),(6,'XXL',1500),(7,'3XL',800),(8,'4XL',500);
SELECT (SUM(CASE WHEN clothing_size IN ('XL', 'XXL', '3XL', '4XL') THEN popularity ELSE 0 END) / SUM(popularity)) * 100 AS percentage FROM fashion_trends_extended;
What is the total number of government employees in the state of Washington, and what is the percentage of those employees who work in the education sector?
CREATE TABLE employees (employee_name VARCHAR(255),employee_sector VARCHAR(255),state VARCHAR(255));
SELECT (COUNT(*) FILTER (WHERE employee_sector = 'education')::float / COUNT(*) * 100) AS education_percentage FROM employees JOIN states ON employees.state = states.state_abbreviation WHERE states.state_name = 'Washington';
What is the total number of crimes reported in 'Forest Area' this month?
CREATE TABLE crimes (id INT,area VARCHAR(20),reported_crimes INT,month INT);
SELECT SUM(reported_crimes) FROM crimes WHERE area = 'Forest Area' AND month = MONTH(CURRENT_DATE);
What are the total sales of all vegetarian menu items?
CREATE TABLE sales (id INT,menu_item_id INT,sales DECIMAL(5,2)); INSERT INTO sales (id,menu_item_id,sales) VALUES (1,1,100.00),(2,1,200.00),(3,2,50.00),(4,3,150.00),(5,3,250.00); CREATE TABLE menus (id INT,menu_item_name TEXT,is_vegetarian BOOLEAN); INSERT INTO menus (id,menu_item_name,is_vegetarian) VALUES (1,'Burger',FALSE),(2,'Fries',TRUE),(3,'Salad',TRUE);
SELECT SUM(sales) FROM sales JOIN menus ON sales.menu_item_id = menus.id WHERE is_vegetarian = TRUE;
What is the total mass of space debris in Low Earth Orbit as of today?
CREATE TABLE space_debris (id INT,name VARCHAR(50),type VARCHAR(50),mass FLOAT,orbit VARCHAR(50),last_update DATE);
SELECT SUM(space_debris.mass) as total_mass FROM space_debris WHERE space_debris.orbit = 'Low Earth Orbit' AND space_debris.last_update = CURDATE();
What are the total quantities of 'Nitric Acid' and 'Phosphoric Acid' produced by all plants in 'Texas' and 'Oklahoma'?
CREATE TABLE Chemical_Plant (plant_name VARCHAR(255),location VARCHAR(255),chemical VARCHAR(255),quantity INT);INSERT INTO Chemical_Plant (plant_name,location,chemical,quantity) VALUES ('Chemical Plant B','Texas','Nitric Acid',1200),('Chemical Plant C','Texas','Phosphoric Acid',1500),('Chemical Plant D','Oklahoma','Nitric Acid',1000),('Chemical Plant E','Oklahoma','Phosphoric Acid',1800);
SELECT chemical, SUM(quantity) FROM Chemical_Plant WHERE (location = 'Texas' OR location = 'Oklahoma') AND chemical IN ('Nitric Acid', 'Phosphoric Acid') GROUP BY chemical;
List the number of mental health facilities in "Colorado" state
CREATE TABLE mental_health_facilities(id INT,name TEXT,state TEXT,type TEXT); INSERT INTO mental_health_facilities(id,name,state,type) VALUES (1,'Mental Health Hospital','Colorado','Hospital'),(2,'Community Mental Health Center','Colorado','Community Health Center'),(3,'Mental Health Clinic','Utah','Community Clinic'),(4,'Mental Health Hospital','Utah','Hospital'),(5,'Mental Health Clinic','Nevada','Community Clinic'),(6,'Mental Health Hospital','Nevada','Hospital'),(7,'Mental Health Clinic','Colorado','Community Clinic'),(8,'Mental Health Hospital','Colorado','Hospital');
SELECT state, COUNT(*) FROM mental_health_facilities WHERE state = 'Colorado' GROUP BY state;
Who are the top 5 countries with the highest number of investments in renewable energy?
CREATE TABLE investments (id INT,company_id INT,country VARCHAR(255),investment_type VARCHAR(255)); INSERT INTO investments (id,company_id,country,investment_type) VALUES (1,1,'USA','Renewable Energy'),(2,1,'Canada','Fossil Fuels'),(3,2,'Germany','Renewable Energy');
SELECT country, COUNT(*) AS investment_count FROM investments WHERE investment_type = 'Renewable Energy' GROUP BY country ORDER BY investment_count DESC LIMIT 5;
What is the distribution of open pedagogy project types among teachers of different ethnicities?
CREATE TABLE open_pedagogy (teacher_id INT,ethnicity VARCHAR(255),project_type VARCHAR(255)); INSERT INTO open_pedagogy (teacher_id,ethnicity,project_type) VALUES (1,'Latinx','Research Paper'),(2,'African American','Presentation'),(3,'Asian American','Group Project'),(4,'Caucasian','Individual Project'),(5,'Latinx','Presentation'),(6,'African American','Group Project');
SELECT ethnicity, project_type, COUNT(*) FROM open_pedagogy GROUP BY ethnicity, project_type;
Insert a new TV show 'The Crown' with a rating of 4.9 and a 2016 release.
CREATE TABLE tv_shows (show_id INT,title VARCHAR(100),release_year INT,rating FLOAT);
INSERT INTO tv_shows (title, release_year, rating) VALUES ('The Crown', 2016, 4.9);
What is the average amount of coal extracted per day in the 'production_data' table?
CREATE TABLE production_data (id INT,date DATE,coal_production INT,gold_production INT); INSERT INTO production_data (id,date,coal_production,gold_production) VALUES (1,'2022-01-01',200,10); INSERT INTO production_data (id,date,coal_production,gold_production) VALUES (2,'2022-01-02',250,15);
SELECT AVG(coal_production) as avg_coal_production FROM production_data;
What is the price of eco-friendly garments made with hemp?
CREATE TABLE garments (id INT,style VARCHAR(255),material VARCHAR(255),price DECIMAL(5,2),sustainable BOOLEAN); INSERT INTO garments (id,style,material,price,sustainable) VALUES (7,'Hemp Tunic','Hemp',39.99,true); INSERT INTO garments (id,style,material,price,sustainable) VALUES (8,'Hemp Pants','Hemp',49.99,true);
SELECT style, price FROM garments WHERE sustainable = true AND material = 'Hemp';
Identify marine species with a population greater than 1000 in 'ocean_species'.
CREATE TABLE ocean_species (id INT,species VARCHAR(255),population INT);
SELECT species FROM ocean_species WHERE population > 1000;
What is the total number of autonomous driving research papers published per year?
CREATE TABLE AutonomousDrivingResearch (Title VARCHAR(100),Author VARCHAR(50),Country VARCHAR(50),Year INT); INSERT INTO AutonomousDrivingResearch (Title,Author,Country,Year) VALUES ('Deep Learning for Autonomous Driving','John Smith','USA',2018),('Computer Vision in Autonomous Vehicles','Anna Johnson','Germany',2019),('Autonomous Driving in Urban Environments','Peter Lee','China',2018),('Sensors in Autonomous Vehicles','Lisa Kim','South Korea',2019);
SELECT Year, COUNT(*) as Total_Papers FROM AutonomousDrivingResearch GROUP BY Year;
Insert a new record into the 'community_education' table for the 'Giraffe Conservation Center'
CREATE TABLE community_education (id INT,center_name VARCHAR(50),location VARCHAR(50),num_participants INT);
INSERT INTO community_education (id, center_name, location, num_participants) VALUES (1, 'Giraffe Conservation Center', 'Kenya', 50);
What is the total number of military personnel in the Asia-Pacific region?
CREATE TABLE military_personnel (id INT,name TEXT,rank TEXT,region TEXT); INSERT INTO military_personnel (id,name,rank,region) VALUES (1,'John Doe','Colonel','Asia-Pacific'),(2,'Jane Smith','General','Europe'),(3,'Robert Johnson','Captain','Asia-Pacific');
SELECT COUNT(*) FROM military_personnel WHERE region = 'Asia-Pacific';
What is the average age of subscribers from 'USA' who prefer investigative journalism?
CREATE TABLE subscribers (id INT,age INT,country TEXT,interest TEXT);
SELECT AVG(age) FROM subscribers WHERE country = 'USA' AND interest = 'investigative journalism';
How many parking tickets were issued in each neighborhood in 2019 and 2020?
CREATE TABLE ParkingTickets (Year INT,Neighborhood VARCHAR(20),Num_Tickets INT); INSERT INTO ParkingTickets (Year,Neighborhood,Num_Tickets) VALUES (2019,'Downtown',1200),(2019,'Uptown',800),(2019,'Westside',900),(2020,'Downtown',1500),(2020,'Uptown',700),(2020,'Westside',850);
SELECT Neighborhood, Year, SUM(Num_Tickets) as Total_Tickets FROM ParkingTickets GROUP BY Neighborhood, Year;
What is the average crop yield by region in 'crops_table'?
CREATE TABLE crops_table (region VARCHAR(50),crop VARCHAR(50),yield INT); INSERT INTO crops_table (region,crop,yield) VALUES ('RegionA','corn',100),('RegionA','wheat',80),('RegionB','corn',110),('RegionB','wheat',90),('RegionC','corn',95),('RegionC','wheat',75);
SELECT region, AVG(yield) as avg_yield FROM crops_table GROUP BY region;
Delete all records from the view "recent_harvest_data" where the "yield" is less than 50
CREATE VIEW recent_harvest_data AS SELECT * FROM harvest_data WHERE date > DATE_SUB(NOW(),INTERVAL 1 MONTH);
DELETE FROM recent_harvest_data WHERE yield < 50;
What is the total revenue for the 'Green' line since its inception?
CREATE TABLE routes (line VARCHAR(10),start_date DATE); INSERT INTO routes (line,start_date) VALUES ('Green','2012-01-01'); CREATE TABLE fares (route VARCHAR(10),revenue DECIMAL(10,2)); INSERT INTO fares (route,revenue) VALUES ('Green',8000),('Green',9000),('Green',10000);
SELECT SUM(revenue) FROM fares WHERE route = (SELECT line FROM routes WHERE start_date <= '2012-01-01' AND line = 'Green' LIMIT 1);
List the top 2 astronauts with the most space missions, along with their respective total mission counts.
CREATE TABLE Astronauts (AstronautID INT,Name VARCHAR(50),TotalMissions INT); INSERT INTO Astronauts (AstronautID,Name,TotalMissions) VALUES (1,'Jerry Ross',7); INSERT INTO Astronauts (AstronautID,Name,TotalMissions) VALUES (2,'Frank De Winne',3); INSERT INTO Astronauts (AstronautID,Name,TotalMissions) VALUES (3,'Soichi Noguchi',3);
SELECT Name, TotalMissions FROM Astronauts ORDER BY TotalMissions DESC LIMIT 2;
What is the average donation amount by age group, considering only donors aged 18-35?
CREATE TABLE Donors (DonorID int,Age int); INSERT INTO Donors (DonorID,Age) VALUES (1,35),(2,45),(3,25),(4,50),(5,19),(6,31); CREATE TABLE Donations (DonationID int,DonorID int,Amount decimal(10,2)); INSERT INTO Donations (DonationID,DonorID,Amount) VALUES (1,1,500),(2,1,750),(3,2,300),(4,2,800),(5,3,900),(6,4,600);
SELECT AVG(D.Amount) as AvgDonation, (D.Age - 18 * FLOOR(D.Age / 18.0)) as AgeGroup FROM Donors D INNER JOIN Donations ON D.DonorID = Donations.DonorID WHERE D.Age BETWEEN 18 AND 35 GROUP BY AgeGroup;
What's the total budget allocated to each cause?
CREATE TABLE Programs (ProgramID INT,ProgramName TEXT,Cause TEXT,Budget FLOAT); INSERT INTO Programs (ProgramID,ProgramName,Cause,Budget) VALUES (1,'Education','Children',15000.00),(2,'Healthcare','Seniors',20000.00);
SELECT Cause, SUM(Budget) FROM Programs GROUP BY Cause;
What is the total number of packages shipped from Mexico to Central America in the last month?
CREATE TABLE package_shipments_central (id INT,package_weight FLOAT,shipped_from VARCHAR(20),shipped_to VARCHAR(20),shipped_date DATE); INSERT INTO package_shipments_central (id,package_weight,shipped_from,shipped_to,shipped_date) VALUES (1,2.3,'Mexico','Guatemala','2022-03-15'),(2,1.9,'Mexico','Belize','2022-03-20');
SELECT COUNT(*) FROM package_shipments_central WHERE shipped_from = 'Mexico' AND shipped_to LIKE 'Central%' AND shipped_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
How many museums in the 'museums' table are located in the United States?
CREATE TABLE museums (museum_id INT,name VARCHAR(50),location VARCHAR(50),status VARCHAR(10));
SELECT COUNT(*) FROM museums WHERE location = 'United States';
Delete all transactions from the 'credit_card' table where the amount is greater than $1000
CREATE TABLE credit_card (transaction_id INT,customer_id INT,amount DECIMAL(10,2),transaction_date DATETIME);
DELETE FROM credit_card WHERE amount > 1000;
What is the total production volume for wells in the North Sea in Q2 2022?
CREATE TABLE wells (id INT,region VARCHAR(20),volume INT,date DATE); INSERT INTO wells (id,region,volume,date) VALUES (1,'North Sea',1500,'2022-04-01'); INSERT INTO wells (id,region,volume,date) VALUES (2,'North Sea',2500,'2022-05-01'); INSERT INTO wells (id,region,volume,date) VALUES (3,'North Sea',3500,'2022-06-01');
SELECT SUM(volume) FROM wells WHERE region = 'North Sea' AND QUARTER(date) = 2 AND YEAR(date) = 2022;
Who are the authors of publications in the Journal of Computer Science in the year 2018?
CREATE TABLE publications (id INT,author VARCHAR(50),year INT,journal VARCHAR(50)); INSERT INTO publications (id,author,year,journal) VALUES (1,'Alice',2019,'Journal of Computer Science'),(2,'Bob',2018,'Journal of Physics'),(3,'Eve',2019,'Journal of Mathematics'),(4,'Alice',2018,'Journal of Computer Science');
SELECT DISTINCT author FROM publications WHERE journal = 'Journal of Computer Science' AND year = 2018;
List all restaurants that have a food safety score above 90.
CREATE TABLE restaurant (restaurant_id INT,food_safety_score INT); INSERT INTO restaurant (restaurant_id,food_safety_score) VALUES (1,95),(2,85),(3,90),(4,75);
SELECT restaurant_id FROM restaurant WHERE food_safety_score > 90;
What is the average drug crime rate in Miami and Phoenix?
CREATE TABLE crime_stats (location VARCHAR(50),year INT,drug_crime_rate FLOAT); INSERT INTO crime_stats (location,year,drug_crime_rate) VALUES ('Miami',2020,1200),('Miami',2019,1300),('Phoenix',2020,1500),('Phoenix',2019,1600);
SELECT location, AVG(drug_crime_rate) as avg_drug_crime_rate FROM crime_stats WHERE location IN ('Miami', 'Phoenix') GROUP BY location;
What is the name of the state with the most public libraries in the United States?
CREATE TABLE State (StateName VARCHAR(50),Country VARCHAR(50),NumberOfPublicLibraries INT); INSERT INTO State (StateName,Country,NumberOfPublicLibraries) VALUES ('California','United States',1500),('Texas','United States',500),('New York','United States',1000);
SELECT StateName FROM State WHERE Country = 'United States' ORDER BY NumberOfPublicLibraries DESC LIMIT 1;
What is the total number of wins for the New York Yankees?
CREATE TABLE teams (id INT,name TEXT,city TEXT,league TEXT); INSERT INTO teams (id,name,city,league) VALUES (5,'New York Yankees','New York','American League'); CREATE TABLE games (id INT,home_team_id INT,away_team_id INT,home_team_wins INT,away_team_wins INT);
SELECT SUM(home_team_wins) + SUM(away_team_wins) FROM games WHERE home_team_id = (SELECT id FROM teams WHERE name = 'New York Yankees' AND city = 'New York') OR away_team_id = (SELECT id FROM teams WHERE name = 'New York Yankees' AND city = 'New York');
List all cruelty-free haircare products with a price over $20, available in the United Kingdom
CREATE TABLE products (product_id INT,product_name TEXT,price DECIMAL(5,2),is_cruelty_free BOOLEAN,country TEXT);
SELECT * FROM products WHERE is_cruelty_free = TRUE AND price > 20 AND country = 'United Kingdom';
What is the total number of workplace safety inspections by month in California in 2022?
CREATE TABLE inspections (id INT,workplace_id INT,state VARCHAR,inspection_date DATE); INSERT INTO inspections (id,workplace_id,state,inspection_date) VALUES (1,2,'California','2022-01-15');
SELECT EXTRACT(MONTH FROM inspection_date) as month, COUNT(*) as total_inspections FROM inspections WHERE state = 'California' AND inspection_date >= '2022-01-01' GROUP BY month;
How many exhibitions have been held in Mexico?
CREATE TABLE Site (SiteID INT PRIMARY KEY,SiteName VARCHAR(50),Country VARCHAR(50),City VARCHAR(50)); INSERT INTO Site (SiteID,SiteName,Country,City) VALUES (5,'Teotihuacan','Mexico','Teotihuacan'); CREATE TABLE Exhibition (ExhibitionID INT PRIMARY KEY,ExhibitionName VARCHAR(50),ExhibitionStartDate DATE,ExhibitionEndDate DATE,SiteID INT); INSERT INTO Exhibition (ExhibitionID,ExhibitionName,ExhibitionStartDate,ExhibitionEndDate,SiteID) VALUES (6,'Teotihuacan - The City of Gods','2022-03-01','2022-06-30',5),(7,'Mesoamerican Art','2021-11-01','2022-02-28',5);
SELECT COUNT(*) FROM Exhibition WHERE SiteID = (SELECT SiteID FROM Site WHERE SiteName = 'Teotihuacan');
What is the total number of workers represented by unions with headquarters in 'New York'?
CREATE TABLE if not exists union_membership (union_id INT,worker_id INT); CREATE TABLE if not exists unions (union_id INT,union_name TEXT,headquarters_address TEXT,total_workers INT); INSERT INTO union_membership (union_id,worker_id) VALUES (1,1001),(1,1002),(1,1003),(2,2001),(2,2002),(3,3001); INSERT INTO unions (union_id,union_name,headquarters_address,total_workers) VALUES (1,'United Steelworkers','60 Boulevard of the Allies,Pittsburgh,PA 15222',5000),(2,'Teamsters','25 Louisiana Ave NW,Washington,DC 20001',7000),(3,'UAW','8000 E Jefferson Ave,Detroit,MI 48214',6000),(4,'NYC Labor Council','275 Seventh Avenue,18th Floor,New York,NY 10001',8000);
SELECT SUM(total_workers) FROM unions WHERE headquarters_address LIKE '%New York%';
What are the names of clients who have not paid their bills for cases handled by female attorneys?
CREATE TABLE Clients (id INT,name VARCHAR(50),attorney_id INT,gender VARCHAR(10),paid DECIMAL(5,2)); CREATE TABLE Bills (id INT,client_id INT,amount DECIMAL(5,2)); INSERT INTO Clients (id,name,attorney_id,gender,paid) VALUES (1,'Client1',1,'Female',600.00),(2,'Client2',1,'Female',NULL),(3,'Client3',2,'Male',1000.00),(4,'Client4',3,'Female',1200.00); INSERT INTO Bills (id,client_id,amount) VALUES (1,1,500.00),(2,2,700.00),(3,3,1200.00),(4,4,1500.00);
SELECT Clients.name FROM Clients INNER JOIN Bills ON Clients.id = Bills.client_id WHERE Clients.paid IS NULL AND Clients.gender = 'Female';
What is the maximum range of military aircrafts in the 'military_tech' table for each country?
CREATE TABLE military_tech (country VARCHAR(50),aircraft_name VARCHAR(50),range INT); INSERT INTO military_tech (country,aircraft_name,range) VALUES ('USA','F-15',3000),('USA','F-22',2960),('Russia','Su-27',3500),('Russia','MiG-35',2000),('China','J-20',2400);
SELECT country, MAX(range) as max_range FROM military_tech GROUP BY country;
What is the minimum mission duration for each space mission?
CREATE TABLE Space_Missions_2 (Mission_Name VARCHAR(50),Astronaut_ID INT,Mission_Duration INT); INSERT INTO Space_Missions_2 (Mission_Name,Astronaut_ID,Mission_Duration) VALUES ('Artemis I',1,25); INSERT INTO Space_Missions_2 (Mission_Name,Astronaut_ID,Mission_Duration) VALUES ('Artemis II',2,300); INSERT INTO Space_Missions_2 (Mission_Name,Astronaut_ID,Mission_Duration) VALUES ('Artemis III',3,365);
SELECT Mission_Name, MIN(Mission_Duration) as Minimum_Mission_Duration FROM Space_Missions_2 GROUP BY Mission_Name;
What is the total billing amount for cases handled by attorney ID 2?
CREATE TABLE AttorneyBilling (AttorneyID INT,CaseID INT,BillingAmount DECIMAL(10,2)); INSERT INTO AttorneyBilling (AttorneyID,CaseID,BillingAmount) VALUES (1,1,2500.00),(2,2,3000.50),(3,3,1500.00);
SELECT SUM(BillingAmount) FROM AttorneyBilling WHERE AttorneyID = 2;
What is the total number of fire emergencies in each district?
CREATE TABLE emergency_incidents (id INT,district VARCHAR(20),type VARCHAR(20),date DATE); INSERT INTO emergency_incidents (id,district,type,date) VALUES (1,'Downtown','Fire','2022-01-01'); INSERT INTO emergency_incidents (id,district,type,date) VALUES (2,'Uptown','Medical','2022-01-02'); INSERT INTO emergency_incidents (id,district,type,date) VALUES (3,'North','Fire','2022-01-03'); INSERT INTO emergency_incidents (id,district,type,date) VALUES (4,'North','Medical','2022-01-04');
SELECT district, COUNT(*) AS total FROM emergency_incidents WHERE type = 'Fire' GROUP BY district;
How many properties with inclusive housing policies are available in Philadelphia?
CREATE TABLE inclusive_housing_policy (property_id INT,city VARCHAR(50),inclusive BOOLEAN); INSERT INTO inclusive_housing_policy VALUES (1,'Philadelphia',TRUE),(2,'Philadelphia',FALSE),(3,'Washington_DC',TRUE);
SELECT COUNT(*) FROM inclusive_housing_policy WHERE city = 'Philadelphia' AND inclusive = TRUE;
List all marine mammals and their conservation status.
CREATE TABLE marine_mammals (name TEXT,conservation_status TEXT);
SELECT name, conservation_status FROM marine_mammals;
Insert new community engagement events in the West region
CREATE TABLE CommunityEvents (event_id INT,region VARCHAR(50),event_type VARCHAR(50),event_date DATE);
INSERT INTO CommunityEvents (event_id, region, event_type, event_date) VALUES (5, 'West', 'Theater', '2023-04-20'), (6, 'West', 'Poetry Slam', '2023-05-15');
Identify the customer with the highest transaction amount in the 'Corporate Banking' division.
CREATE TABLE Customers (CustomerID INT,Division VARCHAR(20)); INSERT INTO Customers (CustomerID,Division) VALUES (1,'Retail Banking'),(2,'Retail Banking'),(3,'Corporate Banking'); CREATE TABLE Transactions (TransactionID INT,CustomerID INT,Amount DECIMAL(10,2)); INSERT INTO Transactions (TransactionID,CustomerID,Amount) VALUES (1,1,500.00),(2,1,250.00),(3,2,750.00),(4,3,1500.00);
SELECT CustomerID, MAX(Amount) FROM Transactions INNER JOIN Customers ON Transactions.CustomerID = Customers.CustomerID WHERE Customers.Division = 'Corporate Banking' GROUP BY CustomerID;
List stores and their total sales quantities for sales that occurred in 2021.
CREATE TABLE stores (store_id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),opened_date DATE); CREATE TABLE sales (sale_id INT PRIMARY KEY,store_id INT,quantity INT,sale_date DATE,FOREIGN KEY (store_id) REFERENCES stores(store_id));
SELECT stores.name, SUM(sales.quantity) FROM stores JOIN sales ON stores.store_id = sales.store_id WHERE sales.sale_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY stores.name;
What is the total number of users who joined the gym in the first quarter of 2022?
CREATE TABLE MembershipData (UserID INT,MembershipStartDate DATE); INSERT INTO MembershipData (UserID,MembershipStartDate) VALUES (1,'2022-01-01'),(2,'2022-01-15'),(3,'2022-02-01'),(4,'2022-03-15'),(5,'2022-03-31');
SELECT COUNT(*) FROM MembershipData WHERE MembershipStartDate >= '2022-01-01' AND MembershipStartDate <= '2022-03-31';
Delete products with a last_sale_date older than 6 months and a quantity of ethically sourced products sold less than 50.
CREATE TABLE daily_sales (sale_date DATE,product_id INT,quantity INT,ethical_source BOOLEAN); INSERT INTO daily_sales VALUES ('2022-06-01',1,50,true),('2022-06-01',2,30,false),('2022-06-02',1,75,true),('2022-06-02',2,40,false),('2022-06-03',1,80,true),('2022-06-03',2,35,false),('2022-06-04',1,90,true),('2022-06-04',2,45,false),('2022-01-01',3,25,false),('2021-12-31',4,10,false);
DELETE FROM daily_sales WHERE sale_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND ethical_source = false AND quantity < 50;
Increase the population of the Green Sea Turtle in the Indian Ocean by 2000.
CREATE TABLE Turtles (Species VARCHAR(255),Ocean VARCHAR(255),Population INT); INSERT INTO Turtles (Species,Ocean,Population) VALUES ('Green Sea Turtle','Indian Ocean',18000);
UPDATE Turtles SET Population = Population + 2000 WHERE Species = 'Green Sea Turtle' AND Ocean = 'Indian Ocean';
What is the total number of accessible technology initiatives in Africa and Asia?
CREATE TABLE accessible_tech_initiatives (id INT,initiative_name VARCHAR(255),location VARCHAR(255),accessibility_score FLOAT);
SELECT SUM(accessibility_score) FROM accessible_tech_initiatives WHERE location IN ('Africa', 'Asia');
Update the 'projects' table by setting the 'status' column to 'completed' for all records where 'country' is 'Brazil'
CREATE TABLE projects (id INT,country VARCHAR(255),status VARCHAR(255));
UPDATE projects SET status = 'completed' WHERE country = 'Brazil';
How many cybersecurity vulnerabilities were discovered in the last 6 months by the Canadian Cybersecurity Agency?
CREATE TABLE CybersecurityVulnerabilities (ID INT,DiscoveryDate DATE,Agency TEXT); INSERT INTO CybersecurityVulnerabilities (ID,DiscoveryDate,Agency) VALUES (1,'2022-04-01','Canadian Cybersecurity Agency'),(2,'2022-03-15','US Cybersecurity Agency'),(3,'2022-02-01','Canadian Cybersecurity Agency');
SELECT COUNT(*) FROM CybersecurityVulnerabilities WHERE DiscoveryDate >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND Agency = 'Canadian Cybersecurity Agency';
What is the percentage of cases resolved through restorative justice, by type and year?
CREATE TABLE cases (case_id INT,case_type VARCHAR(255),year INT,restorative_justice BOOLEAN); INSERT INTO cases (case_id,case_type,year,restorative_justice) VALUES (1,'Assault',2020,TRUE),(2,'Theft',2019,FALSE);
SELECT case_type, year, ROUND(SUM(CASE WHEN restorative_justice THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) as pct_restorative_justice FROM cases GROUP BY case_type, year;
How many male patients in Florida have been diagnosed with depression?
CREATE TABLE patients (id INT,age INT,gender TEXT,state TEXT,condition TEXT); INSERT INTO patients (id,age,gender,state,condition) VALUES (1,35,'Female','California','Anxiety'); INSERT INTO patients (id,age,gender,state,condition) VALUES (2,42,'Male','Florida','Depression');
SELECT COUNT(*) FROM patients WHERE patients.gender = 'Male' AND patients.state = 'Florida' AND patients.condition = 'Depression';
Find the average heart rate of members aged 25-30 from the USA.
CREATE TABLE Member (MemberID INT,Age INT,Country VARCHAR(50)); INSERT INTO Member (MemberID,Age,Country) VALUES (1,27,'USA'); CREATE TABLE Metrics (MemberID INT,HeartRate INT); INSERT INTO Metrics (MemberID,HeartRate) VALUES (1,120);
SELECT AVG(HeartRate) FROM Metrics m JOIN Member mem ON m.MemberID = mem.MemberID WHERE mem.Country = 'USA' AND mem.Age BETWEEN 25 AND 30;
How many events occurred in each quarter of 2022?
CREATE TABLE event_calendar (event_id INT,event_name VARCHAR(50),event_date DATE); INSERT INTO event_calendar (event_id,event_name,event_date) VALUES (1,'Art Show','2022-03-01'); INSERT INTO event_calendar (event_id,event_name,event_date) VALUES (2,'Theater Performance','2022-05-15');
SELECT QUARTER(event_date) as quarter, COUNT(*) as num_events FROM event_calendar WHERE YEAR(event_date) = 2022 GROUP BY quarter;
What is the 2nd highest rent in the greenest buildings in Tokyo?
CREATE TABLE buildings (building_id INT,city VARCHAR(20),green_rating INT,rent INT); INSERT INTO buildings (building_id,city,green_rating,rent) VALUES (1,'Tokyo',5,3000),(2,'Tokyo',4,2800),(3,'Sydney',5,4000);
SELECT LEAD(rent) OVER (ORDER BY green_rating DESC, rent DESC) as second_highest_rent FROM buildings WHERE city = 'Tokyo' AND green_rating = (SELECT MAX(green_rating) FROM buildings WHERE city = 'Tokyo');
What is the total revenue of all vegan skincare products?
CREATE TABLE Skincare (product_id INT,product_name VARCHAR(255),is_vegan BOOLEAN,price DECIMAL(10,2),revenue DECIMAL(10,2)); INSERT INTO Skincare (product_id,product_name,is_vegan,price,revenue) VALUES (1,'Cleanser 1',true,12.99,0),(2,'Toner 1',false,14.99,0),(3,'Moisturizer 4',true,29.99,0);
SELECT SUM(revenue) FROM Skincare WHERE is_vegan = true;
How many humanitarian aid events were there in the Middle East in the last 3 years?
CREATE TABLE aid_events (id INT,region VARCHAR(50),event_type VARCHAR(50),date DATE); INSERT INTO aid_events (id,region,event_type,date) VALUES (1,'Middle East','food distribution','2019-01-01');
SELECT region, COUNT(*) as event_count FROM aid_events WHERE region = 'Middle East' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR) GROUP BY region;
How many pothole repair requests were made in each city?
CREATE TABLE Service_Requests(City VARCHAR(20),Service VARCHAR(20),Request_Date DATE); INSERT INTO Service_Requests(City,Service,Request_Date) VALUES('Los Angeles','Street Cleaning','2022-01-01'); INSERT INTO Service_Requests(City,Service,Request_Date) VALUES('Los Angeles','Pothole Repair','2022-02-01'); INSERT INTO Service_Requests(City,Service,Request_Date) VALUES('San Francisco','Street Cleaning','2022-03-01'); INSERT INTO Service_Requests(City,Service,Request_Date) VALUES('San Francisco','Pothole Repair','2022-04-01');
SELECT City, COUNT(*) FROM Service_Requests WHERE Service = 'Pothole Repair' GROUP BY City;
Which warehouse has the lowest average quantity of items stored?
CREATE TABLE warehouses (id INT,name VARCHAR(50),location VARCHAR(50)); INSERT INTO warehouses (id,name,location) VALUES (1,'Warehouse A','City A'),(2,'Warehouse B','City B'),(3,'Warehouse C','City C'); CREATE TABLE inventory (id INT,warehouse_id INT,item_type VARCHAR(50),quantity INT); INSERT INTO inventory (id,warehouse_id,item_type,quantity) VALUES (1,1,'Item1',100),(2,1,'Item2',200),(3,2,'Item1',150),(4,2,'Item3',50),(5,3,'Item1',250),(6,3,'Item2',100),(7,3,'Item3',150);
SELECT warehouse_id, AVG(quantity) as avg_quantity FROM inventory GROUP BY warehouse_id ORDER BY avg_quantity ASC LIMIT 1;
What is the maximum and minimum budget allocated for ethical AI research by country?
CREATE TABLE Ethical_AI (country VARCHAR(50),budget INT); INSERT INTO Ethical_AI (country,budget) VALUES ('USA',5000000),('Canada',3000000),('Germany',7000000);
SELECT country, MAX(budget) as max_budget, MIN(budget) as min_budget FROM Ethical_AI;
What is the total number of vegetarian and gluten-free dinner menu items?
CREATE TABLE menus (menu_id INT,menu_name VARCHAR(255),category VARCHAR(255),is_vegetarian BOOLEAN,is_gluten_free BOOLEAN); INSERT INTO menus (menu_id,menu_name,category,is_vegetarian,is_gluten_free) VALUES (1,'Quinoa Salad','Dinner',TRUE,TRUE),(2,'Vegan Scramble','Breakfast',TRUE,TRUE),(3,'Cheeseburger','Lunch',FALSE,FALSE);
SELECT SUM(CASE WHEN is_vegetarian = TRUE AND is_gluten_free = TRUE AND category = 'Dinner' THEN 1 ELSE 0 END) FROM menus;
How many operators were hired in the last month in each factory?
CREATE TABLE factories(id INT,name TEXT,location TEXT);CREATE TABLE operators(id INT,factory_id INT,hire_date DATE);INSERT INTO factories(id,name,location) VALUES (1,'Factory A','Location A'),(2,'Factory B','Location B'); INSERT INTO operators(id,factory_id,hire_date) VALUES (1,1,'2021-04-01'),(2,1,'2021-05-01'),(3,2,'2021-03-15');
SELECT factory_id, COUNT(*) as new_hires FROM operators WHERE hire_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY factory_id;
List all animal species included in habitat preservation efforts
CREATE TABLE animal_population (id INT PRIMARY KEY,species VARCHAR(255),population INT); CREATE TABLE habitat_preservation (id INT PRIMARY KEY,species VARCHAR(255),region VARCHAR(255));
SELECT DISTINCT a.species FROM animal_population a INNER JOIN habitat_preservation h ON a.species = h.species;
What is the percentage of sustainable accommodations in Turkey and Greece?
CREATE TABLE SustainableAccommodationsTurkeyGreece (id INT,country VARCHAR(20),sustainable BOOLEAN); INSERT INTO SustainableAccommodationsTurkeyGreece (id,country,sustainable) VALUES (1,'Turkey',TRUE),(2,'Greece',FALSE),(3,'Turkey',TRUE);
SELECT country, AVG(sustainable) * 100.0 AS percentage FROM SustainableAccommodationsTurkeyGreece GROUP BY country;
What are the names of all unique carriers and their associated countries that have a freight forwarding contract?
CREATE TABLE Carrier (CarrierID INT,CarrierName TEXT,Country TEXT); INSERT INTO Carrier (CarrierID,CarrierName,Country) VALUES (1,'ABC Logistics','USA'),(2,'XYZ Freight','Canada');
SELECT DISTINCT CarrierName, Country FROM Carrier WHERE CarrierID IN (SELECT ContractID FROM FreightContract);
Find the number of games each soccer team has played in the last 3 months
CREATE TABLE games (id INT,team_id INT,game_date DATE); INSERT INTO games (id,team_id,game_date) VALUES (1,1,'2021-10-01'),(2,2,'2021-10-05'),(3,1,'2021-11-03');
SELECT team_id, COUNT(*) as games_played FROM games WHERE game_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY team_id;
Which country has the most ethical AI initiatives?
CREATE TABLE ethical_ai_initiatives (country VARCHAR(20),initiatives INT); INSERT INTO ethical_ai_initiatives (country,initiatives) VALUES ('USA',200),('Canada',150),('Germany',250),('India',100),('Brazil',120);
SELECT country, MAX(initiatives) as max_initiatives FROM ethical_ai_initiatives GROUP BY country;
List the number of members who joined in each quarter of the year, for the last two years.
CREATE TABLE members (id INT,join_date DATE);
SELECT QUARTER(join_date) as quarter, COUNT(*) as members_joined FROM members WHERE join_date >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) GROUP BY quarter;
What is the maximum donation amount received from a donor in Canada?
CREATE TABLE Donors (DonorID int,DonorName varchar(50),Country varchar(50)); INSERT INTO Donors (DonorID,DonorName,Country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Canada'); CREATE TABLE Donations (DonationID int,DonorID int,DonationAmount decimal(10,2)); INSERT INTO Donations (DonationID,DonorID,DonationAmount) VALUES (1,2,100),(2,2,200),(3,1,50);
SELECT MAX(DonationAmount) FROM Donations JOIN Donors ON Donations.DonorID = Donors.DonorID WHERE Donors.Country = 'Canada';
What are the total prize pools for esports events held in the USA and Canada?
CREATE TABLE Events (EventID INT,Country VARCHAR(20),PrizePool INT); INSERT INTO Events (EventID,Country,PrizePool) VALUES (1,'USA',500000),(2,'South Korea',700000),(3,'Canada',400000),(4,'Germany',400000),(5,'USA',600000);
SELECT Country, SUM(PrizePool) FROM Events WHERE Country IN ('USA', 'Canada') GROUP BY Country;
What is the number of unique donors who contributed to environmental sustainability programs in the past year, broken down by their age range?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Age INT); CREATE TABLE Donations (DonationID INT,DonorID INT,ProgramID INT,Amount DECIMAL(10,2),DonationDate DATE); CREATE TABLE Programs (ProgramID INT,ProgramName TEXT,FocusArea TEXT);
SELECT CASE WHEN d.Age < 30 THEN 'Under 30' WHEN d.Age BETWEEN 30 AND 50 THEN '30-50' WHEN d.Age > 50 THEN '50 and Over' END AS AgeRange, COUNT(DISTINCT d.DonorID) FROM Donors d INNER JOIN Donations don ON d.DonorID = don.DonorID INNER JOIN Programs p ON don.ProgramID = p.ProgramID WHERE p.FocusArea = 'Environmental Sustainability' AND don.DonationDate >= DATEADD(year, -1, GETDATE()) GROUP BY CASE WHEN d.Age < 30 THEN 'Under 30' WHEN d.Age BETWEEN 30 AND 50 THEN '30-50' WHEN d.Age > 50 THEN '50 and Over' END;
What is the total donation amount for each cause in 'Asia'?
CREATE TABLE causes (id INT PRIMARY KEY,cause TEXT,description TEXT,total_donations FLOAT); INSERT INTO causes (id,cause,description,total_donations) VALUES (1,'Climate Change','Mitigating climate change and its impacts',500000.00); CREATE TABLE donors (id INT PRIMARY KEY,name TEXT,city TEXT,country TEXT); INSERT INTO donors (id,name,city,country) VALUES (1,'John Doe','Tokyo','Japan');
SELECT c.cause, SUM(d.total_donations) as total_donation FROM causes c INNER JOIN donors d ON c.id = d.city WHERE d.country = 'Asia' GROUP BY c.cause;
How many cases were won or lost by attorney 'Garcia'?
CREATE TABLE cases (id INT,attorney TEXT,outcome TEXT); INSERT INTO cases (id,attorney,outcome) VALUES (1,'Garcia','won'),(2,'Garcia','lost'),(3,'Garcia','won'),(4,'Brown','won');
SELECT outcome, COUNT(*) as count FROM cases WHERE attorney = 'Garcia' GROUP BY outcome;