instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total number of bills sponsored by legislators in the 'Democrat' party for the topic 'Healthcare'?
CREATE TABLE Legislator (id INT,Name VARCHAR(50),Party VARCHAR(50),State VARCHAR(50)); CREATE TABLE Bill (id INT,BillID INT,StateSponsor VARCHAR(50),Sponsor INT,Topic VARCHAR(50)); INSERT INTO Legislator (id,Name,Party,State) VALUES (1,'Alex Brown','Democrat','California'); INSERT INTO Legislator (id,Name,Party,State) VALUES (2,'Taylor Green','Republican','Texas'); INSERT INTO Bill (id,BillID,StateSponsor,Sponsor,Topic) VALUES (1,101,'California',1,'Healthcare'); INSERT INTO Bill (id,BillID,StateSponsor,Sponsor,Topic) VALUES (2,201,'Texas',2,'Education');
SELECT COUNT(DISTINCT b.BillID) FROM Legislator l JOIN Bill b ON l.State = b.StateSponsor WHERE l.Party = 'Democrat' AND b.Topic = 'Healthcare';
List all renewable energy projects and their corresponding budgets in the state of California, ordered by budget in descending order.
CREATE TABLE renewable_energy_projects (id INT,name VARCHAR(255),budget FLOAT,state VARCHAR(255)); INSERT INTO renewable_energy_projects (id,name,budget,state) VALUES (1,'Solar Farm 1',10000000.0,'California'),(2,'Wind Farm 1',15000000.0,'California');
SELECT * FROM renewable_energy_projects WHERE state = 'California' ORDER BY budget DESC;
Add a record for a depression patient who underwent CBT
CREATE TABLE patients (id INT PRIMARY KEY,name VARCHAR(255),age INT,gender VARCHAR(50)); CREATE TABLE mental_health_conditions (id INT PRIMARY KEY,name VARCHAR(255),description TEXT); CREATE TABLE mental_health_treatment_approaches (id INT PRIMARY KEY,name VARCHAR(255),description TEXT); CREATE TABLE patient_outcomes (id INT PRIMARY KEY,patient_id INT,mental_health_condition_id INT,treatment_approach_id INT,outcome_date DATE,outcome_description TEXT);
INSERT INTO patient_outcomes (id, patient_id, mental_health_condition_id, treatment_approach_id, outcome_date, outcome_description) VALUES (1, 1, 1, 1, '2022-06-01', 'Improved mood and energy levels.');
Which therapist conducted the longest therapy session, and how long did it last?
CREATE TABLE therapists (id INT,name VARCHAR(50),specialty VARCHAR(50)); INSERT INTO therapists (id,name,speciality) VALUES (1,'Grace Lee','CBT'); INSERT INTO therapists (id,name,speciality) VALUES (2,'Harrison Kim','DBT'); CREATE TABLE treatments (id INT,patient_id INT,therapist_id INT,date DATE,duration INT); INSERT INTO treatments (id,patient_id,therapist_id,date,duration) VALUES (1,1,1,'2022-01-01',60); INSERT INTO treatments (id,patient_id,therapist_id,date,duration) VALUES (2,2,2,'2022-01-02',90);
SELECT t.name as therapist_name, MAX(duration) as longest_session FROM treatments t JOIN therapists tr ON t.therapist_id = tr.id GROUP BY therapist_name;
What is the average experience of electrical engineers for each dam project?
CREATE TABLE dams (id INT,name VARCHAR(255),location VARCHAR(255),budget FLOAT,project_manager VARCHAR(255),engineer_specialty VARCHAR(255),engineer_experience INT);
SELECT d.name, AVG(d.engineer_experience) as avg_experience FROM dams d WHERE d.engineer_specialty = 'Electrical' GROUP BY d.name;
What is the average number of stories of all buildings in the state of New York that are taller than 150 meters?
CREATE TABLE building (id INT,name TEXT,state TEXT,number_of_stories INT,height INT); INSERT INTO building (id,name,state,number_of_stories,height) VALUES (1,'Building A','New York',50,200); INSERT INTO building (id,name,state,number_of_stories,height) VALUES (2,'Building B','New York',60,180);
SELECT AVG(number_of_stories) FROM building WHERE state = 'New York' AND height > 150;
What is the average duration of criminal trials for Indigenous defendants compared to non-Indigenous defendants in Canada and New Zealand?
CREATE TABLE canada_criminal_trials (id INT,defendant_type VARCHAR(255),days_to_completion INT); INSERT INTO canada_criminal_trials (id,defendant_type,days_to_completion) VALUES (1,'Indigenous',60),(2,'Non-Indigenous',45);CREATE TABLE nz_criminal_trials (id INT,defendant_type VARCHAR(255),days_to_completion INT); INSERT INTO nz_criminal_trials (id,defendant_type,days_to_completion) VALUES (1,'Indigenous',70),(2,'Non-Indigenous',50);
SELECT AVG(days_to_completion) AS avg_duration FROM canada_criminal_trials WHERE defendant_type = 'Indigenous' UNION ALL SELECT AVG(days_to_completion) AS avg_duration FROM canada_criminal_trials WHERE defendant_type = 'Non-Indigenous' UNION ALL SELECT AVG(days_to_completion) AS avg_duration FROM nz_criminal_trials WHERE defendant_type = 'Indigenous' UNION ALL SELECT AVG(days_to_completion) AS avg_duration FROM nz_criminal_trials WHERE defendant_type = 'Non-Indigenous';
Calculate the total biomass of marine species in 'MarineResearchArea'
CREATE TABLE SpeciesBiomass (species VARCHAR(255),biomass FLOAT); INSERT INTO SpeciesBiomass (species,biomass) VALUES ('Dolphin',350.5),('Shark',400.0),('Turtle',200.0); CREATE TABLE MarineResearchArea (species VARCHAR(255),location VARCHAR(255)); INSERT INTO MarineResearchArea (species,location) VALUES ('Dolphin','MarineResearchArea'),('Shark','MarineResearchArea'),('Squid','MarineResearchArea');
SELECT SUM(biomass) FROM SpeciesBiomass INNER JOIN MarineResearchArea ON SpeciesBiomass.species = MarineResearchArea.species WHERE MarineResearchArea.location = 'MarineResearchArea';
What is the total biomass for all species in the Arctic Ocean?
CREATE TABLE species_biomass (species VARCHAR(255),ocean VARCHAR(255),biomass FLOAT); INSERT INTO species_biomass (species,ocean,biomass) VALUES ('Polar Bear','Arctic Ocean',500.0);
SELECT ocean, SUM(biomass) FROM species_biomass WHERE ocean = 'Arctic Ocean' GROUP BY ocean
What is the total number of hours of content created in each content category, segmented by language?
CREATE TABLE content_info (content_id INT,content_type VARCHAR(20),content_category VARCHAR(20),content_language VARCHAR(20),creation_date DATE,content_length INT);
SELECT content_category, content_language, SUM(content_length / 60) as total_hours FROM content_info WHERE creation_date >= CURDATE() - INTERVAL 1 YEAR GROUP BY content_category, content_language;
Who is the most frequent customer ordering vegetarian items?
CREATE TABLE customers (customer_id INT,customer_name VARCHAR(50)); INSERT INTO customers VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Alice Johnson'); CREATE TABLE orders (order_id INT,customer_id INT,menu_id INT,order_date DATE); INSERT INTO orders VALUES (1,1,1,'2022-01-01'),(2,2,3,'2022-01-02'),(3,3,2,'2022-01-03'); CREATE TABLE menu (menu_id INT,item_name VARCHAR(50),is_vegetarian BOOLEAN,price DECIMAL(5,2)); INSERT INTO menu VALUES (1,'Veggie Burger',true,8.99),(2,'Cheeseburger',false,7.99),(3,'Tofu Stir Fry',true,11.99);
SELECT customers.customer_name, COUNT(orders.order_id) as order_count FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id INNER JOIN menu ON orders.menu_id = menu.menu_id WHERE menu.is_vegetarian = true GROUP BY customers.customer_name ORDER BY order_count DESC LIMIT 1;
Find the average daily production quantity of zinc for mining sites in South America, for the year 2017, with less than 30 employees.
CREATE TABLE zinc_mine (site_id INT,country VARCHAR(50),num_employees INT,extraction_date DATE,quantity INT); INSERT INTO zinc_mine (site_id,country,num_employees,extraction_date,quantity) VALUES (1,'South America',25,'2017-01-02',120),(2,'South America',28,'2017-12-31',180),(3,'South America',22,'2017-03-04',220);
SELECT country, AVG(quantity) as avg_daily_zinc_prod FROM zinc_mine WHERE num_employees < 30 AND country = 'South America' AND extraction_date >= '2017-01-01' AND extraction_date <= '2017-12-31' GROUP BY country;
What is the total number of accidents in the platinum mines in the last year?
CREATE TABLE AccidentsInMines (AccidentID INT,MineID INT,AccidentDate DATE);
SELECT COUNT(*) FROM AccidentsInMines WHERE (SELECT MineType FROM Mines WHERE Mines.MineID = AccidentsInMines.MineID) = 'Platinum' AND AccidentDate >= DATEADD(year, -1, GETDATE());
How many days in the last month was the data usage for each customer above the average data usage for that customer?
CREATE TABLE daily_usage (customer_id INT,date DATE,data_usage FLOAT); INSERT INTO daily_usage VALUES (1,'2022-01-01',5),(1,'2022-01-02',7);
SELECT customer_id, COUNT(*) as days_above_average FROM (SELECT customer_id, date, data_usage, AVG(data_usage) OVER(PARTITION BY customer_id) as avg_usage FROM daily_usage WHERE date >= DATEADD(month, -1, GETDATE())) daily_usage_avg WHERE data_usage > avg_usage GROUP BY customer_id;
What is the average social impact score for all programs in the programs table?
CREATE TABLE programs (program_id INT,social_impact_score DECIMAL(10,2)); INSERT INTO programs (program_id,social_impact_score) VALUES (1,8.5),(2,9.0),(3,7.5);
SELECT AVG(social_impact_score) as avg_social_impact_score FROM programs;
What is the average number of victories for players from Japan and South Korea, partitioned by game mode?
CREATE TABLE PlayerVictories (PlayerID INT,GameMode VARCHAR(255),Victories INT,Country VARCHAR(255)); INSERT INTO PlayerVictories (PlayerID,GameMode,Victories,Country) VALUES (1,'Battle Royale',25,'Japan'),(2,'Team Deathmatch',18,'South Korea');
SELECT GameMode, AVG(Victories) as AvgVictories FROM PlayerVictories WHERE Country IN ('Japan', 'South Korea') GROUP BY GameMode, Country WITH ROLLUP;
What is the most common genre of PC games?
CREATE TABLE GameDesign (GameID INT,GameName VARCHAR(50),Genre VARCHAR(30),Platform VARCHAR(20)); INSERT INTO GameDesign (GameID,GameName,Genre,Platform) VALUES (1,'Minecraft','Sandbox','PC'),(2,'Call of Duty','FPS','PC'),(3,'The Sims','Simulation','PC');
SELECT Genre, COUNT(*) as GameCount FROM GameDesign WHERE Platform = 'PC' GROUP BY Genre ORDER BY GameCount DESC LIMIT 1;
Find the average soil moisture reading for each crop type in the month of May for 2021.
CREATE TABLE crop_data (id INT,crop_type VARCHAR(255),soil_moisture INT,measurement_date DATE); INSERT INTO crop_data (id,crop_type,soil_moisture,measurement_date) VALUES (1,'Corn',60,'2021-05-01'); INSERT INTO crop_data (id,crop_type,soil_moisture,measurement_date) VALUES (2,'Soybean',55,'2021-05-03');
SELECT crop_type, AVG(soil_moisture) as avg_moisture FROM crop_data WHERE measurement_date BETWEEN '2021-05-01' AND '2021-05-31' GROUP BY crop_type;
Find the maximum temperature for each crop type
CREATE TABLE crop (id INT,type VARCHAR(255),temperature FLOAT); INSERT INTO crop (id,type,temperature) VALUES (1,'corn',22.5),(2,'soybean',20.0),(3,'cotton',24.3),(4,'corn',25.0),(5,'soybean',23.5);
SELECT type, MAX(temperature) FROM crop GROUP BY type;
How many soil moisture sensors are currently active and located in a specific region?
CREATE TABLE SensorData (sensor_id INT,status VARCHAR(255),crop VARCHAR(255),region VARCHAR(255)); CREATE TABLE SoilMoistureSensor (sensor_id INT,location VARCHAR(255));
SELECT COUNT(*) FROM SensorData SD JOIN SoilMoistureSensor SMS ON SD.sensor_id = SMS.sensor_id WHERE SD.status = 'active' AND SD.region = 'Region A';
List all farmers who have not serviced their irrigation systems in the last 6 months.
CREATE TABLE farmer_irrigation (id INT,farmer_id INT,system_type VARCHAR(50),service_date DATE); INSERT INTO farmer_irrigation (id,farmer_id,system_type,service_date) VALUES (1,1,'Drip','2021-08-01'),(2,2,'Sprinkler','2021-10-15'),(3,3,'Drip','2021-11-01'),(4,4,'Sprinkler','2022-02-01'),(5,5,'Drip','2022-03-01'),(6,6,'Sprinkler','2022-01-15'),(7,7,'Drip','2021-06-01'),(8,8,'Sprinkler','2022-04-01'),(9,9,'Drip','2021-12-01'),(10,10,'Sprinkler','2022-05-15');
SELECT farmers.name FROM farmers LEFT JOIN farmer_irrigation ON farmers.id = farmer_irrigation.farmer_id WHERE farmer_irrigation.service_date <= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
List the policy areas with the lowest citizen satisfaction scores.
CREATE TABLE Policy (Area VARCHAR(20),Score INT); INSERT INTO Policy (Area,Score) VALUES ('Transportation',70),('Education',85),('Healthcare',75),('PublicSafety',80);
SELECT Area, Score FROM (SELECT Area, Score, ROW_NUMBER() OVER (ORDER BY Score) AS RN FROM Policy) X WHERE RN IN (1, 2);
What is the average response time for emergency calls in each borough of New York City in 2022?
CREATE TABLE emergency_calls (borough VARCHAR(255),year INT,response_time FLOAT); INSERT INTO emergency_calls (borough,year,response_time) VALUES ('Manhattan',2022,8.5),('Brooklyn',2022,7.8),('Bronx',2022,9.2),('Queens',2022,8.9),('Staten Island',2022,7.6);
SELECT borough, AVG(response_time) AS avg_response_time FROM emergency_calls WHERE year = 2022 GROUP BY borough;
Show the names of companies that produced any Rare Earth elements in both 2015 and 2020.
CREATE TABLE Producers (ProducerID INT PRIMARY KEY,Name TEXT,ProductionYear INT,RareEarth TEXT,Quantity INT);
SELECT DISTINCT Name FROM Producers p1 JOIN Producers p2 ON p1.Name = p2.Name WHERE p1.ProductionYear = 2015 AND p2.ProductionYear = 2020;
List the top 5 neighborhoods in Los Angeles with the highest number of listings that have green building certifications.
CREATE TABLE neighborhoods (name VARCHAR(255),city VARCHAR(255),state VARCHAR(255),country VARCHAR(255),PRIMARY KEY (name)); INSERT INTO neighborhoods (name,city,state,country) VALUES ('Silver Lake','Los Angeles','CA','USA');
SELECT name, COUNT(*) as num_listings FROM real_estate_listings WHERE city = 'Los Angeles' AND green_building_certification = TRUE GROUP BY name ORDER BY num_listings DESC LIMIT 5;
What is the sum of the total square footage of properties in the 'sustainable_urbanism' view that are larger than 2000 square feet?
CREATE VIEW sustainable_urbanism AS SELECT properties.id,properties.city,SUM(properties.square_footage) as total_square_footage FROM properties JOIN sustainable_developments ON properties.id = sustainable_developments.id GROUP BY properties.id,properties.city; INSERT INTO properties (id,city,square_footage) VALUES (1,'Austin',1800.0),(2,'Austin',2200.0),(3,'Seattle',1500.0); INSERT INTO sustainable_developments (id,property_name,low_income_area) VALUES (1,'Green Heights',true),(2,'Eco Estates',false),(3,'Solar Vista',false);
SELECT SUM(total_square_footage) FROM sustainable_urbanism WHERE total_square_footage > 2000;
What is the total number of sustainable urbanism projects in the state of California?
CREATE TABLE sustainable_urbanism_projects (project_id INT,state VARCHAR(20)); INSERT INTO sustainable_urbanism_projects (project_id,state) VALUES (1,'California'),(2,'Oregon'),(3,'California');
SELECT COUNT(*) FROM sustainable_urbanism_projects WHERE state = 'California';
How many solar power projects were completed in California and Texas in 2020 and 2021?
CREATE TABLE solar_projects (project_id INT,state VARCHAR(50),completion_year INT); INSERT INTO solar_projects (project_id,state,completion_year) VALUES (1,'California',2020),(2,'Texas',2021),(3,'California',2019),(4,'Texas',2020),(5,'California',2021),(6,'Texas',2019),(7,'California',2018),(8,'Texas',2018);
SELECT state, COUNT(*) FROM solar_projects WHERE completion_year IN (2020, 2021) AND state IN ('California', 'Texas') GROUP BY state;
What is the total revenue for a specific cuisine type in a given month?
CREATE TABLE revenue_by_cuisine (restaurant_id INT,cuisine VARCHAR(255),revenue FLOAT,revenue_date DATE); INSERT INTO revenue_by_cuisine (restaurant_id,cuisine,revenue,revenue_date) VALUES (1,'Italian',5000.00,'2022-01-01'),(2,'Mexican',6000.00,'2022-01-02'),(3,'Italian',4000.00,'2022-01-03'),(4,'Chinese',7000.00,'2022-01-04'),(5,'Chinese',8000.00,'2022-01-05'),(6,'Italian',9000.00,'2022-01-06');
SELECT cuisine, SUM(revenue) as total_revenue FROM revenue_by_cuisine WHERE cuisine = 'Italian' AND revenue_date BETWEEN '2022-01-01' AND '2022-01-31' GROUP BY cuisine;
Calculate the percentage of revenue generated from circular supply chains?
CREATE TABLE sales (sale_id INT,product_id INT,quantity INT,price DECIMAL,supply_chain TEXT);
SELECT (SUM(CASE WHEN supply_chain = 'Circular' THEN quantity * price ELSE 0 END) / SUM(quantity * price)) * 100 FROM sales;
What is the average weight of spacecrafts for each manufacturing organization?
CREATE TABLE spacecrafts (id INT,name VARCHAR(50),manufacturing_org VARCHAR(50),weight FLOAT); INSERT INTO spacecrafts VALUES (1,'Voyager 1','NASA',795.5),(2,'Voyager 2','NASA',782.5),(3,'Galileo','NASA',2325.0),(4,'Cassini','CNES',2125.0),(5,'Rosetta','ESA',3000.0);
SELECT manufacturing_org, AVG(weight) as avg_weight FROM spacecrafts GROUP BY manufacturing_org;
What is the percentage of games won by the 'Los Angeles Lakers'?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams (team_id,team_name) VALUES (1,'Golden State Warriors'),(2,'Los Angeles Lakers'); CREATE TABLE games (game_id INT,home_team_id INT,away_team_id INT,home_team_score INT,away_team_score INT); INSERT INTO games (game_id,home_team_id,away_team_id,home_team_score,away_team_score) VALUES (1,1,2,100,90),(2,2,1,80,90),(3,1,2,110,100),(4,2,1,120,110),(5,1,2,105,100);
SELECT 100.0 * AVG(CASE WHEN g.home_team_id = 2 THEN 1.0 ELSE 0.0 END + CASE WHEN g.away_team_id = 2 THEN 1.0 ELSE 0.0 END) / COUNT(*) as pct_games_won FROM games g;
What is the total number of athletes in the 'Eastern Conference' who have participated in a wellbeing program?
CREATE TABLE athlete_wellbeing (athlete_id INT,athlete_name VARCHAR(50),conference VARCHAR(50),wellbeing_program BOOLEAN); INSERT INTO athlete_wellbeing (athlete_id,athlete_name,conference,wellbeing_program) VALUES (1,'Athlete A','Eastern Conference',TRUE),(2,'Athlete B','Western Conference',FALSE),(3,'Athlete C','Eastern Conference',TRUE),(4,'Athlete D','Eastern Conference',FALSE),(5,'Athlete E','Western Conference',FALSE),(6,'Athlete F','Eastern Conference',TRUE),(7,'Athlete G','Western Conference',FALSE),(8,'Athlete H','Eastern Conference',TRUE);
SELECT COUNT(*) FROM athlete_wellbeing WHERE conference = 'Eastern Conference' AND wellbeing_program = TRUE;
What is the total number of tickets sold for outdoor stadium events in the summer months?
CREATE TABLE TicketSales (id INT,event_type VARCHAR(255),location VARCHAR(255),tickets_sold INT,month INT); INSERT INTO TicketSales (id,event_type,location,tickets_sold,month) VALUES (1,'Concert','Outdoor Stadium',12000,6),(2,'Sports Game','Indoor Arena',8000,7),(3,'Festival','Outdoor Stadium',15000,8);
SELECT SUM(tickets_sold) FROM TicketSales WHERE location = 'Outdoor Stadium' AND month BETWEEN 6 AND 8;
How many security incidents were recorded per month in the year 2021?
CREATE TABLE security_incidents (id INT,incident_date TIMESTAMP); INSERT INTO security_incidents (id,incident_date) VALUES (1,'2021-01-01 10:00:00'),(2,'2021-02-02 11:00:00');
SELECT DATE_FORMAT(incident_date, '%Y-%m') as month, COUNT(*) as total_incidents FROM security_incidents WHERE incident_date >= '2021-01-01' AND incident_date < '2022-01-01' GROUP BY month;
What is the maximum trip duration for public transportation in Berlin?
CREATE TABLE public_transport (transport_id INT,trip_duration INT); INSERT INTO public_transport (transport_id,trip_duration) VALUES (1,30),(2,45),(3,60),(4,75);
SELECT MAX(trip_duration) as max_duration FROM public_transport;
What was the average retail sales revenue per 'Shirt' item in the USA?
CREATE TABLE RetailSales (id INT,garment_type VARCHAR(10),country VARCHAR(20),revenue DECIMAL(10,2)); INSERT INTO RetailSales (id,garment_type,country,revenue) VALUES (1,'Shirt','USA',50.99),(2,'Dress','USA',75.50),(3,'Shirt','Canada',45.25);
SELECT AVG(revenue) as avg_revenue_per_item FROM RetailSales WHERE garment_type = 'Shirt' AND country = 'USA';
What is the total number of electric vehicle adoptions in each country?
CREATE TABLE CountryEVAdoptions (Country VARCHAR(255),Adoption INT); INSERT INTO CountryEVAdoptions (Country,Adoption) VALUES ('USA',500000),('China',1000000),('Germany',300000),('Japan',400000);
SELECT Country, SUM(Adoption) AS TotalAdoption FROM CountryEVAdoptions GROUP BY Country;
How many visitors attended the Renaissance Art exhibition in the last week of February 2022?
CREATE TABLE exhibitions (exhibition_id INT,name VARCHAR(255)); INSERT INTO exhibitions (exhibition_id,name) VALUES (1,'Classical Art'),(2,'Renaissance Art'); CREATE TABLE visitors (visitor_id INT,exhibition_id INT,visit_date DATE); INSERT INTO visitors (visitor_id,exhibition_id,visit_date) VALUES (1,1,'2022-02-22'),(2,1,'2022-02-23'),(3,2,'2022-02-24'),(4,2,'2022-02-25'),(5,2,'2022-02-26'),(6,2,'2022-02-28');
SELECT COUNT(visitor_id) as num_visitors FROM visitors WHERE exhibition_id = 2 AND visit_date >= '2022-02-22' AND visit_date <= '2022-02-28';
What is the total waste generation by material type for the top 2 contributors in 2022?
CREATE TABLE waste_generation (year INT,location VARCHAR(255),material VARCHAR(255),weight_tons INT); INSERT INTO waste_generation (year,location,material,weight_tons) VALUES (2022,'New York','Plastic',15000),(2022,'New York','Paper',20000),(2022,'Los Angeles','Plastic',20000),(2022,'Los Angeles','Paper',25000),(2022,'Los Angeles','Glass',12000);
SELECT location, material, SUM(weight_tons) as total_weight FROM waste_generation WHERE year = 2022 GROUP BY location, material ORDER BY SUM(weight_tons) DESC LIMIT 2;
What is the average monthly water usage for residential customers in the San Francisco region for the year 2020?
CREATE TABLE water_usage(customer_id INT,region VARCHAR(50),usage FLOAT,year INT,month INT); INSERT INTO water_usage(customer_id,region,usage,year,month) VALUES (1,'San Francisco',15.3,2020,1),(2,'San Francisco',14.8,2020,2);
SELECT AVG(usage) FROM water_usage WHERE region = 'San Francisco' AND year = 2020 GROUP BY month;
What is the total water usage in Arizona and Nevada?
CREATE TABLE water_usage(state VARCHAR(20),volume_used INT); INSERT INTO water_usage VALUES('Arizona',8000),('Nevada',6000);
SELECT volume_used FROM water_usage WHERE state IN ('Arizona', 'Nevada');
What was the total wastewater treated per region in 2020?
CREATE TABLE wastewater_treatment (region TEXT,month TEXT,volume FLOAT); INSERT INTO wastewater_treatment (region,month,volume) VALUES ('North','Jan',123456.7),('North','Feb',134567.8),('South','Jan',234567.8),('South','Feb',345678.9);
SELECT region, SUM(volume) as total_volume FROM wastewater_treatment WHERE YEAR(STR_TO_DATE(month, '%b')) = 2020 GROUP BY region;
List the top 5 most popular workouts in New York based on the number of unique participants in the last month.
CREATE TABLE Workouts (WorkoutID INT,WorkoutName VARCHAR(50),WorkoutType VARCHAR(50),Participants INT,WorkoutDate DATE);
SELECT WorkoutName, COUNT(DISTINCT Participants) AS UniqueParticipants FROM Workouts WHERE WorkoutDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND State = 'New York' GROUP BY WorkoutName ORDER BY UniqueParticipants DESC LIMIT 5;
What is the average heart rate for runners in the morning?
CREATE TABLE workout_data (id INT,user_id INT,activity_type VARCHAR(20),heart_rate INT,workout_time TIME); INSERT INTO workout_data (id,user_id,activity_type,heart_rate,workout_time) VALUES (1,10,'Running',140,'07:00:00'),(2,10,'Cycling',120,'08:00:00'),(3,15,'Running',150,'06:00:00');
SELECT AVG(heart_rate) FROM workout_data WHERE activity_type = 'Running' AND EXTRACT(HOUR FROM workout_time) BETWEEN 0 AND 6;
For users from the USA, calculate the running total of transaction amounts for each transaction type, partitioned by user.
CREATE TABLE users (id INT,country VARCHAR(20)); INSERT INTO users (id,country) VALUES (1,'India'),(2,'USA'),(3,'USA'); CREATE TABLE transactions (id INT,user_id INT,type VARCHAR(20),amount DECIMAL(10,2),transaction_date DATE); INSERT INTO transactions (id,user_id,type,amount,transaction_date) VALUES (1,1,'credit',100.00,'2022-01-01'),(2,1,'debit',50.00,'2022-01-05'),(3,2,'credit',200.00,'2022-01-03'),(4,2,'debit',150.00,'2022-01-31'),(5,3,'credit',300.00,'2022-02-01');
SELECT user_id, type, amount, SUM(amount) OVER (PARTITION BY user_id, type ORDER BY transaction_date) as running_total FROM transactions INNER JOIN users ON transactions.user_id = users.id WHERE users.country = 'USA';
Identify the rural infrastructure projects in 'RuralDev' database that have exceeded their budget.
CREATE TABLE rural_infrastructure_budget (id INT,name VARCHAR(255),budget FLOAT,actual_cost FLOAT); INSERT INTO rural_infrastructure_budget (id,name,budget,actual_cost) VALUES (1,'Water Supply System',450000.00,500000.00),(2,'Solar Farm',900000.00,1000000.00),(3,'School',180000.00,200000.00);
SELECT name FROM rural_infrastructure_budget WHERE actual_cost > budget;
What is the average age of women farmers who have completed agricultural training programs in Kenya?
CREATE TABLE farmers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),country VARCHAR(50)); INSERT INTO farmers (id,name,age,gender,country) VALUES (1,'Jane Njeri',35,'Female','Kenya'); INSERT INTO farmers (id,name,age,gender,country) VALUES (2,'Anna Wangari',40,'Female','Kenya'); CREATE TABLE trainings (id INT,farmer_id INT,title VARCHAR(50),completion_date DATE); INSERT INTO trainings (id,farmer_id,title,completion_date) VALUES (1,1,'Agroecology Course','2020-03-01'); INSERT INTO trainings (id,farmer_id,title,completion_date) VALUES (2,2,'Organic Farming Workshop','2019-08-15');
SELECT AVG(age) FROM farmers f JOIN trainings t ON f.id = t.farmer_id WHERE f.gender = 'Female' AND f.country = 'Kenya';
What is the earliest launch date for each space mission?
CREATE TABLE SpaceMission (ID INT,Name VARCHAR(50),LaunchDate DATE);
SELECT Name, MIN(LaunchDate) AS EarliestLaunchDate FROM SpaceMission GROUP BY Name;
Find the number of animals in each status category
CREATE TABLE animals (id INT,name VARCHAR(50),status VARCHAR(20)); INSERT INTO animals (id,name,status) VALUES (1,'Tiger','Endangered'); INSERT INTO animals (id,name,status) VALUES (2,'Elephant','Vulnerable'); INSERT INTO animals (id,name,status) VALUES (3,'Rhino','Critically Endangered'); INSERT INTO animals (id,name,status) VALUES (4,'Panda','Threatened');
SELECT status, COUNT(*) FROM animals GROUP BY status;
How many fish are there in the 'Tuna' species in the 'Caribbean' region?
CREATE TABLE Farm (id INT,farm_name TEXT,region TEXT,species TEXT,weight FLOAT,age INT); INSERT INTO Farm (id,farm_name,region,species,weight,age) VALUES (1,'OceanPacific','Pacific','Tilapia',500.3,2),(2,'SeaBreeze','Atlantic','Salmon',300.1,1),(3,'OceanPacific','Pacific','Tilapia',600.5,3),(4,'FarmX','Atlantic','Salmon',700.2,4),(5,'SeaBreeze','Atlantic','Tilapia',400,2),(6,'AquaFarm','Indian Ocean','Tuna',900,5),(7,'CoralReef','Caribbean','Tuna',1000,6);
SELECT COUNT(*) FROM Farm WHERE species = 'Tuna' AND region = 'Caribbean';
What was the average number of attendees for events in the 'Music' category?
CREATE TABLE event_attendance (id INT,event_id INT,attendee_count INT); INSERT INTO event_attendance (id,event_id,attendee_count) VALUES (1,1,250),(2,2,320),(3,3,175); CREATE TABLE events (id INT,category VARCHAR(10)); INSERT INTO events (id,category) VALUES (1,'Dance'),(2,'Music'),(3,'Theater');
SELECT AVG(attendee_count) FROM event_attendance JOIN events ON event_attendance.event_id = events.id WHERE events.category = 'Music';
What was the average number of construction laborers employed in the state of Illinois in 2019?
CREATE TABLE Labor_Statistics (id INT,employee_count INT,year INT,state VARCHAR(20)); INSERT INTO Labor_Statistics (id,employee_count,year,state) VALUES (1,12000,2019,'Illinois');
SELECT AVG(employee_count) FROM Labor_Statistics WHERE year = 2019 AND state = 'Illinois';
What is the average temperature in the coldest month for each production site?
CREATE TABLE Production_Sites (Site_ID INT,Site_Name TEXT,Average_Temperature DECIMAL(5,2)); INSERT INTO Production_Sites (Site_ID,Site_Name,Average_Temperature) VALUES (1,'Site A',15.6),(2,'Site B',12.9),(3,'Site C',18.7);
SELECT Site_Name, MIN(Average_Temperature) OVER (PARTITION BY Site_ID) as Coldest_Month_Avg_Temp FROM Production_Sites;
Identify the sectors with zero emissions in the given dataset.
CREATE TABLE Emissions (sector VARCHAR(255),emissions FLOAT); INSERT INTO Emissions VALUES ('Energy',3000.0),('Industry',2500.0),('Agriculture',0.0),('Transportation',1500.0);
SELECT sector FROM Emissions WHERE emissions = 0;
Insert a new clinical trial for DrugE in 2022 in France.
CREATE TABLE clinical_trials (trial_id INT,drug_name VARCHAR(255),year INT,country VARCHAR(255)); INSERT INTO clinical_trials (trial_id,drug_name,year,country) VALUES (1,'DrugA',2018,'USA'),(2,'DrugB',2019,'Canada'),(3,'DrugC',2020,'Germany');
INSERT INTO clinical_trials (trial_id, drug_name, year, country) VALUES (4, 'DrugE', 2022, 'France');
What is the total sales revenue for each drug, ranked by the highest sales revenue first, for the year 2019?
CREATE TABLE sales_revenue_2019 (sales_revenue_id INT,drug_name VARCHAR(255),year INT,sales_revenue DECIMAL(10,2)); INSERT INTO sales_revenue_2019 (sales_revenue_id,drug_name,year,sales_revenue) VALUES (1,'DrugG',2019,50000),(2,'DrugH',2019,45000),(3,'DrugI',2019,55000),(4,'DrugG',2019,52000),(5,'DrugH',2019,48000),(6,'DrugI',2019,58000);
SELECT drug_name, SUM(sales_revenue) as total_sales_revenue FROM sales_revenue_2019 WHERE year = 2019 GROUP BY drug_name ORDER BY total_sales_revenue DESC;
What is the number of vaccination centers providing COVID-19 vaccines and flu shots, differentiated by type, for each state, from the vaccination_centers and state_data tables?
CREATE TABLE vaccination_centers (center_id TEXT,state TEXT,vaccine_type TEXT); INSERT INTO vaccination_centers (center_id,state,vaccine_type) VALUES ('Center1','StateA','COVID-19'),('Center2','StateA','Flu'),('Center3','StateB','COVID-19'),('Center4','StateB','Flu'); CREATE TABLE state_data (state TEXT,total_centers INT); INSERT INTO state_data (state,total_centers) VALUES ('StateA',500),('StateB',600),('StateC',700),('StateD',800);
SELECT state, vaccine_type, COUNT(*) AS center_count FROM vaccination_centers WHERE vaccine_type IN ('COVID-19', 'Flu') GROUP BY state, vaccine_type;
Which companies were founded in the US and have received funding from both venture capital and angel investors?
CREATE TABLE Companies (id INT,name TEXT,country TEXT); INSERT INTO Companies (id,name,country) VALUES (1,'Acme Inc','USA'); INSERT INTO Companies (id,name,country) VALUES (2,'Brick Co','USA'); CREATE TABLE Funding (id INT,company_id INT,investor_type TEXT,amount INT); INSERT INTO Funding (id,company_id,investor_type,amount) VALUES (1,1,'VC',5000000); INSERT INTO Funding (id,company_id,investor_type,amount) VALUES (2,1,'Angel',2000000); INSERT INTO Funding (id,company_id,investor_type,amount) VALUES (3,2,'VC',7000000);
SELECT Companies.name FROM Companies INNER JOIN Funding funding_vc ON Companies.id = funding_vc.company_id INNER JOIN Funding funding_angel ON Companies.id = funding_angel.company_id WHERE Companies.country = 'USA' AND funding_vc.investor_type = 'VC' AND funding_angel.investor_type = 'Angel'
What is the change in yield for each crop over time, for a specific farm?
CREATE TABLE farming (id INT,name TEXT,location TEXT,crop TEXT,yield INT,year INT); INSERT INTO farming VALUES (1,'Smith Farm','Colorado','Corn',120,2020),(2,'Brown Farm','Nebraska','Soybeans',45,2020),(3,'Jones Farm','Iowa','Wheat',80,2020),(1,'Smith Farm','Colorado','Corn',130,2021),(2,'Brown Farm','Nebraska','Soybeans',50,2021),(3,'Jones Farm','Iowa','Wheat',85,2021);
SELECT crop, (yield - LAG(yield) OVER (PARTITION BY crop, name ORDER BY year)) as yield_change FROM farming WHERE name = 'Smith Farm';
List all records from the policy table related to service animals or emotional support animals.
CREATE TABLE policy (id INT,policy_name VARCHAR(255),description VARCHAR(255)); INSERT INTO policy (id,policy_name,description) VALUES (1,'Service Animal Policy','Policy regarding the use of service animals on campus'); INSERT INTO policy (id,policy_name,description) VALUES (2,'Emotional Support Animal Policy','Policy regarding the use of emotional support animals in student housing');
SELECT policy_name, description FROM policy WHERE policy_name LIKE '%Service Animal%' OR policy_name LIKE '%Emotional Support Animal%';
List the names and types of all policy advocacy groups that have received funding in the last year, sorted by the amount of funding received.
CREATE TABLE PolicyAdvocacyGroups (GroupID INT,GroupName VARCHAR(100),GroupType VARCHAR(50)); INSERT INTO PolicyAdvocacyGroups(GroupID,GroupName,GroupType) VALUES (1,'Autistic Self Advocacy Network','Autism'),(2,'National Council on Independent Living','Disability Rights'),(3,'American Association of People with Disabilities','Disability Rights'); CREATE TABLE Funding (FundingID INT,GroupID INT,Amount DECIMAL(10,2),FundingDate DATE); INSERT INTO Funding(FundingID,GroupID,Amount,FundingDate) VALUES (1,1,5000,'2020-01-01'),(2,2,7000,'2021-01-01'),(3,3,9000,'2018-01-01');
SELECT PAG.GroupName, PAG.GroupType, F.Amount FROM PolicyAdvocacyGroups PAG INNER JOIN Funding F ON PAG.GroupID = F.GroupID WHERE F.FundingDate >= DATEADD(year, -1, GETDATE()) ORDER BY F.Amount DESC;
What is the average sea level rise in the Atlantic Ocean over the last 10 years?
CREATE TABLE sea_level (year INT,ocean VARCHAR(255),rise FLOAT); INSERT INTO sea_level (year,ocean,rise) VALUES (2012,'Atlantic Ocean',0.4),(2013,'Atlantic Ocean',0.5);
SELECT AVG(rise) FROM sea_level WHERE ocean = 'Atlantic Ocean' AND year BETWEEN 2012 AND 2021;
What is the sum of all oceanographic research grants awarded?
CREATE TABLE oceanographic_research_grants (grant_id INT,amount FLOAT); INSERT INTO oceanographic_research_grants (grant_id,amount) VALUES (1,50000.0),(2,75000.0),(3,100000.0);
SELECT SUM(amount) FROM oceanographic_research_grants;
What is the maximum balance of any digital asset with a type of 'asset'?
CREATE TABLE digital_assets (id INT,name TEXT,balance INT,type TEXT); INSERT INTO digital_assets (id,name,balance,type) VALUES (1,'Asset1',50,'token'),(2,'Asset2',100,'asset'),(3,'Asset3',150,'token'),(4,'Asset4',200,'asset');
SELECT MAX(digital_assets.balance) AS max_balance FROM digital_assets WHERE digital_assets.type = 'asset';
Calculate the average number of years of experience for artists from each country in the 'ArtistsDemographics' table, ordered by the average in descending order.
CREATE TABLE ArtistsDemographics (ArtistID INT,Age INT,Gender VARCHAR(10),Nationality VARCHAR(50),YearsOfExperience INT); INSERT INTO ArtistsDemographics (ArtistID,Age,Gender,Nationality,YearsOfExperience) VALUES (1,45,'Male','American',15),(2,34,'Female','Canadian',8),(3,50,'Male','British',22),(4,35,'Female','Mexican',10),(5,40,'Non-binary','Australian',12);
SELECT Nationality, AVG(YearsOfExperience) AS AvgYearsOfExperience FROM ArtistsDemographics GROUP BY Nationality ORDER BY AvgYearsOfExperience DESC;
What is the total attendance for each cultural event in the past year, ordered from highest to lowest?
CREATE TABLE cultural_events (event_id INT,event_name VARCHAR(255),event_date DATE); INSERT INTO cultural_events (event_id,event_name,event_date) VALUES (1,'Art Exhibit','2021-06-01'),(2,'Theatre Play','2021-07-15'),(3,'Music Concert','2021-08-20');
SELECT event_name, SUM(attendance) as total_attendance FROM events_attendance JOIN cultural_events ON events_attendance.event_id = cultural_events.event_id WHERE events_attendance.attendance_date >= DATEADD(year, -1, CURRENT_DATE) GROUP BY event_name ORDER BY total_attendance DESC;
What is the total number of artworks created by artists from Asia?
CREATE TABLE artworks (id INT,artist VARCHAR(100),collection VARCHAR(50),region VARCHAR(10)); INSERT INTO artworks (id,artist,collection,region) VALUES (1,'Min','Asian Collection','Asia'),(2,'Claudia','European Collection','Europe'),(3,'Hiroshi','Asian Collection','Asia');
SELECT COUNT(*) FROM artworks WHERE region = 'Asia';
How many peacekeeping operations were conducted in 2014?
CREATE TABLE PeacekeepingOperations (Year INT,Operation VARCHAR(50),Country VARCHAR(50)); INSERT INTO PeacekeepingOperations (Year,Operation,Country) VALUES (2014,'Operation 1','Country 1'),(2014,'Operation 2','Country 2');
SELECT COUNT(*) FROM PeacekeepingOperations WHERE Year = 2014;
Update the 'peace_agreement_signed' column in the 'peacekeeping_operations' table to 'Yes' for 'Operation United shield'
CREATE TABLE peacekeeping_operations (operation_id INT PRIMARY KEY,operation_name VARCHAR(50),start_date DATE,end_date DATE,participating_countries INT,peace_agreement_signed VARCHAR(50));
UPDATE peacekeeping_operations SET peace_agreement_signed = 'Yes' WHERE operation_name = 'Operation United shield';
What is the three-year trend of military innovation expenditure for each nation, ranked from highest to lowest?
CREATE TABLE MilitaryInnovation (Nation VARCHAR(50),Year INT,Expenditure DECIMAL(10,2)); INSERT INTO MilitaryInnovation (Nation,Year,Expenditure) VALUES ('USA',2019,500),('China',2019,400),('Russia',2019,300),('USA',2020,550),('China',2020,450),('Russia',2020,350),('USA',2021,600),('China',2021,500),('Russia',2021,400);
SELECT Nation, AVG(Expenditure) OVER (PARTITION BY Nation ORDER BY Year ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS AvgExpenditure, RANK() OVER (ORDER BY AVG(Expenditure) DESC) AS Rank FROM MilitaryInnovation GROUP BY Nation ORDER BY Rank;
Find the average age of customers in each city who have made a transaction over 5000 in the last 6 months.
CREATE TABLE customers (id INT,name VARCHAR(50),age INT,city VARCHAR(50)); CREATE TABLE transactions (id INT,customer_id INT,transaction_amount DECIMAL(10,2),transaction_date DATE); INSERT INTO transactions (id,customer_id,transaction_amount,transaction_date) VALUES (1,1,6000.00,'2022-01-01'),(2,2,9000.00,'2022-02-01');
SELECT city, AVG(age) as avg_age FROM customers JOIN transactions ON customers.id = transactions.customer_id WHERE transaction_amount > 5000 AND transaction_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY city;
How many transactions occurred in each region?
CREATE TABLE transactions (transaction_id INT,customer_id INT,region VARCHAR(20)); INSERT INTO transactions (transaction_id,customer_id,region) VALUES (1,1,'West Coast'),(2,2,'East Coast'),(3,3,'West Coast'),(4,4,'North East');
SELECT region, COUNT(*) FROM transactions GROUP BY region;
Calculate average sustainability score for each location
CREATE TABLE suppliers (id INT,name VARCHAR(255),location VARCHAR(255),sustainability_score FLOAT); INSERT INTO suppliers (id,name,location,sustainability_score) VALUES (1,'Supplier A','New York',8.5),(2,'Supplier B','Los Angeles',9.2),(3,'Supplier C','Chicago',7.8);
SELECT location, AVG(sustainability_score) FROM suppliers GROUP BY location;
Delete all records from the 'machines' table where the 'manufacturing_country' is 'Germany'
CREATE TABLE machines (id INT PRIMARY KEY,name VARCHAR(100),manufacturing_country VARCHAR(50));
DELETE FROM machines WHERE manufacturing_country = 'Germany';
Find the number of workforce training sessions per team, ordered by the total number of training sessions in descending order.
CREATE TABLE workforce_training (team VARCHAR(50),total_hours FLOAT); INSERT INTO workforce_training (team,total_hours) VALUES ('engineering',12.3),('production',14.7),('maintenance',NULL);
SELECT team, ROW_NUMBER() OVER (ORDER BY total_hours DESC) AS rank FROM workforce_training WHERE total_hours IS NOT NULL;
What is the total number of workers in each department across all factories?
CREATE TABLE factories (factory_id INT,department VARCHAR(255)); INSERT INTO factories VALUES (1,'Assembly'),(1,'Quality Control'),(2,'Design'),(2,'Testing'); CREATE TABLE workers (worker_id INT,factory_id INT,department VARCHAR(255),role VARCHAR(255)); INSERT INTO workers VALUES (1,1,'Assembly','Engineer'),(2,1,'Assembly','Technician'),(3,1,'Quality Control','Inspector'),(4,2,'Design','Architect'),(5,2,'Testing','Tester');
SELECT f.department, COUNT(w.worker_id) as total_workers FROM factories f JOIN workers w ON f.factory_id = w.factory_id GROUP BY f.department;
What is the average age of healthcare workers in 'rural_hospitals'?
CREATE TABLE if not exists 'rural_hospitals' (id INT,name TEXT,address TEXT,worker_age INT,PRIMARY KEY(id));
SELECT AVG(worker_age) FROM 'rural_hospitals';
What is the number of hospitals in each state, ordered by the number of hospitals?
CREATE TABLE hospitals (id INT,state VARCHAR(255),name VARCHAR(255)); INSERT INTO hospitals (id,state,name) VALUES (1,'NY','Hospital A'),(2,'CA','Hospital B'),(3,'TX','Hospital C');
SELECT state, COUNT(*) as hospital_count FROM hospitals GROUP BY state ORDER BY hospital_count DESC;
List the names of organizations that have made social impact investments in Latin America.
CREATE TABLE social_impact_investments (investment_id INT,organization_id INT,region VARCHAR(50)); CREATE TABLE organizations (organization_id INT,organization_name VARCHAR(100)); INSERT INTO social_impact_investments (investment_id,organization_id,region) VALUES (1,1,'Africa'),(2,2,'Europe'),(3,3,'Asia'),(4,5,'Latin America'); INSERT INTO organizations (organization_id,organization_name) VALUES (1,'Global Impact Fund'),(2,'Renewable Energy Foundation'),(3,'Community Housing Initiative'),(5,'Sustainable Agriculture Partners');
SELECT o.organization_name FROM social_impact_investments i INNER JOIN organizations o ON i.organization_id = o.organization_id WHERE i.region = 'Latin America';
What is the minimum response time for cybersecurity incidents in the last year?
CREATE TABLE cybersecurity_responses (id INT,incident_id INT,response_time INT); INSERT INTO cybersecurity_responses (id,incident_id,response_time) VALUES (1,1,60),(2,2,90),(3,3,120); CREATE VIEW recent_cybersecurity_responses AS SELECT * FROM cybersecurity_responses WHERE incident_date >= DATE_SUB(CURDATE(),INTERVAL 1 YEAR);
SELECT MIN(response_time) FROM recent_cybersecurity_responses;
How many new donors did we acquire in Q2 and Q3 of 2021?
CREATE TABLE Donors (donor_id INT,donor_name VARCHAR(50),first_donation_date DATE);
SELECT COUNT(*) FROM (SELECT donor_id FROM Donors WHERE first_donation_date BETWEEN '2021-04-01' AND '2021-09-30' GROUP BY donor_id HAVING COUNT(*) = 1);
Insert a new record in the 'courses' table with 'course_name' as 'Introduction to Open Pedagogy' and 'course_duration' as '15 weeks'
CREATE TABLE courses (course_id INT,course_name VARCHAR(50),course_duration VARCHAR(20));
INSERT INTO courses (course_name, course_duration) VALUES ('Introduction to Open Pedagogy', '15 weeks');
Calculate the maximum carbon price in Germany and Norway?
CREATE TABLE carbon_prices_gn (country VARCHAR(20),price DECIMAL(5,2)); INSERT INTO carbon_prices_gn (country,price) VALUES ('Germany',30.50),('Germany',31.20),('Germany',32.00),('Norway',40.00),('Norway',41.00),('Norway',42.00);
SELECT MAX(price) FROM carbon_prices_gn WHERE country IN ('Germany', 'Norway');
What is the carbon price in Europe and Australia for the last quarter of 2020?
CREATE TABLE CarbonPrices (Country TEXT,Year INT,Quarter INT,CarbonPrice NUMBER); INSERT INTO CarbonPrices (Country,Year,Quarter,CarbonPrice) VALUES ('Europe',2020,4,25),('Australia',2020,4,15); CREATE TABLE CarbonTaxes (Country TEXT,Year INT,Quarter INT,CarbonPrice NUMBER); INSERT INTO CarbonTaxes (Country,Year,Quarter,CarbonPrice) VALUES ('Europe',2019,4,20),('Australia',2019,4,10);
SELECT Context.Country, Context.CarbonPrice FROM ( SELECT * FROM CarbonPrices WHERE CarbonPrices.Country IN ('Europe', 'Australia') AND CarbonPrices.Year = 2020 AND CarbonPrices.Quarter = 4 UNION SELECT * FROM CarbonTaxes WHERE CarbonTaxes.Country IN ('Europe', 'Australia') AND CarbonTaxes.Year = 2020 AND CarbonTaxes.Quarter = 4 ) AS Context;
What is the average production of wells in 'FieldB' for the last quarter of 2019?
CREATE TABLE wells (well_id varchar(10),field varchar(10),production int,datetime date); INSERT INTO wells (well_id,field,production,datetime) VALUES ('W001','FieldB',1200,'2019-10-01'),('W002','FieldB',1400,'2019-11-01');
SELECT AVG(production) FROM wells WHERE field = 'FieldB' AND datetime BETWEEN DATE_SUB(LAST_DAY('2019-12-01'), INTERVAL 3 MONTH) AND LAST_DAY('2019-12-01');
Which rugby team has the most tries scored in the 'tries' table?
CREATE TABLE tries (try_id INT,player_id INT,match_id INT,team_id INT,tries INT); INSERT INTO tries (try_id,player_id,match_id,team_id,tries) VALUES (1,4,6,403,1);
SELECT team_id, SUM(tries) FROM tries GROUP BY team_id ORDER BY SUM(tries) DESC LIMIT 1;
Who is the player with the most points scored in a single NBA season?
CREATE TABLE nba_players (player_name VARCHAR(100),points INT,assists INT,rebounds INT); INSERT INTO nba_players VALUES ('Michael Jordan',3838,527,1404),('LeBron James',3627,650,1081),('Kareem Abdul-Jabbar',3838,454,1375),('James Harden',3044,876,534);
SELECT player_name, points FROM nba_players WHERE points = (SELECT MAX(points) FROM nba_players);
What is the previous project's end date for each project, ordered by start date?
CREATE TABLE projects_ext (id INT,project_name VARCHAR(50),location VARCHAR(50),start_date DATE,end_date DATE,budget DECIMAL(10,2)); INSERT INTO projects_ext (id,project_name,location,start_date,end_date,budget) VALUES (1,'Rebuilding School','Haiti','2022-05-01','2023-04-30',150000.00),(2,'Water Supply','Pakistan','2022-07-01','2024-06-30',200000.00);
SELECT project_name, start_date, LAG(end_date) OVER (ORDER BY start_date) AS prev_end_date FROM projects_ext ORDER BY start_date;
Which advocacy campaigns were launched in 'advocacy' table, and when?
CREATE TABLE advocacy (id INT,campaign VARCHAR(50),launch_date DATE,end_date DATE); INSERT INTO advocacy (id,campaign,launch_date,end_date) VALUES (1,'Child Rights','2021-01-01','2021-12-31'),(2,'Gender Equality','2021-02-01','2021-12-31');
SELECT campaign, launch_date FROM advocacy;
Find the difference in technology accessibility scores between the first and last quarters for each region.
CREATE TABLE accessibility (region VARCHAR(50),quarter INT,score INT); INSERT INTO accessibility (region,quarter,score) VALUES ('Americas',1,80),('Americas',2,85),('Americas',3,75),('Americas',4,90),('APAC',1,70),('APAC',2,75),('APAC',3,80),('APAC',4,85);
SELECT region, LAG(score, 3) OVER (PARTITION BY region ORDER BY quarter) - score as diff FROM accessibility;
What is the total number of devices for accessibility in Europe?
CREATE TABLE device_accessibility_europe (country VARCHAR(20),device VARCHAR(20),cost FLOAT); INSERT INTO device_accessibility_europe (country,device,cost) VALUES ('Germany','Screen Reader',110.00),('France','Adaptive Keyboard',95.00),('United Kingdom','Speech Recognition Software',130.00);
SELECT SUM(cost) FROM device_accessibility_europe WHERE country = 'Europe';
Who are the top 3 contributors in terms of total donations?
CREATE TABLE donors (id INT,donor_name VARCHAR(50),donation_amount DECIMAL(5,2),donation_date DATE); INSERT INTO donors (id,donor_name,donation_amount,donation_date) VALUES (1,'Donor1',1000.00,'2021-01-01'); INSERT INTO donors (id,donor_name,donation_amount,donation_date) VALUES (2,'Donor2',1500.00,'2021-02-15'); INSERT INTO donors (id,donor_name,donation_amount,donation_date) VALUES (3,'Donor3',2000.00,'2021-03-30');
SELECT donor_name, SUM(donation_amount) OVER (ORDER BY donation_amount DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS total_donations, RANK() OVER (ORDER BY SUM(donation_amount) DESC) AS rank FROM donors;
Show the number of donations made by each donor
CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,amount) VALUES (1,1,1000.00); INSERT INTO donations (id,donor_id,amount) VALUES (2,2,2000.00); INSERT INTO donations (id,donor_id,amount) VALUES (3,3,500.00);
SELECT donor_id, COUNT(*) as num_donations FROM donations GROUP BY donor_id;
How many genetic research projects were completed each year in Germany?
CREATE SCHEMA if not exists genetics; USE genetics; CREATE TABLE if not exists projects (id INT PRIMARY KEY,name VARCHAR(255),completion_date DATE,country VARCHAR(255)); INSERT INTO projects (id,name,completion_date,country) VALUES (1,'ProjectX','2017-12-31','Germany'),(2,'ProjectY','2018-06-15','Germany'),(3,'ProjectZ','2019-04-22','Germany'),(4,'ProjectP','2020-02-03','Germany'),(5,'ProjectQ','2021-01-01','Germany'),(6,'ProjectR','2016-08-08','USA');
SELECT YEAR(completion_date) AS year, COUNT(*) AS completed_projects FROM projects WHERE country = 'Germany' GROUP BY year ORDER BY year;
List the titles and filing dates of patents owned by GenTech.
CREATE TABLE company (id INT,name VARCHAR(50),industry VARCHAR(50),location VARCHAR(50)); INSERT INTO company (id,name,industry,location) VALUES (1,'GenTech','Genetic Research','San Francisco'); INSERT INTO company (id,name,industry,location) VALUES (2,'BioEngineer','Bioprocess Engineering','Boston'); INSERT INTO company (id,name,industry,location) VALUES (3,'BioSolutions','Bioprocess Engineering','Seattle'); CREATE TABLE patent (id INT,title VARCHAR(100),company_id INT,filing_date DATE); INSERT INTO patent (id,title,company_id,filing_date) VALUES (1,'GenTech Patent A',1,'2020-01-01'); INSERT INTO patent (id,title,company_id,filing_date) VALUES (2,'BioEngineer Patent B',2,'2019-06-15'); INSERT INTO patent (id,title,company_id,filing_date) VALUES (3,'GenTech Patent C',1,'2018-03-20');
SELECT title, filing_date FROM patent WHERE company_id IN (SELECT id FROM company WHERE name = 'GenTech')
Delete all FOIA requests with status 'Denied' in the 'foia_requests' table.
CREATE TABLE foia_requests (request_id INT,requester_name VARCHAR(100),request_date DATE,request_type VARCHAR(50),status VARCHAR(50));
DELETE FROM foia_requests WHERE status = 'Denied';
Identify community health workers who have not been assigned any health equity metrics in Texas.
CREATE TABLE health_equity_metrics (worker_id INT,metric TEXT); INSERT INTO health_equity_metrics (worker_id,metric) VALUES (1,'Accessibility'); CREATE TABLE community_health_workers_tx (worker_id INT,name TEXT); INSERT INTO community_health_workers_tx (worker_id,name) VALUES (1,'Alice Johnson');
SELECT c.name FROM community_health_workers_tx c LEFT JOIN health_equity_metrics h ON c.worker_id = h.worker_id WHERE h.worker_id IS NULL AND c.name = 'Alice Johnson';
What is the total number of mental health parity cases reported in 2020 and 2021?
CREATE TABLE MentalHealthParity (CaseID INT,ReportYear INT); INSERT INTO MentalHealthParity (CaseID,ReportYear) VALUES (1,2020),(2,2021),(3,2020),(4,2020),(5,2021);
SELECT SUM(CASE WHEN ReportYear IN (2020, 2021) THEN 1 ELSE 0 END) as TotalCases FROM MentalHealthParity;
What is the average revenue per OTA booking in the NA region for the last quarter?
CREATE TABLE ota_bookings_2 (booking_id INT,ota_name TEXT,region TEXT,booking_amount DECIMAL(10,2)); INSERT INTO ota_bookings_2 (booking_id,ota_name,region,booking_amount) VALUES (1,'Booking.com','NA',200.50),(2,'Expedia','NA',150.25),(3,'Agoda','APAC',300.00),(4,'Expedia','NA',250.00);
SELECT AVG(booking_amount) FROM ota_bookings_2 WHERE region = 'NA' AND booking_date >= DATEADD(quarter, -1, GETDATE());