instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Insert a new record into the 'Sustainable_Sources' table with id 1, vendor 'Eco-Friendly Farms', product 'Organic Chicken', and sustainable BOOLEAN as TRUE.
CREATE TABLE Sustainable_Sources (id INT,vendor VARCHAR(255),product VARCHAR(255),sustainable BOOLEAN); INSERT INTO Sustainable_Sources (id,vendor,product,sustainable) VALUES ((SELECT MAX(id) FROM Sustainable_Sources) + 1,'Eco-Friendly Farms','Organic Chicken',TRUE);
INSERT INTO Sustainable_Sources (vendor, product, sustainable) VALUES ('Eco-Friendly Farms', 'Organic Chicken', TRUE);
Delete all records of sales of non-sustainable hair care products in Australia.
CREATE TABLE HairCareSales (sale_id INT,product_name VARCHAR(100),category VARCHAR(50),price DECIMAL(10,2),quantity INT,sale_date DATE,country VARCHAR(50),sustainable BOOLEAN);
DELETE FROM HairCareSales WHERE category = 'Hair Care' AND country = 'Australia' AND sustainable = FALSE;
What is the total revenue generated by each dispensary in Arizona, grouped by dispensary and ordered by revenue from highest to lowest?
CREATE TABLE dispensaries (dispensary_id INT,name TEXT,state TEXT); INSERT INTO dispensaries (dispensary_id,name,state) VALUES (1,'Dispensary A','Arizona'),(2,'Dispensary B','Arizona'),(3,'Dispensary C','California'); CREATE TABLE sales (sale_id INT,dispensary_id INT,revenue INT); INSERT INTO sales (sale_id,dispensary_...
SELECT d.name, SUM(s.revenue) AS total_revenue FROM dispensaries d JOIN sales s ON d.dispensary_id = s.dispensary_id WHERE d.state = 'Arizona' GROUP BY d.name ORDER BY total_revenue DESC;
List all infectious diseases recorded in hospitals located in New York and New Jersey
CREATE TABLE hospitals (id INT,name TEXT,state TEXT); CREATE TABLE infectious_diseases (id INT,hospital_id INT,disease TEXT); INSERT INTO hospitals (id,name,state) VALUES (1,'Hospital X','New York'),(2,'Hospital Y','New Jersey'); INSERT INTO infectious_diseases (id,hospital_id,disease) VALUES (1,1,'Measles'),(2,1,'Tube...
SELECT i.disease FROM hospitals h INNER JOIN infectious_diseases i ON h.id = i.hospital_id WHERE h.state IN ('New York', 'New Jersey');
What is the average number of AI-powered features offered by hotels in the 'hotel_tech_adoption' table?
CREATE TABLE hotel_tech_adoption (hotel_id INT,ai_powered_features INT); INSERT INTO hotel_tech_adoption (hotel_id,ai_powered_features) VALUES (1,5),(2,3),(3,4),(4,6);
SELECT AVG(ai_powered_features) FROM hotel_tech_adoption;
Which movies in the "movies" table were released in the 2010s?
CREATE TABLE movies (id INT,title VARCHAR(100),release_year INT);
SELECT * FROM movies WHERE release_year BETWEEN 2010 AND 2019;
Determine the cosmetic products that are NOT certified as cruelty-free in the US region.
CREATE TABLE products (product_id INT,product_name VARCHAR(50),region VARCHAR(20),cruelty_free BOOLEAN); INSERT INTO products (product_id,product_name,region,cruelty_free) VALUES (1,'Lipstick','Canada',TRUE),(2,'Foundation','US',FALSE),(3,'Eyeshadow','US',TRUE);
SELECT * FROM products WHERE region = 'US' AND cruelty_free = FALSE;
What is the ZIP code of the community health worker who conducted the least mental health parity consultations in Illinois?
CREATE TABLE community_health_workers (id INT,name TEXT,zip TEXT,consultations INT); INSERT INTO community_health_workers (id,name,zip,consultations) VALUES (1,'John Doe','60001',40),(2,'Jane Smith','60601',20); CREATE VIEW il_workers AS SELECT * FROM community_health_workers WHERE zip BETWEEN '60001' AND '62999';
SELECT zip FROM il_workers WHERE consultations = (SELECT MIN(consultations) FROM il_workers);
What is the change in housing affordability in Boston from Q1 2021 to Q2 2021?
CREATE TABLE boston_housing (id INT,quarter INT,year INT,affordability FLOAT); INSERT INTO boston_housing (id,quarter,year,affordability) VALUES (1,1,2021,90),(2,2,2021,85),(3,1,2021,95),(4,2,2021,80);
SELECT (MAX(affordability) FILTER (WHERE year = 2021 AND quarter = 2) - MAX(affordability) FILTER (WHERE year = 2021 AND quarter = 1)) FROM boston_housing;
Delete all volunteer records for organizations located in Oceania with no donations in 2022.
CREATE TABLE org_volunteers (org_id INT,org_name VARCHAR(50),num_volunteers INT,country VARCHAR(50)); CREATE TABLE donations (donation_id INT,org_id INT,donation_amount FLOAT,donation_date DATE); INSERT INTO org_volunteers (org_id,org_name,num_volunteers,country) VALUES (1,'Australian Red Cross',50,'Australia'),(2,'New...
DELETE FROM org_volunteers WHERE org_id NOT IN (SELECT org_id FROM donations WHERE donation_date BETWEEN '2022-01-01' AND '2022-12-31') AND country IN ('Australia', 'New Zealand', 'Fiji', 'Papua New Guinea', 'Solomon Islands');
What is the maximum transaction value for each customer in the last year?
CREATE TABLE transactions (id INT,customer_id INT,value DECIMAL(10,2),transaction_date DATE); INSERT INTO transactions (id,customer_id,value,transaction_date) VALUES (1,1,100,'2022-01-01'),(2,1,200,'2022-01-15'),(3,2,50,'2022-01-05'),(4,2,150,'2022-01-30'),(5,3,300,'2022-01-20');
SELECT c.id, MAX(t.value) FROM customers c INNER JOIN transactions t ON c.id = t.customer_id WHERE t.transaction_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY c.id;
What is the average fare and its corresponding currency for each route, along with the fare of the previous record, ordered by fare date?
CREATE TABLE fares (fare_id INT,route_id INT,fare FLOAT,fare_currency VARCHAR(3),fare_date DATE); INSERT INTO fares (fare_id,route_id,fare,fare_currency,fare_date) VALUES (1,1,3.0,'USD','2022-05-01'),(2,2,4.0,'USD','2022-05-02'),(3,1,3.5,'USD','2022-05-03');
SELECT route_id, fare, fare_currency, fare_date, LAG(fare) OVER (PARTITION BY route_id ORDER BY fare_date) as prev_fare FROM fares;
What is the total weight of non-organic products sourced from local suppliers?
CREATE TABLE suppliers (id INT,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE products (id INT,name VARCHAR(255),organic BOOLEAN,weight FLOAT,supplier_id INT);
SELECT SUM(p.weight) as total_weight FROM suppliers s INNER JOIN products p ON s.id = p.supplier_id WHERE p.organic = 'f' AND s.country = 'USA';
Update the mental health score of the student with the highest ID who has not participated in lifelong learning activities.
CREATE TABLE students (student_id INT,mental_health_score INT,participated_in_lifelong_learning BOOLEAN); INSERT INTO students (student_id,mental_health_score,participated_in_lifelong_learning) VALUES (1,80,FALSE),(2,70,FALSE),(3,90,FALSE),(4,60,TRUE);
UPDATE students SET mental_health_score = 85 WHERE student_id = (SELECT MAX(student_id) FROM students WHERE participated_in_lifelong_learning = FALSE);
What is the total number of labor disputes in each quarter for the year 2020, based on the 'disputes_2020' table?
CREATE TABLE disputes_2020 (id INT,dispute_count INT,date DATE); INSERT INTO disputes_2020 (id,dispute_count,date) VALUES (1,50,'2020-01-01'),(2,35,'2020-04-15'),(3,40,'2020-07-01');
SELECT QUARTER(date) as quarter, SUM(dispute_count) as total_disputes FROM disputes_2020 GROUP BY quarter;
What is the total number of public parks in New York and California?
CREATE TABLE public_parks (name VARCHAR(255),state VARCHAR(255),acres DECIMAL(10,2)); INSERT INTO public_parks (name,state,acres) VALUES ('Central Park','New York',843),('Prospect Park','New York',585),('Golden Gate Park','California',1017);
SELECT SUM(acres) FROM public_parks WHERE state IN ('New York', 'California');
What are the total quantities of gold and silver mined in the USA and Canada?
CREATE TABLE mine_stats (country VARCHAR(20),mineral VARCHAR(20),quantity INT); INSERT INTO mine_stats (country,mineral,quantity) VALUES ('USA','gold',500),('USA','silver',2000),('Canada','gold',800),('Canada','silver',1500);
SELECT country, SUM(quantity) FROM mine_stats WHERE mineral IN ('gold', 'silver') GROUP BY country;
What is the sum of cybersecurity threats reported in the North American region in 2022?
CREATE TABLE Threats (threat_id INT,threat_type VARCHAR(50),year INT,region_id INT); INSERT INTO Threats (threat_id,threat_type,year,region_id) VALUES (1,'Cybersecurity threat',2022,1),(2,'Terrorism',2021,1);
SELECT SUM(threat_id) FROM Threats WHERE threat_type = 'Cybersecurity threat' AND year = 2022 AND region_id = (SELECT region_id FROM Regions WHERE region_name = 'North American');
What are the maximum and minimum confidence scores for AI models in AI safety in Asia?
CREATE TABLE ai_safety (id INT,model_name VARCHAR(255),country VARCHAR(255),confidence_score FLOAT); INSERT INTO ai_safety (id,model_name,country,confidence_score) VALUES (1,'SafeModelA','China',0.75),(2,'SafeModelB','Japan',0.90),(3,'SafeModelC','India',0.85);
SELECT MAX(confidence_score), MIN(confidence_score) FROM ai_safety WHERE country IN ('China', 'Japan', 'India');
What is the average fine amount issued in traffic court, broken down by the day of the week?
CREATE TABLE traffic_court_fines (id INT,fine_amount DECIMAL(5,2),fine_date DATE);
SELECT DATE_FORMAT(fine_date, '%W') AS day_of_week, AVG(fine_amount) FROM traffic_court_fines GROUP BY day_of_week;
What is the average attendance for home games of the New York Yankees?
CREATE TABLE baseball_games (game_id INT,season_year INT,home_team VARCHAR(50),away_team VARCHAR(50),home_attendance INT,away_attendance INT);
SELECT AVG(home_attendance) FROM baseball_games WHERE home_team = 'New York Yankees';
Find the top 3 most expensive garments by their retail price.
CREATE TABLE Garments (garment_id INT,garment_name VARCHAR(50),retail_price DECIMAL(5,2)); INSERT INTO Garments (garment_id,garment_name,retail_price) VALUES (1,'Sequin Evening Gown',850.99),(2,'Cashmere Sweater',250.00),(3,'Silk Blouse',150.00);
SELECT garment_name, retail_price FROM (SELECT garment_name, retail_price, ROW_NUMBER() OVER (ORDER BY retail_price DESC) as rn FROM Garments) sub WHERE rn <= 3;
List the top 5 drugs by R&D expenditure in 2021, with a running total of their R&D costs.
CREATE TABLE r_and_d_expenditures (id INT,drug_name VARCHAR(255),r_and_d_cost DECIMAL(10,2),expenditure_date DATE);
SELECT drug_name, r_and_d_cost, SUM(r_and_d_cost) OVER (ORDER BY r_and_d_cost DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as running_total FROM r_and_d_expenditures WHERE expenditure_date BETWEEN '2021-01-01' AND '2021-12-31' ORDER BY running_total DESC, drug_name LIMIT 5;
What is the distribution of severity scores for vulnerabilities in the VulnAssess table?
CREATE TABLE VulnAssess (systemName VARCHAR(50),severityScore INT); INSERT INTO VulnAssess (systemName,severityScore) VALUES ('SystemA',7),('SystemB',5),('SystemC',3),('SystemD',6),('SystemE',8);
SELECT severityScore, COUNT(*) FROM VulnAssess GROUP BY severityScore;
What is the average order value per customer from the United States?
CREATE TABLE customers (customer_id INT,customer_name TEXT,country TEXT); INSERT INTO customers (customer_id,customer_name,country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Canada'); CREATE TABLE orders (order_id INT,customer_id INT,order_value DECIMAL); INSERT INTO orders (order_id,customer_id,order_value) VALUES ...
SELECT AVG(order_value) FROM orders JOIN customers ON orders.customer_id = customers.customer_id WHERE customers.country = 'USA';
What is the maximum temperature recorded in Greenland in July 2019?
CREATE TABLE WeatherData (location VARCHAR(50),date DATE,temperature DECIMAL(5,2)); INSERT INTO WeatherData (location,date,temperature) VALUES ('Greenland','2019-07-01',12.3),('Greenland','2019-07-02',15.1);
SELECT MAX(temperature) FROM WeatherData WHERE location = 'Greenland' AND date BETWEEN '2019-07-01' AND '2019-07-31';
What was the average time taken for restorative justice cases in the first quarter of 2021?
CREATE TABLE restorative_justice (case_id INT,quarter INT,year INT,time_taken INT); INSERT INTO restorative_justice (case_id,quarter,year,time_taken) VALUES (1,1,2021,30),(2,1,2021,45),(3,1,2021,60);
SELECT AVG(time_taken) as avg_time FROM restorative_justice WHERE quarter = 1 AND year = 2021;
What are the average fan demographics (age and gender) for each team?
CREATE TABLE fans (fan_id INT,team_id INT,age INT,gender VARCHAR(10)); INSERT INTO fans (fan_id,team_id,age,gender) VALUES (1,1,35,'Male'); INSERT INTO fans (fan_id,team_id,age,gender) VALUES (2,2,45,'Female');
SELECT teams.team_name, AVG(fans.age) as avg_age, COUNT(CASE WHEN fans.gender = 'Male' THEN 1 ELSE NULL END) as male_count, COUNT(CASE WHEN fans.gender = 'Female' THEN 1 ELSE NULL END) as female_count FROM fans JOIN teams ON fans.team_id = teams.team_id GROUP BY teams.team_name;
What is the average fare of trains per route in the "fares" table?
CREATE TABLE fares (id INT,route_id INT,vehicle_type VARCHAR(255),fare DECIMAL); INSERT INTO fares (id,route_id,vehicle_type,fare) VALUES (1,1,'Train',5.00);
SELECT route_id, AVG(fare) FROM fares WHERE vehicle_type = 'Train' GROUP BY route_id;
What is the maximum budget allocated for any project in the infrastructure projects table?
CREATE TABLE infrastructure_projects (id INT,project_name TEXT,budget INT);INSERT INTO infrastructure_projects (id,project_name,budget) VALUES (1,'ProjectA',5000000),(2,'ProjectB',3000000),(3,'ProjectC',7000000);
SELECT MAX(budget) FROM infrastructure_projects;
What is the change in energy storage capacity in Japan between 2015 and 2018?
CREATE TABLE energy_storage (id INT,year INT,country VARCHAR(255),capacity FLOAT); INSERT INTO energy_storage (id,year,country,capacity) VALUES (1,2015,'Japan',120.5),(2,2016,'Japan',135.2),(3,2017,'Japan',142.1),(4,2018,'Japan',150.9);
SELECT (capacity - LAG(capacity) OVER (PARTITION BY country ORDER BY year)) FROM energy_storage WHERE country = 'Japan' AND year IN (2016, 2017, 2018);
What is the percentage of health equity metrics met by each community health worker in the Southeast region?
CREATE TABLE health_equity_metrics (id INT,worker_id INT,region VARCHAR(50),metric1 BOOLEAN,metric2 BOOLEAN,metric3 BOOLEAN); INSERT INTO health_equity_metrics (id,worker_id,region,metric1,metric2,metric3) VALUES (1,1,'Southeast',true,true,false),(2,2,'Southeast',true,false,true),(3,3,'Southeast',false,true,true);
SELECT worker_id, (SUM(CASE WHEN metric1 THEN 1 ELSE 0 END) + SUM(CASE WHEN metric2 THEN 1 ELSE 0 END) + SUM(CASE WHEN metric3 THEN 1 ELSE 0 END)) * 100.0 / 3 as percentage_met FROM health_equity_metrics WHERE region = 'Southeast' GROUP BY worker_id;
List the number of workplace safety incidents for each quarter in the 'WorkplaceSafety' table
CREATE TABLE WorkplaceSafety (id INT,quarter VARCHAR(10),incidents INT); INSERT INTO WorkplaceSafety (id,quarter,incidents) VALUES (1,'Q1',12),(2,'Q2',15),(3,'Q3',18);
SELECT quarter, SUM(incidents) as total_incidents FROM WorkplaceSafety GROUP BY quarter;
List the renewable energy production of each city in Japan, sorted in descending order.
CREATE TABLE renewable_energy_japan (id INT,city VARCHAR(255),production FLOAT); INSERT INTO renewable_energy_japan (id,city,production) VALUES (1,'Tokyo',2000),(2,'Osaka',1500),(3,'Nagoya',1200);
SELECT city, production FROM renewable_energy_japan ORDER BY production DESC;
What is the total revenue generated from sustainable tourism initiatives in Costa Rica?
CREATE TABLE sustainable_tourism (id INT,initiative VARCHAR(20),country VARCHAR(20),revenue DECIMAL(10,2)); INSERT INTO sustainable_tourism (id,initiative,country,revenue) VALUES (1,'Eco-Lodge','Costa Rica',5000.00),(2,'Birdwatching Tours','Costa Rica',3000.00);
SELECT SUM(revenue) FROM sustainable_tourism WHERE country = 'Costa Rica';
What is the average mental health score of students in 'High School X'?
CREATE TABLE HighSchoolX (studentID INT,mentalHealthScore INT); INSERT INTO HighSchoolX (studentID,mentalHealthScore) VALUES (1,80),(2,85),(3,70);
SELECT AVG(mentalHealthScore) FROM HighSchoolX WHERE schoolName = 'High School X';
Show all the players who have played more than 50 games
game_stats(player_id,game_id,score,date_played)
SELECT g.player_id, p.name FROM game_stats g JOIN players p ON g.player_id = p.player_id GROUP BY g.player_id HAVING COUNT(DISTINCT g.game_id) > 50;
What is the average number of founders in companies founded in 2018?
CREATE TABLE companies (id INT,name TEXT,founding_year INT,founder_count INT); INSERT INTO companies (id,name,founding_year,founder_count) VALUES (1,'InnoVentures',2018,3); INSERT INTO companies (id,name,founding_year,founder_count) VALUES (2,'TechBoost',2018,1); INSERT INTO companies (id,name,founding_year,founder_cou...
SELECT AVG(founder_count) FROM companies WHERE founding_year = 2018;
What is the average rating of products in the 'Face' category?
CREATE TABLE products (product_id INT,category TEXT,rating FLOAT); INSERT INTO products (product_id,category,rating) VALUES (1,'Lips',4.5),(2,'Face',3.2),(3,'Lips',4.8);
SELECT AVG(rating) FROM products WHERE category = 'Face';
What is the highest number of wins in a single game for each player?
CREATE TABLE PlayerGameScores (GameID int,PlayerID int,PlayerName varchar(50),GameType varchar(50),Wins int); INSERT INTO PlayerGameScores (GameID,PlayerID,PlayerName,GameType,Wins) VALUES (1,1,'Leung Chan','Racing',12),(2,1,'Leung Chan','Shooter',8),(3,2,'Akane Tanaka','Racing',15),(4,2,'Akane Tanaka','Shooter',10),(5...
SELECT PlayerID, MAX(Wins) FROM PlayerGameScores GROUP BY PlayerID;
What is the minimum number of electric buses operating in Cairo on a daily basis?
CREATE TABLE if not exists Buses (id INT,type VARCHAR(20),city VARCHAR(20),operating INT,date DATE); INSERT INTO Buses (id,type,city,operating,date) VALUES (1,'Electric','Cairo',100,'2022-03-22'),(2,'Diesel','Cairo',200,'2022-03-22'),(3,'Electric','Cairo',95,'2022-03-23');
SELECT MIN(operating) FROM Buses WHERE type = 'Electric' AND city = 'Cairo';
What is the average rainfall in June for agroecology projects in Brazil and Colombia?
CREATE TABLE agroecology_projects (id INT,name TEXT,country TEXT,avg_rainfall FLOAT); INSERT INTO agroecology_projects (id,name,country,avg_rainfall) VALUES (1,'Project 1','Brazil',100.5),(2,'Project 2','Colombia',120.0);
SELECT AVG(avg_rainfall) as avg_rainfall FROM agroecology_projects WHERE country IN ('Brazil', 'Colombia') AND MONTH(datetime) = 6;
Calculate the average amount of energy consumed by mining operations per day
CREATE TABLE energy_consumption(year INT,operation VARCHAR(20),daily_energy_consumption FLOAT); INSERT INTO energy_consumption VALUES (2018,'mining',25000.5),(2019,'mining',26000.3),(2020,'mining',27000.2);
SELECT AVG(daily_energy_consumption) FROM energy_consumption WHERE year BETWEEN 2018 AND 2020 AND operation = 'mining';
Detect mobile subscribers with a sudden increase in data usage, showing the top 3 largest increase percentages.
CREATE TABLE mobile_usage (subscriber_id INT,month INT,usage FLOAT); INSERT INTO mobile_usage (subscriber_id,month,usage) VALUES (1,1,100),(1,2,110),(2,1,200),(2,2,220),(3,1,150),(3,2,180);
SELECT subscriber_id, 100.0 * (LAG(usage, 1) OVER (PARTITION BY subscriber_id ORDER BY month) - usage) / LAG(usage, 1) OVER (PARTITION BY subscriber_id ORDER BY month) as pct_increase, ROW_NUMBER() OVER (ORDER BY pct_increase DESC) as rank FROM mobile_usage GROUP BY subscriber_id HAVING rank <= 3;
Which indigenous food systems are present in South America?
CREATE TABLE FoodSystems (id INT,name VARCHAR(50),location VARCHAR(50),type VARCHAR(50)); INSERT INTO FoodSystems (id,name,location,type) VALUES (1,'Andean Root Crops','South America','Indigenous Food System');
SELECT * FROM FoodSystems WHERE location = 'South America' AND type = 'Indigenous Food System';
Find the carbon prices and their moving average for the last 2 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, price, AVG(price) OVER (ORDER BY date ROWS BETWEEN 27 PRECEDING AND 1 PRECEDING) as moving_avg FROM carbon_prices WHERE date >= '2021-02-01';
Identify ship incidents in the Baltic Sea
CREATE TABLE Ship_Incidents (id INT,ship_name VARCHAR(50),incident_type VARCHAR(50),incident_date DATE,location VARCHAR(50)); INSERT INTO Ship_Incidents (id,ship_name,incident_type,incident_date,location) VALUES (1,'MS Zenith','grounding','2019-03-12','Baltic Sea');
SELECT ship_name, incident_type FROM Ship_Incidents WHERE location = 'Baltic Sea';
What is the average fare for train trips in Berlin?
CREATE TABLE if not exists berlin_train_trips (id INT,trip_id INT,fare DECIMAL(5,2),route_id INT,vehicle_id INT,timestamp TIMESTAMP);
SELECT AVG(fare) FROM berlin_train_trips WHERE fare IS NOT NULL;
How many incidents has each vessel had, and when was the earliest incident date for each vessel?
CREATE TABLE SafetyRecords (RecordID int,VesselID int,IncidentType varchar(50),IncidentDate datetime); INSERT INTO SafetyRecords (RecordID,VesselID,IncidentType,IncidentDate) VALUES (1000,3,'Collision','2019-12-15'); INSERT INTO SafetyRecords (RecordID,VesselID,IncidentType,IncidentDate) VALUES (1001,1,'Oil Spill','202...
SELECT VesselID, VesselName, COUNT(*) as IncidentCount, MIN(IncidentDate) as FirstIncidentDate FROM SafetyRecords sr JOIN Vessels v ON sr.VesselID = v.VesselID GROUP BY VesselID, VesselName;
What is the average budget for national security operations in the last 5 years?
CREATE TABLE fiscal_year (id INT,year INT); INSERT INTO fiscal_year (id,year) VALUES (1,2017),(2,2018),(3,2019),(4,2020),(5,2021); CREATE TABLE national_security_operations (id INT,fiscal_year_id INT,budget DECIMAL(10,2)); INSERT INTO national_security_operations (id,fiscal_year_id,budget) VALUES (1,1,5000000.00),(2,2,...
SELECT AVG(n.budget) as avg_budget FROM national_security_operations n INNER JOIN fiscal_year f ON n.fiscal_year_id = f.id WHERE f.year BETWEEN 2017 AND 2021;
Calculate the average number of exhibitions visited by visitors from each US state.
CREATE TABLE exhibition_visits (id INT,visitor_id INT,exhibition_id INT,state TEXT); INSERT INTO exhibition_visits (id,visitor_id,exhibition_id,state) VALUES (1,1,1,'CA'),(2,2,1,'NY');
SELECT state, AVG(COUNT(DISTINCT exhibition_id)) as avg_exhibitions_visited FROM exhibition_visits WHERE state IS NOT NULL GROUP BY state;
What is the total playtime for each platform?
CREATE TABLE PlayerSessions (SessionID int,PlayerID int,GameID int,PlatformID int,Playtime int); INSERT INTO PlayerSessions (SessionID,PlayerID,GameID,PlatformID,Playtime) VALUES (1,1,1,1,60),(2,1,1,1,90),(3,2,1,2,75),(4,2,2,2,120),(5,3,2,3,100),(6,3,3,1,80); CREATE TABLE Platforms (PlatformID int,PlatformName varchar(...
SELECT P.PlatformName, SUM(PS.Playtime) as TotalPlaytime FROM PlayerSessions PS JOIN Platforms P ON PS.PlatformID = P.PlatformID GROUP BY P.PlatformName;
What's the total amount donated by each donor in '2022'?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,DonationDate DATE,DonationAmount INT);
SELECT DonorName, SUM(DonationAmount) FROM Donors WHERE YEAR(DonationDate) = 2022 GROUP BY DonorName;
What is the maximum balance for customers from Germany?
CREATE TABLE customers (id INT,name VARCHAR(255),country VARCHAR(255)); INSERT INTO customers (id,name,country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Canada'),(3,'Jim Brown','UK'),(4,'Heidi Klum','Germany'); CREATE TABLE accounts (id INT,customer_id INT,balance DECIMAL(10,2)); INSERT INTO accounts (id,customer_i...
SELECT MAX(a.balance) FROM accounts a JOIN customers c ON a.customer_id = c.id WHERE c.country = 'Germany';
Show all posts related to data privacy in Spanish and the number of likes for each.
CREATE TABLE posts (id INT,user_id INT,content TEXT,created_at TIMESTAMP,language VARCHAR(10)); CREATE TABLE likes (id INT,post_id INT,user_id INT,created_at TIMESTAMP);
SELECT posts.content, COUNT(likes.id) AS likes_count FROM posts JOIN likes ON posts.id = likes.post_id WHERE posts.content LIKE '%data privacy%' AND posts.language = 'es' GROUP BY posts.id;
Show all unions and their collective bargaining agreements, if any, along with the date of the latest agreement
CREATE TABLE UnionInfo (UnionID INT,UnionName VARCHAR(50)); INSERT INTO UnionInfo (UnionID,UnionName) VALUES (1001,'National Labor Union'); INSERT INTO UnionInfo (UnionID,UnionName) VALUES (1002,'United Steelworkers'); CREATE TABLE CollectiveBargaining (CBAID INT,UnionID INT,AgreementDate DATE); INSERT INTO CollectiveB...
SELECT u.UnionID, u.UnionName, ISNULL(MAX(c.AgreementDate), 'No Agreements') as LatestAgreement FROM UnionInfo u LEFT JOIN CollectiveBargaining c ON u.UnionID = c.UnionID GROUP BY u.UnionID, u.UnionName;
How many community development initiatives were completed in each province in 2020?
CREATE TABLE CommunityDevelopment (province VARCHAR(50),year INT,initiative VARCHAR(50),status VARCHAR(50));
SELECT province, COUNT(*) FROM CommunityDevelopment WHERE year = 2020 AND status = 'completed' GROUP BY province;
Insert new water conservation initiatives in the 'Mississippi River Basin'
CREATE TABLE conservation_initiatives (id INT PRIMARY KEY,region VARCHAR(255),initiative_name VARCHAR(255),start_date DATE,end_date DATE);
INSERT INTO conservation_initiatives (id, region, initiative_name, start_date, end_date) VALUES (1, 'Mississippi River Basin', 'Smart irrigation systems', DATE_SUB(CURDATE(), INTERVAL 1 MONTH), DATE_ADD(CURDATE(), INTERVAL 2 YEAR));
List all crew members for vessel with id 1, ordered by join_date
crew_by_vessel
SELECT * FROM crew_by_vessel WHERE vessel_id = 1 ORDER BY join_date;
How many users are from each country in the profiles table?
CREATE TABLE profiles (id INT,user_id INT,country VARCHAR(50));
SELECT country, COUNT(DISTINCT user_id) FROM profiles GROUP BY country;
What is the percentage of renewable energy consumption for the year 2020 in the world?
CREATE TABLE global_energy (year INT,renewable_energy_consumption FLOAT,total_energy_consumption FLOAT);
SELECT renewable_energy_consumption/total_energy_consumption * 100 AS pct FROM global_energy WHERE year = 2020;
Which rare earth element had the highest production increase between 2015 and 2018?
CREATE TABLE production (element VARCHAR(10),year INT,quantity FLOAT); INSERT INTO production (element,year,quantity) VALUES ('Erbium',2015,550),('Erbium',2016,650),('Erbium',2017,750),('Erbium',2018,850),('Erbium',2019,950),('Gadolinium',2015,250),('Gadolinium',2016,300),('Gadolinium',2017,350),('Gadolinium',2018,400)...
SELECT element, MAX(diff) FROM (SELECT element, (quantity - LAG(quantity) OVER (PARTITION BY element ORDER BY year)) AS diff FROM production) AS subquery;
Insert a new record into the "cargo_tracking" table with values "VT-123", "Mumbai", "Delhi", 5000, and "2022-03-22 10:30:00".
CREATE TABLE cargo_tracking (vessel_id VARCHAR(20),departure_port VARCHAR(255),destination_port VARCHAR(255),cargo_weight INT,departure_time TIMESTAMP);
INSERT INTO cargo_tracking (vessel_id, departure_port, destination_port, cargo_weight, departure_time) VALUES ('VT-123', 'Mumbai', 'Delhi', 5000, '2022-03-22 10:30:00');
List the top 5 cities with the most green buildings
CREATE TABLE green_buildings (id INT,building_name VARCHAR(255),city VARCHAR(255),country VARCHAR(255),certification_date DATE);
SELECT city, COUNT(*) AS num_green_buildings FROM green_buildings GROUP BY city ORDER BY num_green_buildings DESC LIMIT 5;
Who are the top 5 legal aid providers in California by the number of clients served in the last 2 years?
CREATE TABLE legal_aid_providers (id INT,name VARCHAR(50),state VARCHAR(2)); INSERT INTO legal_aid_providers (id,name,state) VALUES (1,'California Legal Aid','CA'),(2,'Los Angeles Legal Aid','CA'),(3,'San Francisco Legal Aid','CA'),(4,'San Diego Legal Aid','CA'),(5,'Silicon Valley Legal Aid','CA'); CREATE TABLE clients...
SELECT legal_aid_providers.name, COUNT(clients.id) AS client_count FROM legal_aid_providers INNER JOIN clients ON legal_aid_providers.id = clients.provider_id WHERE clients.year BETWEEN YEAR(CURRENT_DATE()) - 2 AND YEAR(CURRENT_DATE()) GROUP BY legal_aid_providers.name ORDER BY client_count DESC LIMIT 5;
What is the maximum number of visitors to a sustainable destination in a single month in South East Asia?
CREATE TABLE MonthlySEAVisitors (visitor_id INT,destination VARCHAR(50),country VARCHAR(50),visit_month DATE); INSERT INTO MonthlySEAVisitors (visitor_id,destination,country,visit_month) VALUES (1,'Eco Park','Thailand','2022-02-01'); INSERT INTO MonthlySEAVisitors (visitor_id,destination,country,visit_month) VALUES (2,...
SELECT MAX(visitor_id) FROM MonthlySEAVisitors WHERE country IN ('South East Asia') GROUP BY visit_month;
What are the total sales for vintage garments at each retail store?
CREATE TABLE sales_vintage (id INT,garment VARCHAR(255),retail_store VARCHAR(255),sale_date DATE,quantity INT,sales_price DECIMAL(5,2)); INSERT INTO sales_vintage (id,garment,retail_store,sale_date,quantity,sales_price) VALUES (1,'vintage_t-shirt','London Fashion','2021-03-01',20,25.99); INSERT INTO sales_vintage (id,g...
SELECT retail_store, SUM(quantity * sales_price) as total_sales FROM sales_vintage WHERE garment LIKE '%vintage%' GROUP BY retail_store;
List all restaurants that had zero food safety violations in 2022.
CREATE TABLE Inspections (Restaurant VARCHAR(255),Date DATE,Violation INT); INSERT INTO Inspections (Restaurant,Date,Violation) VALUES ('Cafe R','2022-01-01',0),('Cafe R','2022-02-01',0),('Cafe R','2022-03-01',0),('Bistro A','2022-01-01',1),('Bistro A','2022-02-01',0),('Bistro A','2022-03-01',1);
SELECT DISTINCT Restaurant FROM Inspections WHERE YEAR(Date) = 2022 AND Violation = 0;
What is the average yield of crops planted in the Midwest?
CREATE TABLE Crops (id INT PRIMARY KEY,name VARCHAR(50),planting_date DATE,harvest_date DATE,yield INT,farmer_id INT,FOREIGN KEY (farmer_id) REFERENCES Farmers(id)); INSERT INTO Crops (id,name,planting_date,harvest_date,yield,farmer_id) VALUES (1,'Corn','2022-05-01','2022-08-01',100,1),(2,'Soybeans','2022-06-15','2022-...
SELECT AVG(yield) FROM Crops WHERE region = 'Midwest';
What is the average energy consumption per household in the "RenewableResidentialData" table, partitioned by city?
CREATE TABLE RenewableResidentialData (City VARCHAR(50),HouseholdID INT,EnergyConsumption FLOAT);
SELECT City, AVG(EnergyConsumption) OVER (PARTITION BY City) FROM RenewableResidentialData;
What is the average wind speed and solar radiation for each city by month?
CREATE TABLE sensors (id INT,city VARCHAR(255),type VARCHAR(255),value FLOAT,timestamp TIMESTAMP); INSERT INTO sensors (id,city,type,value,timestamp) VALUES (1,'EcoCity','Wind Speed',7.2,'2022-04-01 10:00:00'),(2,'EcoCity','Solar Radiation',500,'2022-04-01 10:00:00');
SELECT city, type, AVG(value) as avg_value, DATE_FORMAT(timestamp, '%%Y-%%m') as month FROM sensors GROUP BY city, type, month;
What is the percentage of autonomous driving test distance driven by each manufacturer in the USA in 2021?
CREATE TABLE AutonomousTests (Id INT,Manufacturer VARCHAR(100),TestDate DATE,Distance FLOAT); INSERT INTO AutonomousTests (Id,Manufacturer,TestDate,Distance) VALUES (1,'Tesla','2021-01-01',150.0); INSERT INTO AutonomousTests (Id,Manufacturer,TestDate,Distance) VALUES (2,'Waymo','2021-02-01',170.0); INSERT INTO Autonomo...
SELECT Manufacturer, (SUM(Distance) * 100.0 / (SELECT SUM(Distance) FROM AutonomousTests WHERE Country = 'USA' AND EXTRACT(YEAR FROM TestDate) = 2021)) AS Percentage FROM AutonomousTests WHERE Country = 'USA' AND EXTRACT(YEAR FROM TestDate) = 2021 GROUP BY Manufacturer;
What is the maximum and minimum depth of marine protected areas in the Pacific Ocean?
CREATE TABLE marine_protected_areas (name TEXT,location TEXT,depth FLOAT); INSERT INTO marine_protected_areas (name,location,depth) VALUES ('Galapagos Marine Reserve','Pacific',2400.0),('Monterey Bay National Marine Sanctuary','Pacific',30.0),('Great Barrier Reef','Pacific',344.0);
SELECT MAX(depth) AS max_depth, MIN(depth) AS min_depth FROM marine_protected_areas WHERE location = 'Pacific';
What is the total number of art pieces in 'Paris', 'Madrid', and 'Barcelona'?
CREATE TABLE museums (id INT,city VARCHAR(20),art_pieces INT); INSERT INTO museums (id,city,art_pieces) VALUES (1,'Paris',5000),(2,'Madrid',7000),(3,'Barcelona',8000),(4,'Paris',6000),(5,'Madrid',8000),(6,'Barcelona',9000);
SELECT city, SUM(art_pieces) FROM museums GROUP BY city HAVING city IN ('Paris', 'Madrid', 'Barcelona');
What is the average price of vegetarian menu items sold in New York?
CREATE TABLE menus (menu_id INT,menu_name VARCHAR(255),price DECIMAL(5,2),city VARCHAR(255)); INSERT INTO menus (menu_id,menu_name,price,city) VALUES (1,'Veggie Burger',8.99,'New York'); INSERT INTO menus (menu_id,menu_name,price,city) VALUES (2,'Veggie Wrap',7.49,'New York');
SELECT AVG(price) FROM menus WHERE menu_name LIKE '%vegetarian%' AND city = 'New York';
Which genre has the highest average movie rating?
CREATE TABLE movies (title VARCHAR(255),rating INT,genre VARCHAR(50)); INSERT INTO movies (title,rating,genre) VALUES ('Movie1',8,'Action'),('Movie2',7,'Drama'),('Movie3',9,'Comedy'),('Movie4',6,'Action'),('Movie5',8,'Drama'),('Movie6',7,'Comedy');
SELECT genre, AVG(rating) as avg_rating FROM movies GROUP BY genre ORDER BY avg_rating DESC LIMIT 1;
Which vulnerabilities had the highest severity in the European Union in the past week?
CREATE TABLE vulnerabilities (id INT,severity INT,country VARCHAR(255),vulnerability_date DATE); INSERT INTO vulnerabilities (id,severity,country,vulnerability_date) VALUES (1,9,'EU','2022-02-01'),(2,7,'EU','2022-02-02'),(3,8,'EU','2022-02-03');
SELECT severity, COUNT(*) AS high_severity_count FROM vulnerabilities WHERE country = 'EU' AND vulnerability_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) AND severity >= 7 GROUP BY severity ORDER BY high_severity_count DESC;
Update the 'MentalHealthScore' field for a mental health record in the 'MentalHealth' table
CREATE TABLE MentalHealth (StudentID int,Date date,MentalHealthScore int);
UPDATE MentalHealth SET MentalHealthScore = 80 WHERE StudentID = 1234 AND Date = '2022-09-01';
What is the average number of international visitors for each continent, and the total number of visitors worldwide?
CREATE TABLE global_tourism (destination VARCHAR(255),continent VARCHAR(255),visitors INT); INSERT INTO global_tourism (destination,continent,visitors) VALUES ('Rio de Janeiro','South America',1000000); INSERT INTO global_tourism (destination,continent,visitors) VALUES ('Sydney','Australia',2000000);
SELECT continent, AVG(visitors) as avg_visitors_per_continent, SUM(visitors) as total_visitors_worldwide FROM global_tourism GROUP BY continent;
How many parcels were shipped from Vietnam to France in the first half of the year?
CREATE TABLE vn_fr_parcels (id INT,shipped_date DATE); INSERT INTO vn_fr_parcels (id,shipped_date) VALUES (1,'2022-01-10'),(2,'2022-06-01');
SELECT COUNT(*) FROM vn_fr_parcels WHERE MONTH(shipped_date) <= 6 AND MONTH(shipped_date) > 0;
What was the recycling rate in percentage for the region 'Sydney' in 2020?
CREATE TABLE recycling_rates (region VARCHAR(50),year INT,recycling_rate FLOAT); INSERT INTO recycling_rates (region,year,recycling_rate) VALUES ('Sydney',2020,67.89);
SELECT recycling_rate FROM recycling_rates WHERE region = 'Sydney' AND year = 2020;
What is the total weight of all shipments?
CREATE TABLE Shipment (id INT,weight INT); INSERT INTO Shipment (id,weight) VALUES (101,10000),(102,15000),(103,8000);
SELECT SUM(weight) FROM Shipment;
What is the average environmental impact score for companies in the 'Latin America' region?
CREATE TABLE impact_assessment (id INT PRIMARY KEY,company_id INT,assessment_date DATE,social_impact_score INT,environmental_impact_score INT); INSERT INTO impact_assessment (id,company_id,assessment_date,social_impact_score,environmental_impact_score) VALUES (1,1,'2019-12-31',85,90); INSERT INTO impact_assessment (id,...
SELECT AVG(ia.environmental_impact_score) AS avg_env_score FROM impact_assessment AS ia JOIN company AS c ON ia.company_id = c.id WHERE c.location LIKE 'Lat%';
Update the 'city_infrastructure' table to change the status of the project with ID 15 to 'Completed'
CREATE TABLE city_infrastructure (project_id INT,project_name VARCHAR(50),project_status VARCHAR(20));
UPDATE city_infrastructure SET project_status = 'Completed' WHERE project_id = 15;
Identify the humanitarian assistance provided by the US and China
CREATE TABLE humanitarian_assistance (donor VARCHAR(255),recipient VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO humanitarian_assistance (donor,recipient,amount) VALUES ('USA','Syria',1000000),('China','Pakistan',500000),('USA','Iraq',800000),('China','Afghanistan',700000);
SELECT donor, recipient, amount FROM humanitarian_assistance WHERE donor IN ('USA', 'China');
List the top 3 smart contracts with the most transactions on the 'Binance Smart Chain'?
CREATE TABLE smart_contracts (contract_id INT,contract_address VARCHAR(50),network VARCHAR(20)); INSERT INTO smart_contracts (contract_id,contract_address,network) VALUES (1,'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D','Binance Smart Chain'); CREATE TABLE contract_transactions (transaction_id INT,contract_id INT,block_...
SELECT s.contract_address, COUNT(c.transaction_id) as transaction_count FROM smart_contracts s JOIN contract_transactions c ON s.contract_id = c.contract_id WHERE s.network = 'Binance Smart Chain' GROUP BY s.contract_address ORDER BY transaction_count DESC LIMIT 3;
What was the total number of community health workers and mental health parity complaints for each state?
CREATE TABLE CommunityHealthWorkers (ID INT,State VARCHAR(20),Gender VARCHAR(10)); CREATE TABLE MentalHealthParity (ID INT,State VARCHAR(20),Complaint INT); INSERT INTO CommunityHealthWorkers (ID,State,Gender) VALUES (1,'California','Male'),(2,'California','Female'),(3,'Texas','Male'); INSERT INTO MentalHealthParity (I...
SELECT State, COUNT(DISTINCT CommunityHealthWorker) as HealthWorkers, SUM(Complaint) as TotalComplaints FROM CommunityHealthWorkers JOIN MentalHealthParity ON CommunityHealthWorkers.State = MentalHealthParity.State GROUP BY State;
List all programs and their respective total expenses for Q3 2021, sorted by total expenses in descending order.
CREATE TABLE programs (id INT,name TEXT,start_date DATE,end_date DATE); CREATE TABLE expenses (id INT,program_id INT,amount DECIMAL(10,2),expense_date DATE); INSERT INTO programs (id,name,start_date,end_date) VALUES (1,'Education Program','2021-07-01','2021-12-31'),(2,'Medical Outreach Program','2021-04-15','2021-11-30...
SELECT programs.name, SUM(expenses.amount) as total_expenses FROM programs INNER JOIN expenses ON programs.id = expenses.program_id WHERE expenses.expense_date BETWEEN '2021-07-01' AND '2021-09-30' GROUP BY programs.id ORDER BY total_expenses DESC;
Identify the number of unique donors and total donation amount per country in the past year.
CREATE TABLE DonorCountry (DonorID int,Country varchar(255)); INSERT INTO DonorCountry VALUES (1,'USA'); INSERT INTO DonorCountry VALUES (2,'Canada'); CREATE TABLE Donations (DonationID int,DonorID int,Amount float,DonationDate date); INSERT INTO Donations VALUES (1,1,5000000,'2022-01-01'); INSERT INTO Donations VALUES...
SELECT d.Country, COUNT(DISTINCT d.DonorID) as UniqueDonors, SUM(d.Amount) as TotalDonations FROM Donations d INNER JOIN DonorCountry dc ON d.DonorID = dc.DonorID WHERE d.DonationDate >= DATEADD(year, -1, GETDATE()) GROUP BY d.Country;
What is the total number of properties in each city with inclusive housing policies?
CREATE TABLE Cities (City varchar(20),Inclusive varchar(5)); CREATE TABLE Properties (PropertyID int,City varchar(20)); INSERT INTO Cities (City,Inclusive) VALUES ('Seattle','Yes'); INSERT INTO Properties (PropertyID,City) VALUES (1,'Seattle'); INSERT INTO Properties (PropertyID,City) VALUES (2,'Portland');
SELECT Properties.City, COUNT(Properties.PropertyID) FROM Properties INNER JOIN Cities ON Properties.City = Cities.City WHERE Cities.Inclusive = 'Yes' GROUP BY Properties.City;
What is the average 'data_usage' in GB for each 'service_type' in the 'services' table, ordered by average 'data_usage' in descending order?
CREATE TABLE subscribers (subscriber_id INT,service_type VARCHAR(50),data_usage FLOAT); CREATE TABLE services (service_type VARCHAR(50),description VARCHAR(50));
SELECT s.service_type, AVG(sub.data_usage) OVER (PARTITION BY s.service_type) AS avg_data_usage_gb FROM services s JOIN subscribers sub ON s.service_type = sub.service_type ORDER BY avg_data_usage_gb DESC;
What is the distribution of media literacy scores for Latinx users compared to Arab users?
CREATE TABLE media_literacy (id INT,user_id INT,ethnicity VARCHAR,score INT); INSERT INTO media_literacy (id,user_id,ethnicity,score) VALUES (1,1,'Latinx',80); INSERT INTO media_literacy (id,user_id,ethnicity,score) VALUES (2,2,'Arab',70);
SELECT ethnicity, AVG(score) as avg_score FROM media_literacy WHERE ethnicity IN ('Latinx', 'Arab') GROUP BY ethnicity;
How many visitors from each country engaged with the digital museum's online workshops?
CREATE TABLE visitor_workshops (visitor_id INT,country VARCHAR(50),workshop_name VARCHAR(50)); INSERT INTO visitor_workshops (visitor_id,country,workshop_name) VALUES (1,'United States','Painting'),(2,'Canada','Sculpture'),(3,'Mexico','Digital Art');
SELECT country, COUNT(*) as num_visitors FROM visitor_workshops GROUP BY country;
Find the maximum price for tops
CREATE TABLE clothing (id INT,category VARCHAR(50),subcategory VARCHAR(50),price DECIMAL(5,2)); INSERT INTO clothing (id,category,subcategory,price) VALUES (1,'Clothing','Tops',25.99),(2,'Clothing','Tops',35.99),(3,'Clothing','Tops',15.99),(4,'Clothing','Bottoms',49.99),(5,'Clothing','Bottoms',39.99),(6,'Clothing','Bot...
SELECT MAX(price) FROM clothing WHERE subcategory = 'Tops';
Calculate the total humanitarian assistance provided by the US and China in 2020
CREATE TABLE humanitarian_assistance (donor VARCHAR(255),recipient VARCHAR(255),amount DECIMAL(10,2),year INT); INSERT INTO humanitarian_assistance (donor,recipient,amount,year) VALUES ('USA','Syria',1000000,2020),('China','Pakistan',500000,2020),('USA','Iraq',800000,2020),('China','Afghanistan',700000,2020);
SELECT donor, SUM(amount) as total_assistance FROM humanitarian_assistance WHERE donor IN ('USA', 'China') AND year = 2020 GROUP BY donor;
Identify the top 2 states with the highest budget allocation for education and public transportation?
CREATE TABLE states (state_name VARCHAR(255),budget INT); INSERT INTO states (state_name,budget) VALUES ('California',3000000),('Texas',2500000),('New York',2000000); CREATE TABLE services (service_name VARCHAR(255),state_name VARCHAR(255),budget INT); INSERT INTO services (service_name,state_name,budget) VALUES ('educ...
SELECT state_name, budget FROM (SELECT state_name, SUM(budget) AS budget FROM services WHERE service_name IN ('education', 'public transportation') GROUP BY state_name ORDER BY budget DESC) AS subquery LIMIT 2;
What is the CO2 emissions reduction in percentage achieved by renewable energy sources in Germany in 2020?
CREATE TABLE co2_emissions (country VARCHAR(50),year INT,co2_emissions_mt INT,renewable_energy_production_twh FLOAT); INSERT INTO co2_emissions (country,year,co2_emissions_mt,renewable_energy_production_twh) VALUES ('Germany',2019,750,230),('Germany',2020,700,245),('Germany',2021,650,260);
SELECT ((co2_emissions_mt * 100 / 750) - 100) FROM co2_emissions WHERE country = 'Germany' AND year = 2020;
How many total donations were made in the month of June in the "museum_donations" table?
CREATE TABLE museum_donations (donation_id INT,donation_amount FLOAT,donation_date DATE); INSERT INTO museum_donations (donation_id,donation_amount,donation_date) VALUES (1,250.00,'2021-06-01'),(2,300.00,'2021-06-15'),(3,150.00,'2021-07-01');
SELECT SUM(donation_amount) FROM museum_donations WHERE EXTRACT(MONTH FROM donation_date) = 6;
What is the maximum sustainable stocking density for each fish species in the different farms?
CREATE TABLE Farm (FarmID INT,FarmName VARCHAR(255)); CREATE TABLE FishSpecies (SpeciesID INT,SpeciesName VARCHAR(255),MaxDensity DECIMAL(10,2)); CREATE TABLE Stock (StockID INT,FarmID INT,SpeciesID INT,StockDensity DECIMAL(10,2),StockDate DATE); INSERT INTO Farm (FarmID,FarmName) VALUES (1,'Farm A'),(2,'Farm B'),(3,'F...
SELECT f.FarmName, fs.SpeciesName, MAX(StockDensity) OVER (PARTITION BY f.FarmName, fs.SpeciesID) as MaxSustainableDensity FROM Stock JOIN Farm f ON Stock.FarmID = f.FarmID JOIN FishSpecies fs ON Stock.SpeciesID = fs.SpeciesID WHERE StockDensity <= MaxDensity;
What is the total funding received by biotech startups in California that have conducted genetic research in the last 2 years?
CREATE TABLE biotech_startups(id INT,name TEXT,location TEXT,industry TEXT,funding FLOAT,research TEXT); INSERT INTO biotech_startups VALUES(1,'Caligenix','California','Biotechnology',8000000,'Genetic Research'); INSERT INTO biotech_startups VALUES(2,'BioCal','California','Biotechnology',10000000,'Protein Synthesis');
SELECT SUM(funding) FROM biotech_startups WHERE industry = 'Biotechnology' AND location = 'California' AND research IS NOT NULL AND research <> '' AND research LIKE '%Genetic%' AND research LIKE '%Last 2 Years%';