instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the number of times the manufacturing sector has been targeted by malware attacks?
CREATE TABLE attacks (id INT,sector VARCHAR(20),type VARCHAR(50)); INSERT INTO attacks (id,sector,type) VALUES (1,'Manufacturing','Malware'),(2,'Healthcare','Phishing'),(3,'Financial','Ransomware');
SELECT COUNT(*) FROM attacks WHERE sector = 'Manufacturing' AND type = 'Malware';
List all military equipment types and their corresponding sales revenue for the last quarter
CREATE TABLE equipment_sales (equipment_type VARCHAR(255),sale_date DATE,revenue INT); INSERT INTO equipment_sales (equipment_type,sale_date,revenue) VALUES ('Tank','2021-04-01',5000000),('Tank','2021-07-01',6000000),('Jet','2021-05-01',8000000),('Jet','2021-08-01',9000000);
SELECT equipment_type, SUM(revenue) as total_revenue FROM equipment_sales WHERE sale_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) AND DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY equipment_type;
What is the maximum amount of resources extracted in a single day by mining sites in Africa in the last year?
CREATE TABLE MiningSites(id INT,name VARCHAR(30),location VARCHAR(30)); CREATE TABLE ResourceExtraction(site_id INT,date DATE,resources_extracted INT);
SELECT m.location, MAX(re.resources_extracted) FROM MiningSites m JOIN ResourceExtraction re ON m.id = re.site_id WHERE m.location LIKE 'Africa%' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY m.location;
Get the names of all non-vegan makeup products
CREATE TABLE products (product_id INT,product_name VARCHAR(50),product_type VARCHAR(20),vegan BOOLEAN); INSERT INTO products (product_id,product_name,product_type,vegan) VALUES (1,'lipstick','makeup',false),(2,'foundation','makeup',false),(3,'mascara','makeup',true),(4,'eyeshadow','makeup',true);
SELECT product_name FROM products WHERE product_type = 'makeup' AND vegan = false;
Calculate the average satisfaction score for public services in each state, excluding records with a satisfaction score of 0.
CREATE TABLE state_services (state VARCHAR(20),service_type VARCHAR(50),satisfaction_score INT); INSERT INTO state_services (state,service_type,satisfaction_score) VALUES ('California','transportation',8),('California','education',7),('California','healthcare',9),('California','public_safety',6),('California','utilities',0),('Texas','transportation',9),('Texas','education',8),('Texas','healthcare',7),('Texas','public_safety',8),('Texas','utilities',0);
SELECT state, AVG(satisfaction_score) FROM state_services WHERE satisfaction_score > 0 GROUP BY state;
How many polar bears are observed in each Arctic region?
CREATE TABLE arctic_region (region_id INT,region_name VARCHAR(255)); INSERT INTO arctic_region (region_id,region_name) VALUES (1,'Canadian Arctic'),(2,'Greenland'); CREATE TABLE polar_bear_observation (region_id INT,observation INT); INSERT INTO polar_bear_observation (region_id,observation) VALUES (1,500),(2,700);
SELECT region_id, SUM(observation) as total_observation FROM polar_bear_observation GROUP BY region_id;
List all green building certifications with their certification dates in descending order
CREATE TABLE green_building_certifications (id INT,certification_number INT,certification_date DATE);
SELECT * FROM green_building_certifications ORDER BY certification_date DESC;
List the chemical names with their production costs in descending order
CREATE TABLE chemical_costs (chemical VARCHAR(20),cost FLOAT); INSERT INTO chemical_costs (chemical,cost) VALUES ('Eco-friendly Polymer',475.50),('Nano Polymer',452.12),('Smart Polymer',500.00),('Carbon Nanotube',650.00),('Graphene',700.00),('Buckyball',750.00);
SELECT chemical, cost FROM chemical_costs ORDER BY cost DESC;
List the names and topics of articles that have a word count greater than the average word count.
CREATE TABLE articles (id INT,title VARCHAR(50),topic VARCHAR(50),word_count INT); INSERT INTO articles (id,title,topic,word_count) VALUES (1,'Article 1','topic1',1500),(2,'Article 2','topic2',1000);
SELECT title, topic FROM articles WHERE word_count > (SELECT AVG(word_count) FROM articles);
What is the average response time for fire incidents in the city of Chicago, categorized by incident type?
CREATE TABLE emergency_responses (id INT,incident_id INT,response_time INT); CREATE TABLE emergency_incidents (id INT,incident_type VARCHAR(255),report_date DATE); INSERT INTO emergency_incidents (id,incident_type,report_date) VALUES (1,'Fire','2022-01-01'),(2,'Medical Emergency','2022-01-02'); INSERT INTO emergency_responses (id,incident_id,response_time) VALUES (1,1,10),(2,1,12),(3,2,20);
SELECT incident_type, AVG(response_time) FROM emergency_responses JOIN emergency_incidents ON emergency_responses.incident_id = emergency_incidents.id WHERE incident_type = 'Fire' GROUP BY incident_type;
Remove all music albums released before 2000
CREATE TABLE albums (id INT,title TEXT,artist TEXT,release_year INT);
DELETE FROM albums WHERE release_year < 2000;
What are the names of all the farmers who have cultivated either corn or soybean, but not both?
CREATE TABLE farmers (id INT,name VARCHAR(50)); CREATE TABLE crops_farmers (farmer_id INT,crop_id INT); CREATE TABLE crops (id INT,name VARCHAR(50)); INSERT INTO crops (id,name) VALUES (1,'Corn'),(2,'Soybean'),(3,'Wheat'); INSERT INTO farmers (id,name) VALUES (1,'John'),(2,'Jane'),(3,'Mary'); INSERT INTO crops_farmers (farmer_id,crop_id) VALUES (1,1),(1,3),(2,1),(2,2),(3,1);
SELECT f.name FROM farmers f JOIN crops_farmers cf ON f.id = cf.farmer_id JOIN crops c ON cf.crop_id = c.id WHERE c.name IN ('Corn', 'Soybean') GROUP BY f.name HAVING COUNT(DISTINCT c.name) = 1;
Rank garments by the number of times they were sold, partitioned by clothing category, and show only the top ranked garment in each category.
CREATE TABLE GarmentSales (SaleID INT,GarmentID INT,Category VARCHAR(255),Country VARCHAR(255)); INSERT INTO GarmentSales (SaleID,GarmentID,Category,Country) VALUES (1,1,'Tops','USA');
SELECT GarmentID, Category, ROW_NUMBER() OVER (PARTITION BY Category ORDER BY COUNT(*) DESC) as Rank FROM GarmentSales WHERE Country = 'USA' GROUP BY GarmentID, Category HAVING Rank = 1;
How many articles were published by each author in 'regional_newspapers' table and 'international_newswire' table in 2020?
CREATE TABLE regional_newspapers (article_id INT,author_name VARCHAR(50),region VARCHAR(50),publication_date DATE);CREATE TABLE international_newswire (article_id INT,author_name VARCHAR(50),country VARCHAR(50),publication_date DATE);
SELECT author_name, COUNT(*) FROM regional_newspapers WHERE YEAR(publication_date) = 2020 GROUP BY author_name;SELECT author_name, COUNT(*) FROM international_newswire WHERE YEAR(publication_date) = 2020 GROUP BY author_name;
List all ingredients sourced from France for cosmetic products launched in 2020 with a 'natural' label.
CREATE TABLE ingredients (ingredient_id INT,product_id INT,ingredient_name VARCHAR(100),source_country VARCHAR(50),launch_year INT,label VARCHAR(50)); INSERT INTO ingredients (ingredient_id,product_id,ingredient_name,source_country,launch_year,label) VALUES (1,1,'Beeswax','France',2020,'natural'),(2,2,'Water','Canada',2019,'organic'),(3,3,'Coconut Oil','Sri Lanka',2020,'natural'),(4,4,'Shea Butter','Ghana',2018,'natural'),(5,5,'Jojoba Oil','Argentina',2020,'natural');
SELECT ingredient_name FROM ingredients WHERE source_country = 'France' AND launch_year = 2020 AND label = 'natural';
What is the average distance traveled per day by all manually driven vehicles in 'paris'?
CREATE TABLE vehicles (id INT,city VARCHAR(20),type VARCHAR(20),daily_distance INT); INSERT INTO vehicles VALUES (1,'paris','manual',50); INSERT INTO vehicles VALUES (2,'paris','manual',60); INSERT INTO vehicles VALUES (3,'london','manual',70);
SELECT AVG(daily_distance) FROM vehicles WHERE city = 'paris' AND type = 'manual';
What is the total amount of transactions per customer, sorted by the highest total?
CREATE TABLE transactions (customer_id INT,transaction_date DATE,amount DECIMAL(10,2)); INSERT INTO transactions (customer_id,transaction_date,amount) VALUES (1,'2022-01-01',100),(1,'2022-01-05',200),(2,'2022-01-02',150),(2,'2022-01-03',50);
SELECT customer_id, SUM(amount) AS total_amount FROM transactions GROUP BY customer_id ORDER BY total_amount DESC;
What is the average donation amount from donors aged 60 and above from each country?
CREATE TABLE Donors (DonorID int,DonorName varchar(50),Country varchar(50),Age int); INSERT INTO Donors (DonorID,DonorName,Country,Age) VALUES (1,'John Doe','USA',65),(2,'Jane Smith','Canada',45); 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 Country, AVG(DonationAmount) FROM Donations JOIN Donors ON Donations.DonorID = Donors.DonorID WHERE Donors.Age >= 60 GROUP BY Country;
Update the vaccine of patient 2 to 'Pfizer'.
CREATE TABLE patient_vaccinations (patient_id INTEGER,vaccine TEXT,vaccination_date DATE); INSERT INTO patient_vaccinations (patient_id,vaccine,vaccination_date) VALUES (1,'Moderna','2022-01-05'),(2,'Moderna','2022-02-12'),(3,'Pfizer','2022-03-20');
UPDATE patient_vaccinations SET vaccine = 'Pfizer' WHERE patient_id = 2
What is the average delivery time for shipments from Australia to Asia?
CREATE TABLE DeliveryTimes3(id INT,source_country VARCHAR(50),destination_country VARCHAR(50),delivery_time INT); INSERT INTO DeliveryTimes3(id,source_country,destination_country,delivery_time) VALUES (1,'Australia','Japan',7),(2,'Australia','India',9);
SELECT AVG(delivery_time) FROM DeliveryTimes3 WHERE source_country = 'Australia' AND destination_country LIKE '%Asia%';
Insert records for 3 students in the student_mental_health table
CREATE TABLE student_mental_health (id INT PRIMARY KEY,student_id INT,mental_health_score INT,assessment_date DATE);
INSERT INTO student_mental_health (id, student_id, mental_health_score, assessment_date) VALUES (1, 101, 60, '2021-01-15'), (2, 102, 70, '2021-02-12'), (3, 103, 80, '2021-03-18');
What is the minimum age of animals in the habitat preservation program?
CREATE TABLE habitat_ages_2 (animal_id INT,age INT); INSERT INTO habitat_ages_2 (animal_id,age) VALUES (1,6),(2,4),(3,3),(4,5);
SELECT MIN(age) FROM habitat_ages_2;
What is the average maintenance cost for tunnels in the 'tunnel_info' table?
CREATE TABLE tunnel_info (tunnel_id INT,tunnel_name VARCHAR(50),maintenance_cost INT); INSERT INTO tunnel_info (tunnel_id,tunnel_name,maintenance_cost) VALUES (1,'Hartford Tunnel',200000),(2,'Holland Tunnel',300000),(3,'Lincoln Tunnel',250000);
SELECT AVG(maintenance_cost) FROM tunnel_info;
What is the maximum number of likes for posts on 'Monday'?
CREATE TABLE posts (id INT,post_date DATE,likes INT); INSERT INTO posts (id,post_date,likes) VALUES (1,'2022-01-01',10),(2,'2022-01-01',20),(3,'2022-01-02',30),(4,'2022-01-03',40),(5,'2022-01-04',50),(6,'2022-01-05',60),(7,'2022-01-06',70),(8,'2022-01-07',80),(9,'2022-01-08',90),(10,'2022-01-09',100),(11,'2022-01-10',110),(12,'2022-01-11',120);
SELECT MAX(likes) FROM posts WHERE DATE_FORMAT(post_date, '%W') = 'Monday';
Which countries have the most ocean acidification research vessels?
CREATE TABLE ocean_acidification_vessels (country VARCHAR(255),num_vessels INT); INSERT INTO ocean_acidification_vessels (country,num_vessels) VALUES ('United States',5),('Germany',4),('Japan',3);
SELECT country, SUM(num_vessels) FROM ocean_acidification_vessels GROUP BY country ORDER BY SUM(num_vessels) DESC;
What is the average manufacturing time for each garment type in Central America?
CREATE TABLE garment_manufacturing (garment_id INT,garment_type VARCHAR(50),region VARCHAR(50),manufacturing_time INT); CREATE TABLE garments (garment_id INT,garment_name VARCHAR(50));
SELECT garment_type, AVG(manufacturing_time) FROM garment_manufacturing JOIN garments ON garment_manufacturing.garment_id = garments.garment_id WHERE region = 'Central America' GROUP BY garment_type;
How many members have a 'Basic' membership and do not own a smartwatch?
CREATE TABLE Members (MemberID INT,Age INT,MembershipType VARCHAR(10)); INSERT INTO Members (MemberID,Age,MembershipType) VALUES (1,35,'Premium'),(2,28,'Basic'),(3,42,'Premium'); CREATE TABLE SmartwatchOwners (MemberID INT); INSERT INTO SmartwatchOwners (MemberID) VALUES (1),(3);
SELECT COUNT(*) FROM Members LEFT JOIN SmartwatchOwners ON Members.MemberID = SmartwatchOwners.MemberID WHERE Members.MembershipType = 'Basic' AND SmartwatchOwners.MemberID IS NULL;
Count the number of members in the 'Construction_Workers_Union' having a safety_rating below 8.
CREATE TABLE Construction_Workers_Union (union_member_id INT,member_id INT,safety_rating FLOAT); INSERT INTO Construction_Workers_Union (union_member_id,member_id,safety_rating) VALUES (1,101,7.50),(1,102,8.25),(1,103,8.75),(2,201,6.50),(2,202,7.75);
SELECT COUNT(union_member_id) FROM Construction_Workers_Union WHERE safety_rating < 8;
Find the names of dishes that are both in the pasta and vegetarian categories.
CREATE TABLE dishes (id INT,name VARCHAR(50),category VARCHAR(50),price DECIMAL(5,2)); INSERT INTO dishes (id,name,category,price) VALUES (1,'Margherita Pizza','Pizza',9.99),(2,'Chicken Alfredo','Pasta',12.49),(3,'Vegetable Lasagna','Pasta',10.99),(4,'Eggplant Parmesan','Vegetarian',11.99);
SELECT name FROM dishes WHERE category = 'Pasta' INTERSECT SELECT name FROM dishes WHERE category = 'Vegetarian';
What is the total volume of pollution in cubic meters in the Pacific Ocean?
CREATE TABLE pollution (location TEXT,volume REAL); INSERT INTO pollution (location,volume) VALUES ('Pacific Ocean',123456789.0);
SELECT volume FROM pollution WHERE location = 'Pacific Ocean';
What is the second highest property tax for affordable housing units in the state of California?
CREATE TABLE property_tax (id INT,state VARCHAR(20),property_tax INT,housing_type VARCHAR(20)); INSERT INTO property_tax (id,state,property_tax,housing_type) VALUES (1,'California',2000,'affordable'),(2,'California',2500,'affordable'),(3,'California',1500,'market_rate');
SELECT property_tax FROM (SELECT property_tax, ROW_NUMBER() OVER (ORDER BY property_tax DESC) as rn FROM property_tax WHERE state = 'California' AND housing_type = 'affordable') t WHERE rn = 2;
What is the minimum age of patients who have been diagnosed with tuberculosis in the state of Texas?
CREATE TABLE patients (patient_id INT,age INT,gender VARCHAR(10),state VARCHAR(20)); INSERT INTO patients (patient_id,age,gender,state) VALUES (1,45,'Male','New York'); INSERT INTO patients (patient_id,age,gender,state) VALUES (2,34,'Female','California');
SELECT MIN(age) FROM patients WHERE state = 'Texas' AND disease = 'Tuberculosis'
What is the percentage change in temperature for each country between 2019 and 2020 in the 'world_temperature' table?
CREATE TABLE world_temperature (country VARCHAR(255),temperature DECIMAL(5,2),measurement_date DATE); INSERT INTO world_temperature (country,temperature,measurement_date) VALUES ('South Africa',25.3,'2019-01-01'),('Nigeria',28.1,'2019-01-01'),('South Africa',27.0,'2020-01-01'),('Nigeria',29.2,'2020-01-01');
SELECT a.country, (a.temperature - b.temperature) * 100.0 / b.temperature as temperature_change_percentage FROM world_temperature a INNER JOIN world_temperature b ON a.country = b.country WHERE YEAR(a.measurement_date) = 2020 AND YEAR(b.measurement_date) = 2019;
List all safety test results for vehicle models starting with 'A' in the 'safety_tests_detailed' table.
CREATE TABLE safety_tests_detailed (vehicle_model VARCHAR(10),safety_rating INT,year INT,test_number INT);
SELECT * FROM safety_tests_detailed WHERE vehicle_model LIKE 'A%' ORDER BY vehicle_model, year;
What is the number of startups founded by individuals from historically marginalized communities in the augmented reality industry that have received funding, but only for startups founded after 2015?
CREATE TABLE company (id INT,name TEXT,industry TEXT,founding_date DATE,founder_marginalized TEXT); INSERT INTO company (id,name,industry,founding_date,founder_marginalized) VALUES (1,'AugmentedRealityCo','Augmented Reality','2016-01-01','Yes');
SELECT COUNT(DISTINCT company.id) FROM company JOIN funding_records ON company.id = funding_records.company_id WHERE company.industry = 'Augmented Reality' AND company.founder_marginalized = 'Yes' AND company.founding_date > '2015-01-01';
What is the total number of cybersecurity incidents reported by each continent in the last 3 years?
CREATE TABLE CybersecurityIncidents (id INT,incident_name VARCHAR(255),incident_date DATE,country VARCHAR(255),continent VARCHAR(255)); INSERT INTO CybersecurityIncidents (id,incident_name,incident_date,country,continent) VALUES (1,'Incident A','2020-01-01','France','Europe'),(2,'Incident B','2020-02-15','Brazil','South America'),(3,'Incident C','2021-03-03','Canada','North America');
SELECT continent, COUNT(*) as total_incidents FROM CybersecurityIncidents WHERE incident_date BETWEEN DATEADD(year, -3, GETDATE()) AND GETDATE() GROUP BY continent;
What is the total number of concerts in Los Angeles and New York?
CREATE TABLE Concerts (id INT,city VARCHAR(255),price DECIMAL(5,2),tickets_sold INT); INSERT INTO Concerts (id,city,price,tickets_sold) VALUES (1,'New York',50.00,1000),(2,'Los Angeles',75.00,800);
SELECT COUNT(*) FROM Concerts WHERE city IN ('New York', 'Los Angeles');
What is the total number of streams for Latin artists in 2020?
CREATE TABLE Streams (artist_name VARCHAR(50),artist_category VARCHAR(20),year INT,streams INT); INSERT INTO Streams (artist_name,artist_category,year,streams) VALUES ('Shakira','Latin',2020,10000000),('J Balvin','Latin',2020,12000000);
SELECT SUM(streams) FROM Streams WHERE artist_category = 'Latin' AND year = 2020;
Get the number of unique visitors who attended workshops in the last month
CREATE TABLE WorkshopAttendance (id INT,visitor_id INT,date DATE); INSERT INTO WorkshopAttendance (id,visitor_id,date) VALUES (1,1,'2022-01-01'); INSERT INTO WorkshopAttendance (id,visitor_id,date) VALUES (2,2,'2022-01-03');
SELECT COUNT(DISTINCT visitor_id) FROM WorkshopAttendance WHERE date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND CURRENT_DATE;
What are the unique animal species in the 'habitat_preservation' table?
CREATE TABLE habitat_preservation (id INT,year INT,animal_species VARCHAR(50),acres FLOAT); INSERT INTO habitat_preservation (id,year,animal_species,acres) VALUES (1,2021,'Tiger',50.5),(2,2022,'Giant Panda',75.3);
SELECT DISTINCT animal_species FROM habitat_preservation;
How many ethical AI initiatives were implemented in each region, ordered by the number of initiatives in descending order?
CREATE TABLE ethical_ai_initiatives (initiative_id INT,initiative_name VARCHAR(255),region VARCHAR(255)); INSERT INTO ethical_ai_initiatives (initiative_id,initiative_name,region) VALUES (1,'AI for social justice','North America'),(2,'Ethical AI guidelines','Europe'),(3,'AI for disability','Asia'),(4,'AI for healthcare equality','Africa'),(5,'Fair AI in education','South America'),(6,'Ethical AI for finance','North America'),(7,'AI for environmental justice','Europe');
SELECT region, COUNT(*) as total_initiatives FROM ethical_ai_initiatives GROUP BY region ORDER BY total_initiatives DESC;
Delete records in the 'cargo' table where the type is 'Dangerous Goods' and the origin is 'China'
CREATE TABLE cargo (id INT,type VARCHAR(20),origin VARCHAR(20),destination VARCHAR(20),weight FLOAT); INSERT INTO cargo (id,type,origin,destination,weight) VALUES (1,'Containers','China','USA',1000.0); INSERT INTO cargo (id,type,origin,destination,weight) VALUES (2,'Dangerous Goods','China','Japan',500.0);
DELETE FROM cargo WHERE type = 'Dangerous Goods' AND origin = 'China';
Find the average rating for each product category in 2022?
CREATE TABLE ratings (product_category VARCHAR(255),rating INT,rating_date DATE); INSERT INTO ratings (product_category,rating,rating_date) VALUES ('Skincare',4,'2022-01-01'),('Makeup',5,'2022-01-03'),('Skincare',3,'2022-01-05'),('Haircare',5,'2022-01-07'),('Makeup',4,'2022-02-01');
SELECT product_category, AVG(rating) as avg_rating FROM ratings WHERE rating_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY product_category;
What is the earliest planting date for each crop in the 'farming_practices' table?
CREATE TABLE farming_practices (crop VARCHAR(50),planting_date DATE,region VARCHAR(50)); INSERT INTO farming_practices VALUES ('Quinoa','2022-04-15','South America'); INSERT INTO farming_practices VALUES ('Quinoa','2022-04-10','Central America'); INSERT INTO farming_practices VALUES ('Potatoes','2022-06-01','South America'); INSERT INTO farming_practices VALUES ('Potatoes','2022-05-20','Central America');
SELECT crop, MIN(planting_date) AS earliest_planting_date FROM farming_practices GROUP BY crop;
Avg. CO2 offset for green building certification
CREATE TABLE green_buildings (id INT,name VARCHAR(255),certification VARCHAR(255),co2_offset FLOAT);
SELECT AVG(co2_offset) FROM green_buildings WHERE certification IS NOT NULL;
Which menu items have been sold for more than $1000 in a single day?
CREATE TABLE menu_items (item_name VARCHAR(255),sale_date DATE,revenue INT); INSERT INTO menu_items (item_name,sale_date,revenue) VALUES ('Burger','2022-01-01',1500),('Pizza','2022-01-01',800),('Burger','2022-01-02',1700),('Pizza','2022-01-02',900);
SELECT item_name, sale_date FROM menu_items WHERE revenue > 1000;
What's the average rating of movies produced in the USA?
CREATE TABLE movies (id INT,title TEXT,rating FLOAT,country TEXT); INSERT INTO movies (id,title,rating,country) VALUES (1,'Movie1',4.5,'USA'),(2,'Movie2',3.2,'Canada');
SELECT AVG(rating) FROM movies WHERE country = 'USA';
What is the difference in scores between the top and bottom players in the 'Strategy' game category?
CREATE TABLE StrategyScores (PlayerID int,PlayerName varchar(50),Game varchar(50),Score int); INSERT INTO StrategyScores (PlayerID,PlayerName,Game,Score) VALUES (1,'Player1','Game3',1000),(2,'Player2','Game3',1200),(3,'Player3','Game3',1400),(4,'Player4','Game3',1600),(5,'Player5','Game3',1800),(6,'Player6','Game3',2000);
SELECT Game, MAX(Score) as TopScore, MIN(Score) as BottomScore, MAX(Score) - MIN(Score) as ScoreDifference FROM StrategyScores WHERE Game = 'Game3';
What is the average call duration for each mobile plan?
CREATE TABLE mobile_plans (id INT,name VARCHAR(50),price DECIMAL(5,2)); INSERT INTO mobile_plans (id,name,price) VALUES (1,'PlanA',30.00),(2,'PlanB',45.00); CREATE TABLE call_duration (id INT,plan_id INT,duration INT); INSERT INTO call_duration (id,plan_id,duration) VALUES (1,1,120),(2,1,150),(3,2,180);
SELECT m.name, AVG(cd.duration) as avg_call_duration FROM mobile_plans m INNER JOIN call_duration cd ON m.id = cd.plan_id GROUP BY m.name;
What is the total amount of climate finance invested in each country?
CREATE TABLE finance (country TEXT,investment_amount FLOAT); INSERT INTO finance (country,investment_amount) VALUES ('USA',5000000),('India',3000000),('Brazil',4000000),('China',7000000);
SELECT country, SUM(investment_amount) FROM finance GROUP BY country;
What is the total number of traditional art pieces preserved in each cultural institution?
CREATE TABLE Institution (InstitutionID INT,InstitutionName VARCHAR(50),Country VARCHAR(50)); INSERT INTO Institution (InstitutionID,InstitutionName,Country) VALUES (1,'Museo Nacional de Antropología','Mexico'),(2,'British Museum','United Kingdom'),(3,'National Museum of Australia','Australia'); CREATE TABLE Art (ArtID INT,ArtName VARCHAR(50),InstitutionID INT); INSERT INTO Art (ArtID,ArtName,InstitutionID) VALUES (1,'Aztec Calendar Stone',1),(2,'Rosetta Stone',2),(3,'Aboriginal Art',3);
SELECT Country, COUNT(ArtName) as ArtCount FROM Art JOIN Institution ON Art.InstitutionID = Institution.InstitutionID GROUP BY Country;
Add a new record to the 'athletics_meets' table for a meet with a capacity of 50000 located in 'Delhi', 'India'
CREATE TABLE athletics_meets (meet_id INT,meet_name VARCHAR(50),capacity INT,city VARCHAR(50),country VARCHAR(50));
INSERT INTO athletics_meets (meet_id, meet_name, capacity, city, country) VALUES (1, 'Delhi Athletics Meet', 50000, 'Delhi', 'India');
What is the total number of games played by the New York Yankees and the Boston Red Sox in the 2018 MLB season?
CREATE TABLE games (team1 VARCHAR(50),team2 VARCHAR(50),season VARCHAR(10)); INSERT INTO games (team1,team2,season) VALUES ('New York Yankees','Boston Red Sox','2018'),('New York Yankees','Boston Red Sox','2018');
SELECT COUNT(*) FROM games WHERE (team1 = 'New York Yankees' AND team2 = 'Boston Red Sox') OR (team1 = 'Boston Red Sox' AND team2 = 'New York Yankees') AND season = '2018';
Find the average fine and total revenue for environmental crimes in 2020?
CREATE TABLE environmental_crimes (id INT,fine_amount INT,crime_date DATE); INSERT INTO environmental_crimes (id,fine_amount,crime_date) VALUES (1,5000,'2020-01-01'),(2,7000,'2020-02-15'),(3,3000,'2019-12-31');
SELECT AVG(fine_amount), SUM(fine_amount) FROM environmental_crimes WHERE YEAR(crime_date) = 2020;
What is the average price of vegan appetizers in the Los Angeles region?
CREATE TABLE Menu (id INT,item_name VARCHAR(20),item_type VARCHAR(10),price DECIMAL(10,2),region VARCHAR(10)); INSERT INTO Menu (id,item_name,item_type,price,region) VALUES (1,'Vegan Soup','appetizer',7.99,'Los Angeles'),(2,'Cheese Pizza','appetizer',10.99,'New York');
SELECT AVG(price) FROM Menu WHERE item_type = 'appetizer' AND region = 'Los Angeles' AND item_name LIKE '%vegan%';
What is the average response time for emergencies in the Westside district?
CREATE TABLE emergency_responses (id INT,district VARCHAR(20),type VARCHAR(20),response_time INT); INSERT INTO emergency_responses (id,district,type,response_time) VALUES (1,'Downtown','Fire',10); INSERT INTO emergency_responses (id,district,type,response_time) VALUES (2,'Uptown','Medical',8); INSERT INTO emergency_responses (id,district,type,response_time) VALUES (3,'North','Fire',12); INSERT INTO emergency_responses (id,district,type,response_time) VALUES (4,'North','Medical',7); INSERT INTO emergency_responses (id,district,type,response_time) VALUES (5,'Westside','Fire',9); INSERT INTO emergency_responses (id,district,type,response_time) VALUES (6,'Westside','Medical',11);
SELECT AVG(response_time) FROM emergency_responses WHERE district = 'Westside';
What is the total budget allocated for services in areas with a population greater than 1000000?
CREATE TABLE AreaBudget (Service VARCHAR(25),Location VARCHAR(25),Budget INT); INSERT INTO AreaBudget (Service,Location,Budget) VALUES ('Education','City A',10000000),('Health','City A',8000000),('Education','City B',12000000);
SELECT SUM(Budget) FROM AreaBudget WHERE Population > 1000000;
Delete all farms in India that do not use drip irrigation.
CREATE TABLE farms (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255),drip_irrigation BOOLEAN); INSERT INTO farms (id,name,country,drip_irrigation) VALUES (1,'Farm 1','India',true),(2,'Farm 2','India',false),(3,'Farm 3','India',true);
DELETE FROM farms WHERE country = 'India' AND drip_irrigation = false;
What is the total number of military equipment sales by each defense contractor?
CREATE TABLE MilitaryEquipmentSalesByContractor (saleID INT,equipmentName VARCHAR(255),quantity INT,company VARCHAR(255)); INSERT INTO MilitaryEquipmentSalesByContractor (saleID,equipmentName,quantity,company) VALUES (1,'M1 Abrams Tank',100,'General Dynamics'); INSERT INTO MilitaryEquipmentSalesByContractor (saleID,equipmentName,quantity,company) VALUES (2,'M1 Abrams Tank',50,'General Dynamics');
SELECT company, SUM(quantity) AS total_sales FROM MilitaryEquipmentSalesByContractor GROUP BY company;
List all mining projects in the African continent that have a start date on or after 2010-01-01 and have a reported environmental impact?
CREATE TABLE projects (id INT,name TEXT,continent TEXT,start_date DATE,end_date DATE,environmental_impact TEXT); INSERT INTO projects (id,name,continent,start_date,end_date,environmental_impact) VALUES (1,'Ghana Gold','Africa','2010-02-01','2022-12-31','high'),(2,'Namibia Uranium','Africa','2005-05-15','2025-04-30','low');
SELECT name FROM projects WHERE continent = 'Africa' AND start_date >= '2010-01-01' AND environmental_impact IS NOT NULL;
List all virtual tours in Japan with a price under 10 USD.
CREATE TABLE VirtualTours (id INT,name TEXT,country TEXT,price FLOAT); INSERT INTO VirtualTours (id,name,country,price) VALUES (1,'Virtual Tokyo Tour','Japan',8.5),(2,'Japan Virtual Cultural Tour','Japan',12.0);
SELECT * FROM VirtualTours WHERE country = 'Japan' AND price < 10;
What is the distribution of clean energy policy trends by income level of countries?
CREATE TABLE policy_trends_high_income (country VARCHAR(255),trend VARCHAR(255)); INSERT INTO policy_trends_high_income (country,trend) VALUES ('US','Renewable Energy'),('UK','Carbon Pricing'),('Japan','Energy Efficiency'); CREATE TABLE policy_trends_low_income (country VARCHAR(255),trend VARCHAR(255)); INSERT INTO policy_trends_low_income (country,trend) VALUES ('India','Renewable Energy'),('Bangladesh','Energy Efficiency'),('Ethiopia','Carbon Pricing');
SELECT country, COUNT(trend) AS num_trends, 100.0 * COUNT(trend) / (SELECT COUNT(*) FROM policy_trends_high_income) AS percent FROM policy_trends_high_income GROUP BY country UNION ALL SELECT country, COUNT(trend) AS num_trends, 100.0 * COUNT(trend) / (SELECT COUNT(*) FROM policy_trends_low_income) AS percent FROM policy_trends_low_income GROUP BY country;
What is the total claim amount for policyholders in the 'FL' region?
CREATE TABLE Policyholders (PolicyID INT,PolicyholderName TEXT,State TEXT); INSERT INTO Policyholders (PolicyID,PolicyholderName,State) VALUES (1,'John Smith','FL'),(2,'Jane Doe','NY'); CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimAmount INT); INSERT INTO Claims (ClaimID,PolicyID,ClaimAmount) VALUES (1,1,5000),(2,1,3000),(3,2,7000);
SELECT SUM(Claims.ClaimAmount) FROM Claims INNER JOIN Policyholders ON Claims.PolicyID = Policyholders.PolicyID WHERE Policyholders.State = 'FL';
Which investment strategies have had at least one transaction per day for the past week in a hedge fund?
CREATE TABLE investment_strategies (strategy_id INT,name VARCHAR(255)); CREATE TABLE hedge_fund_transactions (transaction_id INT,strategy_id INT,amount DECIMAL(10,2),trans_date DATE);
SELECT investment_strategies.name FROM investment_strategies INNER JOIN hedge_fund_transactions ON investment_strategies.strategy_id = hedge_fund_transactions.strategy_id WHERE hedge_fund_transactions.trans_date >= NOW() - INTERVAL '1 week' GROUP BY investment_strategies.name HAVING COUNT(DISTINCT hedge_fund_transactions.trans_date) >= 7;
What is the total cost of dam projects in the South region that were completed after 2015?
CREATE TABLE InfrastructureProjects (id INT,name VARCHAR(100),region VARCHAR(50),project_type VARCHAR(50),cost FLOAT,completion_date DATE); INSERT INTO InfrastructureProjects (id,name,region,project_type,cost,completion_date) VALUES (1,'Atlanta Dam','South','dam',15000000,'2016-01-01');
SELECT SUM(cost) FROM InfrastructureProjects WHERE region = 'South' AND project_type = 'dam' AND completion_date > '2015-01-01';
What is the percentage of donation amount by each program category?
CREATE TABLE Programs (ProgramID INT,ProgramName TEXT,ProgramCategory TEXT,Budget DECIMAL); INSERT INTO Programs (ProgramID,ProgramName,ProgramCategory,Budget) VALUES (1,'Education','Social',15000.00),(2,'Healthcare','Health',20000.00),(3,'Environment','Environment',10000.00); CREATE TABLE Donors (DonorID INT,DonorName TEXT,DonationAmount DECIMAL,ProgramCategory TEXT); INSERT INTO Donors (DonorID,DonorName,DonationAmount,ProgramCategory) VALUES (1,'John Doe',500.00,'Social'),(2,'Jane Smith',350.00,'Health'),(3,'Alice Johnson',700.00,'Environment');
SELECT ProgramCategory, SUM(DonationAmount) as TotalDonation, (SUM(DonationAmount)/SUM(Budget))*100 as Percentage FROM Programs P INNER JOIN Donors D ON P.ProgramCategory = D.ProgramCategory GROUP BY ProgramCategory;
Identify the number of green building projects in Europe, as well as the count of each building type in ascending order.
CREATE TABLE green_buildings (id INT,region VARCHAR(20),building_type VARCHAR(20),certification_level VARCHAR(10)); INSERT INTO green_buildings (id,region,building_type,certification_level) VALUES (1,'Europe','Residential','Gold'),(2,'Europe','Commercial','Platinum'),(3,'Europe','Residential','Silver'),(4,'Europe','Mixed-use','Gold'),(5,'Europe','Commercial','Silver');
SELECT building_type, COUNT(*) AS count FROM green_buildings WHERE region = 'Europe' GROUP BY building_type ORDER BY count ASC;
Find the total duration of 'pilates' and 'barre' classes offered in a week.
CREATE TABLE class_schedule (class_type VARCHAR(50),start_time TIME,end_time TIME,duration INT); INSERT INTO class_schedule (class_type,start_time,end_time,duration) VALUES ('yoga','06:00:00','07:00:00',60),('spinning','07:00:00','08:00:00',60),('yoga','17:00:00','18:00:00',60),('pilates','08:00:00','09:00:00',60),('barre','09:00:00','10:00:00',60),('yoga','18:00:00','19:00:00',60);
SELECT SUM(duration) FROM class_schedule WHERE class_type IN ('pilates', 'barre') AND start_time BETWEEN '00:00:00' AND '23:59:59' GROUP BY class_type;
Show the total number of food safety violations for each type of violation, excluding any types with zero violations.
CREATE TABLE violations (id INT,region TEXT,violation_type TEXT,date DATE);
SELECT violation_type, COUNT(*) as total_violations FROM violations GROUP BY violation_type HAVING total_violations > 0;
What is the total investment amount for startups founded by women in the Fintech industry?
CREATE TABLE startup (id INT,name TEXT,founder_gender TEXT,industry TEXT); CREATE TABLE investment (startup_id INT,investment_amount INT); INSERT INTO startup (id,name,founder_gender,industry) VALUES (1,'Sigma Corp','Female','Fintech'); INSERT INTO investment (startup_id,investment_amount) VALUES (1,2000000); INSERT INTO startup (id,name,founder_gender,industry) VALUES (2,'Tau Inc','Male','Fintech'); INSERT INTO investment (startup_id,investment_amount) VALUES (2,1200000);
SELECT SUM(i.investment_amount) FROM startup s INNER JOIN investment i ON s.id = i.startup_id WHERE s.founder_gender = 'Female' AND s.industry = 'Fintech';
How many biosensors were developed by each organization in 2021?
CREATE TABLE biosensor_development (id INT,organization TEXT,year INT,quantity INT); INSERT INTO biosensor_development (id,organization,year,quantity) VALUES (1,'BioTech Inc',2021,120);
SELECT organization, SUM(quantity) FROM biosensor_development WHERE year = 2021 GROUP BY organization;
What is the distribution of security incidents by day of the week in the past month?
CREATE TABLE incident_days (id INT,incidents INT,day VARCHAR(10),timestamp TIMESTAMP); INSERT INTO incident_days (id,incidents,day,timestamp) VALUES (1,10,'Monday','2022-02-01 10:00:00'),(2,12,'Tuesday','2022-02-02 12:00:00');
SELECT day, SUM(incidents) as total_incidents FROM incident_days WHERE timestamp >= '2022-02-01' AND timestamp < '2022-03-01' GROUP BY day;
How many medical supplies were shipped to Bangladesh in the first quarter of 2022?
CREATE TABLE medical_supplies (id INT,name TEXT,shipped_date DATE); INSERT INTO medical_supplies VALUES (1,'Bandages','2022-01-10'); INSERT INTO medical_supplies VALUES (2,'Medicine','2022-01-12');
SELECT COUNT(*) FROM medical_supplies WHERE shipped_date >= '2022-01-01' AND shipped_date < '2022-04-01' AND name = 'Bangladesh';
What is the maximum balance for any account owned by clients in the United Kingdom?
CREATE TABLE clients (id INT,country VARCHAR(20));CREATE TABLE accounts (id INT,client_id INT,balance FLOAT); INSERT INTO clients (id,country) VALUES (1,'United Kingdom'),(2,'United States'),(3,'Canada'),(4,'United Kingdom'); INSERT INTO accounts (id,client_id,balance) VALUES (1,1,10000),(2,1,12000),(3,2,15000),(4,3,8000),(5,4,18000);
SELECT MAX(balance) FROM accounts a JOIN clients c ON a.client_id = c.id WHERE c.country = 'United Kingdom';
What is the average cultural competency score of community health workers by state?
CREATE TABLE states (state_id INT,state_name VARCHAR(100)); INSERT INTO states (state_id,state_name) VALUES (1,'California'),(2,'Texas'),(3,'New York'); CREATE TABLE community_health_workers (worker_id INT,state_id INT,cultural_competency_score INT); INSERT INTO community_health_workers (worker_id,state_id,cultural_competency_score) VALUES (1,1,85),(2,1,90),(3,2,80),(4,3,95),(5,1,92);
SELECT S.state_name, AVG(cultural_competency_score) as avg_score FROM community_health_workers CHW JOIN states S ON CHW.state_id = S.state_id GROUP BY S.state_name;
What is the total number of public participation events in each city, partitioned by event type?
CREATE TABLE PublicEvents (city VARCHAR(50),event_type VARCHAR(50),participation INT); INSERT INTO PublicEvents (city,event_type,participation) VALUES ('CityA','Workshop',50),('CityA','Meeting',30),('CityB','Workshop',40),('CityB','Meeting',60);
SELECT city, event_type, SUM(participation) AS total_participation FROM PublicEvents GROUP BY city, event_type;
how many victims of hate crimes were there in California in the year 2020?
CREATE TABLE hate_crimes (id INT,state TEXT,year INT,victims INT); INSERT INTO hate_crimes (id,state,year,victims) VALUES (1,'California',2019,1234); INSERT INTO hate_crimes (id,state,year,victims) VALUES (2,'California',2020,5678);
SELECT victims FROM hate_crimes WHERE state = 'California' AND year = 2020;
List all unique exit strategies for startups in the transportation sector founded by BIPOC entrepreneurs.
CREATE TABLE exit_strategy (id INT,company_id INT,strategy TEXT); INSERT INTO exit_strategy (id,company_id,strategy) VALUES (1,1,'Merger'); CREATE TABLE company (id INT,name TEXT,industry TEXT,founder_race TEXT); INSERT INTO company (id,name,industry,founder_race) VALUES (1,'Via','Transportation','BIPOC');
SELECT DISTINCT strategy FROM exit_strategy INNER JOIN company ON exit_strategy.company_id = company.id WHERE industry = 'Transportation' AND founder_race = 'BIPOC';
What is the average age of volunteers for a specific cause?
CREATE TABLE causes (id INT,name TEXT); CREATE TABLE volunteers (id INT,name TEXT,age INT,cause_id INT); INSERT INTO causes (id,name) VALUES (1,'Cause A'),(2,'Cause B'); INSERT INTO volunteers (id,name,age,cause_id) VALUES (1,'John Doe',30,1),(2,'Jane Smith',25,1),(3,'Mary Johnson',45,2);
SELECT causes.name, AVG(volunteers.age) as avg_age FROM causes JOIN volunteers ON causes.id = volunteers.cause_id GROUP BY causes.name;
Count the number of successful PTSD treatment outcomes for veterans in the United States.
CREATE TABLE patients (patient_id INT,patient_name VARCHAR(50),condition VARCHAR(50),country VARCHAR(50),veteran_status VARCHAR(50),treatment_outcome VARCHAR(50)); INSERT INTO patients (patient_id,patient_name,condition,country,veteran_status,treatment_outcome) VALUES (1,'James Smith','PTSD','USA','Veteran','Successful'),(2,'Olivia Brown','PTSD','USA','Civilian','Successful');
SELECT COUNT(patient_id) FROM patients WHERE patients.condition = 'PTSD' AND patients.country = 'USA' AND patients.veteran_status = 'Veteran' AND patients.treatment_outcome = 'Successful';
What is the average production quantity for wells in the 'North Sea' that have a production quantity greater than 1000?
CREATE TABLE wells (id INT,name VARCHAR(255),location VARCHAR(255),production_quantity INT); INSERT INTO wells (id,name,location,production_quantity) VALUES (1,'Well A','North Sea',1000),(2,'Well B','North Sea',1200),(3,'Well C','North Sea',1500);
SELECT AVG(production_quantity) FROM wells WHERE location = 'North Sea' AND production_quantity > 1000;
What is the average salary of workers in each country?
CREATE TABLE workers (id INT,country VARCHAR(255),salary FLOAT);
SELECT country, AVG(salary) FROM workers GROUP BY country;
What is the average attendance at events held in Canada in the year 2021?
CREATE TABLE Events (EventID int,EventDate date,Attendees int,Country varchar(50)); INSERT INTO Events (EventID,EventDate,Attendees,Country) VALUES (1,'2021-01-01',100,'Canada'),(2,'2021-02-01',150,'Canada'),(3,'2021-03-01',75,'Canada');
SELECT AVG(Attendees) FROM Events WHERE Country = 'Canada' AND EventDate BETWEEN '2021-01-01' AND '2021-12-31';
Find the number of male and female employees in each department.
CREATE TABLE departments (dept_id INT,dept_name VARCHAR(255));CREATE TABLE employees (emp_id INT,emp_name VARCHAR(255),dept_id INT,gender VARCHAR(10)); INSERT INTO departments (dept_id,dept_name) VALUES (1,'HR'),(2,'IT'); INSERT INTO employees (emp_id,emp_name,dept_id,gender) VALUES (1,'John Doe',1,'Male'),(2,'Jane Smith',1,'Female'),(3,'Alice Johnson',2,'Female'),(4,'Bob Brown',2,'Male');
SELECT dept_name, gender, COUNT(*) as count FROM employees e JOIN departments d ON e.dept_id = d.dept_id GROUP BY dept_name, gender;
Show the total weight of all imported products during the month of 'January'
CREATE TABLE imports (import_id INT,import_date DATE,weight INT,country TEXT,product TEXT); INSERT INTO imports (import_id,import_date,weight,country,product) VALUES (1,'2022-01-01',500,'China','Fish'),(2,'2022-01-05',600,'Japan','Fish'),(3,'2022-02-10',700,'India','Fish'),(4,'2022-03-15',800,'Indonesia','Fish');
SELECT SUM(weight) FROM imports WHERE MONTH(import_date) = 1;
What is the total number of collective bargaining agreements in the 'service' industry?
CREATE TABLE cb_agreements (id INT,union_id INT,industry VARCHAR(255),cb_agreements INT); INSERT INTO cb_agreements (id,union_id,industry,cb_agreements) VALUES (1,1,'service',3);
SELECT SUM(cb_agreements) FROM cb_agreements WHERE industry = 'service';
What is the total investment in projects with a gender equality focus?
CREATE TABLE projects (id INT,name TEXT,focus TEXT,investment FLOAT); INSERT INTO projects (id,name,focus,investment) VALUES (1,'Clean Water Initiative','Gender Equality',75000.0),(2,'Sustainable Agriculture','Climate Action',125000.0);
SELECT SUM(investment) FROM projects WHERE focus = 'Gender Equality';
What is the percentage of sales revenue for cruelty-free products in H1 2022?
CREATE TABLE sales (product VARCHAR(255),sale_date DATE,revenue NUMERIC(10,2),is_cruelty_free BOOLEAN); INSERT INTO sales (product,sale_date,revenue,is_cruelty_free) VALUES ('Eyeliner','2022-01-01',500,true),('Lipstick','2022-01-03',300,false),('Moisturizer','2022-01-05',700,true),('Conditioner','2022-01-07',600,false),('Eyeshadow','2022-02-01',400,true);
SELECT (SUM(revenue) / (SELECT SUM(revenue) FROM sales WHERE sale_date BETWEEN '2022-01-01' AND '2022-06-30' AND is_cruelty_free = true) * 100) as percentage FROM sales WHERE sale_date BETWEEN '2022-01-01' AND '2022-06-30' AND is_cruelty_free = true;
Delete all mobile subscribers in New York who have not used their service in the last 6 months.
CREATE TABLE mobile_subscribers (id INT,subscriber_name VARCHAR(50),state VARCHAR(20),last_usage DATE);
DELETE FROM mobile_subscribers WHERE state = 'New York' AND last_usage < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
List all satellite images for 'field10' taken in the last 14 days.
CREATE TABLE field10 (id INT,image_date DATE); INSERT INTO field10 (id,image_date) VALUES (1,'2021-11-18'),(2,'2021-11-19'),(3,'2021-11-21');
SELECT * FROM field10 WHERE image_date >= (CURRENT_DATE - INTERVAL '14 days');
Which artists contributed the most to the museum's collection in Africa?
CREATE TABLE artists (id INT,name TEXT,country TEXT,works_count INT); INSERT INTO artists (id,name,country,works_count) VALUES (1,'Nana Oforiatta Ayim','Ghana',15),(2,'Wanuri Kahiu','Kenya',20),(3,'Bisi Silva','Nigeria',25),(4,'El Anatsui','Ghana',30),(5,'Peju Alatise','Nigeria',18);
SELECT name, SUM(works_count) AS total_works FROM artists WHERE country IN ('Ghana', 'Kenya', 'Nigeria') GROUP BY name ORDER BY total_works DESC;
How many energy efficiency projects were implemented in each country in 2019?
CREATE TABLE if not exists energy_efficiency_projects (project_id integer,project_date date,country varchar(255)); INSERT INTO energy_efficiency_projects (project_id,project_date,country) VALUES (1,'2019-01-01','USA'),(2,'2019-02-15','Canada'),(3,'2019-07-01','Mexico'),(4,'2019-12-31','Brazil');
SELECT country, COUNT(*) as num_projects FROM energy_efficiency_projects WHERE project_date BETWEEN '2019-01-01' AND '2019-12-31' GROUP BY country;
List all air defense systems in the 'Europe' schema.
CREATE SCHEMA Europe; CREATE TABLE AirDefenseSystems (id INT,name VARCHAR(255),type VARCHAR(255),location VARCHAR(255)); INSERT INTO AirDefenseSystems (id,name,type,location) VALUES (1,'Patriot','Missile System','Germany'); INSERT INTO AirDefenseSystems (id,name,type,location) VALUES (2,'S-300','Missile System','Russia');
SELECT * FROM Europe.AirDefenseSystems;
List the top 3 donors from the United States based on their total donation amount in 2021.
CREATE TABLE Donors (id INT,name TEXT,country TEXT,donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (1,'John Doe','USA',250.00,'2021-03-01'); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (2,'Jane Smith','Canada',100.00,'2021-02-15'); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (3,'Alice Johnson','USA',500.00,'2021-05-05'); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (4,'Bob Brown','USA',300.00,'2021-07-10');
SELECT name, SUM(donation_amount) AS total_donation FROM Donors WHERE country = 'USA' AND YEAR(donation_date) = 2021 GROUP BY name ORDER BY total_donation DESC LIMIT 3;
What is the average response time for emergency services in each city?
CREATE TABLE Emergency_Services (city_id INT,response_time INT); INSERT INTO Emergency_Services (city_id,response_time) VALUES (1,8),(1,9),(2,7),(2,6),(3,9),(3,8),(4,6),(4,5); CREATE TABLE Cities (id INT,name VARCHAR(50)); INSERT INTO Cities (id,name) VALUES (1,'New York'),(2,'Los Angeles'),(3,'Chicago'),(4,'Houston');
SELECT C.name, AVG(ES.response_time) as Avg_Response_Time FROM Emergency_Services ES JOIN Cities C ON ES.city_id = C.id GROUP BY C.name;
Which glacier has the largest size in the region with the highest average temperature?
CREATE TABLE glaciers (id INT PRIMARY KEY,name VARCHAR(255),size INT,latitude FLOAT,longitude FLOAT,region VARCHAR(255)); INSERT INTO glaciers (id,name,size,latitude,longitude,region) VALUES (1,'Glacier A',150,78.9,15.1,'Arctic'),(2,'Glacier B',200,75.5,-125.3,'Antarctic'),(3,'Glacier C',120,68.7,14.2,'Arctic'),(4,'Glacier D',250,63.4,-168.5,'Antarctic');
SELECT g.name, g.size FROM glaciers g INNER JOIN (SELECT region, AVG(latitude) AS avg_temp FROM glaciers GROUP BY region ORDER BY avg_temp DESC LIMIT 1) r ON g.region = r.region WHERE g.size = (SELECT MAX(size) FROM glaciers WHERE region = r.region);
What was the total revenue for the state of Oregon in the third quarter of 2022?
CREATE TABLE sales (id INT,state VARCHAR(50),quarter INT,revenue FLOAT); INSERT INTO sales (id,state,quarter,revenue) VALUES (1,'California',1,25000.0),(2,'California',2,30000.0),(3,'Colorado',1,20000.0),(4,'Colorado',2,28000.0),(5,'Oregon',3,29000.0);
SELECT SUM(revenue) FROM sales WHERE state = 'Oregon' AND quarter = 3;
Find the average age of patients in each state in the 'patients' table, ordered by the average age in ascending order.
CREATE TABLE patients (patient_id INT PRIMARY KEY AUTO_INCREMENT,first_name VARCHAR(50),last_name VARCHAR(50),age INT,gender VARCHAR(10),ethnicity VARCHAR(50),state VARCHAR(20));
SELECT state, AVG(age) as avg_age FROM patients GROUP BY state ORDER BY avg_age ASC;
What is the total number of public schools and public hospitals in the state of Texas?
CREATE TABLE tx_schools (school_type VARCHAR(20),num_schools INT); INSERT INTO tx_schools (school_type,num_schools) VALUES ('public',4000),('private',1000); CREATE TABLE tx_hospitals (hospital_type VARCHAR(20),num_hospitals INT); INSERT INTO tx_hospitals (hospital_type,num_hospitals) VALUES ('public',450),('private',550);
SELECT 4000 + COALESCE((SELECT num_hospitals FROM tx_hospitals WHERE hospital_type = 'public'), 0) AS total_schools_hospitals;
What is the total quantity of item 'BBB' shipped to each city?
CREATE TABLE shipments (shipment_id INT,item_code VARCHAR(5),warehouse_id VARCHAR(5),quantity INT,city VARCHAR(5)); CREATE TABLE warehouses (warehouse_id VARCHAR(5),city VARCHAR(5),state VARCHAR(3)); INSERT INTO shipments VALUES (1,'AAA','LAX',200,'Los Angeles'),(2,'BBB','NYC',300,'New York'),(3,'AAA','LAX',100,'Los Angeles'),(4,'CCC','NYC',50,'New York'),(5,'BBB','LAX',150,'Los Angeles'); INSERT INTO warehouses VALUES ('LAX','Los',' Angeles'),('NYC','New',' York'),('JFK','New',' York');
SELECT city, SUM(quantity) FROM shipments WHERE item_code = 'BBB' GROUP BY city;