instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Show the 'name' and 'investment_amount' of all investors who have invested more than 50000 in the 'biosensors' table
CREATE TABLE investors (id INT PRIMARY KEY,name TEXT); CREATE TABLE biosensors (id INT PRIMARY KEY,investor_id INT,investment_amount INT);
SELECT i.name, b.investment_amount FROM investors i JOIN biosensors b ON i.id = b.investor_id WHERE b.investment_amount > 50000;
Update the name of StartupA to NewStartupA.
CREATE TABLE startups (id INT,name VARCHAR(50),location VARCHAR(50),funding FLOAT); INSERT INTO startups VALUES (1,'StartupA','California',15000000); INSERT INTO startups VALUES (2,'StartupB','New York',20000000); INSERT INTO startups VALUES (3,'StartupC','California',25000000);
UPDATE startups SET name = 'NewStartupA' WHERE name = 'StartupA';
What is the total funding for Genetic Research at 'Genome Inc.'?
CREATE TABLE genome_inc (id INT,project TEXT,funding FLOAT); INSERT INTO genome_inc (id,project,funding) VALUES (1,'Genetic Research',12000000.0); INSERT INTO genome_inc (id,project,funding) VALUES (2,'Bioprocess Engineering',8000000.0);
SELECT SUM(funding) FROM genome_inc WHERE project = 'Genetic Research';
What is the total size of all green buildings in India with GRIHA certification?
CREATE TABLE green_buildings (id INT,city VARCHAR(255),country VARCHAR(255),certification VARCHAR(255),size INT); INSERT INTO green_buildings (id,city,country,certification,size) VALUES (2,'Mumbai','India','GRIHA',12000);
SELECT SUM(size) as total_size FROM green_buildings WHERE country = 'India' AND certification = 'GRIHA';
Who are the top 5 green building contractors in the state of California based on their total number of certified green building projects?
CREATE TABLE contractors (contractor_id INT,contractor_name VARCHAR(100),state VARCHAR(100)); CREATE TABLE green_buildings (building_id INT,contractor_id INT,building_name VARCHAR(100),certification VARCHAR(50)); INSERT INTO contractors (contractor_id,contractor_name,state) VALUES (1,'GreenBuild Inc','CA'); INSERT INTO green_buildings (building_id,contractor_id,building_name,certification) VALUES (1,1,'GreenHouse','LEED Platinum'),(2,1,'GreenPlace','LEED Gold');
SELECT contractor_name, COUNT(*) AS total_certified_projects FROM green_buildings INNER JOIN contractors ON green_buildings.contractor_id = contractors.contractor_id WHERE contractors.state = 'CA' GROUP BY contractor_name ORDER BY total_certified_projects DESC LIMIT 5;
What are the top 3 countries with the highest number of heritage sites?
CREATE TABLE Countries (id INT,name TEXT); INSERT INTO Countries (id,name) VALUES (1,'Italy'); CREATE TABLE CountryHeritages (id INT,country_id INT,heritage_site TEXT); INSERT INTO CountryHeritages (id,country_id,heritage_site) VALUES (1,1,'Colosseum');
SELECT C.name, COUNT(*) FROM Countries C INNER JOIN CountryHeritages CH ON C.id = CH.country_id GROUP BY C.name ORDER BY COUNT(*) DESC LIMIT 3;
What is the average number of languages spoken per country in Southeast Asia?
CREATE TABLE continents (id INT,name TEXT); INSERT INTO continents (id,name) VALUES (1,'Asia'),(2,'Africa'); CREATE TABLE countries (id INT,continent_id INT,name TEXT); INSERT INTO countries (id,continent_id,name) VALUES (1,1,'Indonesia'),(2,1,'Philippines'),(3,2,'Nigeria'); CREATE TABLE languages (id INT,country_id INT,name TEXT); INSERT INTO languages (id,country_id,name) VALUES (1,1,'Indonesian'),(2,1,'Javanese'),(3,2,'Filipino'),(4,2,'Cebuano'),(5,3,'Hausa');
SELECT c.continent_id, AVG(COUNT(*)) FROM countries c JOIN languages l ON c.id = l.country_id WHERE c.continent_id = 1 GROUP BY c.continent_id;
How many patients have been diagnosed with anxiety in Germany?
CREATE TABLE diagnoses (id INT,patient_id INT,condition VARCHAR(255)); CREATE TABLE patients (id INT,age INT,country VARCHAR(255)); INSERT INTO diagnoses (id,patient_id,condition) VALUES (1,1,'Depression'),(2,2,'Anxiety'),(3,3,'Bipolar'),(4,4,'Anxiety'); INSERT INTO patients (id,age,country) VALUES (1,35,'Germany'),(2,42,'Canada'),(3,28,'Mexico'),(4,31,'Germany');
SELECT COUNT(*) FROM diagnoses JOIN patients ON diagnoses.patient_id = patients.id WHERE diagnoses.condition = 'Anxiety' AND patients.country = 'Germany';
What are the average maintenance costs for airports in Germany?
CREATE TABLE Airport (id INT,name VARCHAR(50),maintenance_cost FLOAT,country VARCHAR(50)); INSERT INTO Airport (id,name,maintenance_cost,country) VALUES (1,'Frankfurt Airport',5000000,'Germany');
SELECT AVG(maintenance_cost) FROM Airport WHERE country = 'Germany' AND type = 'Airport';
Identify the number of pollution incidents in each country's coastal waters.
CREATE SCHEMA MarinePollution(pollution_id INT,country_name TEXT,incident_date DATE);INSERT INTO MarinePollution(pollution_id,country_name,incident_date) VALUES (1,'Canada','2021-06-01'),(2,'Mexico','2021-07-15'),(3,'USA','2021-08-05'),(4,'Canada','2021-09-20');
SELECT country_name, COUNT(*) FROM MarinePollution GROUP BY country_name;
How many TV shows were produced in Spain in 2017?
CREATE TABLE tv_shows (id INT,title TEXT,country TEXT,year INT); INSERT INTO tv_shows (id,title,country,year) VALUES (1,'ShowA','Spain',2017),(2,'ShowB','Spain',2018),(3,'ShowC','USA',2019);
SELECT COUNT(*) FROM tv_shows WHERE country = 'Spain' AND year = 2017;
What's the earliest publication date of articles in the 'Tech' category?
CREATE TABLE articles_tech (id INT,title TEXT,category TEXT,pub_date DATE); INSERT INTO articles_tech (id,title,category,pub_date) VALUES (1,'Article1','Tech','2022-01-01'),(2,'Article2','Tech','2022-01-10');
SELECT MIN(pub_date) FROM articles_tech WHERE category = 'Tech';
Find the number of menu items prepared with allergen-free options and the percentage of total items.
CREATE TABLE menus (menu_item_name VARCHAR(255),daily_sales INT,has_allergen_free BOOLEAN);
SELECT COUNT(*) as num_allergen_free, (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM menus)) as allergen_free_percentage FROM menus WHERE has_allergen_free = TRUE;
How many 'Veggie Burgers' were sold in each region?
CREATE TABLE Regional_Sales(Region VARCHAR(20),Menu_Item VARCHAR(30),Quantity INT); INSERT INTO Regional_Sales(Region,Menu_Item,Quantity) VALUES('Northeast','Veggie Burger',50),('Midwest','Veggie Burger',75),('South','Veggie Burger',100);
SELECT Region, SUM(Quantity) as Total_Quantity FROM Regional_Sales WHERE Menu_Item = 'Veggie Burger' GROUP BY Region;
What is the revenue generated from the sale of organic dishes in the last month?
CREATE TABLE inventory (item_id INT,quantity INT,unit_price DECIMAL(5,2),is_organic BOOLEAN); INSERT INTO inventory (item_id,quantity,unit_price,is_organic) VALUES (1,10,12.99,true),(2,20,7.50,false),(3,30,9.99,true),(4,40,15.49,false),(5,50,8.99,true); CREATE TABLE orders (order_id INT,item_id INT,order_date DATE); INSERT INTO orders (order_id,item_id,order_date) VALUES (1,1,'2022-01-01'),(2,3,'2022-01-02'),(3,2,'2022-01-03'),(4,4,'2022-01-04'),(5,5,'2022-01-05'); CREATE TABLE menu_items (item_id INT,name TEXT,is_organic BOOLEAN); INSERT INTO menu_items (item_id,name,is_organic) VALUES (1,'Quinoa Salad',true),(2,'Beef Burger',false),(3,'Chickpea Curry',true),(4,'Cheesecake',false),(5,'Veggie Pizza',true);
SELECT SUM(i.unit_price * o.quantity) as revenue FROM inventory i JOIN orders o ON i.item_id = o.item_id JOIN menu_items m ON i.item_id = m.item_id WHERE m.is_organic = true AND o.order_date BETWEEN '2022-02-01' AND '2022-02-28';
What is the maximum number of naval vessels sold by ArmaTech in Europe?
CREATE TABLE IF NOT EXISTS naval_sales (vessel_id int,quantity_sold int,company varchar(30),region varchar(30)); INSERT INTO naval_sales (vessel_id,quantity_sold,company,region) VALUES (1,10,'ArmaTech','Europe'),(2,12,'ArmaTech','Europe'),(3,8,'ArmaTech','Europe');
SELECT MAX(quantity_sold) FROM naval_sales WHERE company = 'ArmaTech' AND region = 'Europe';
How many unique genres did artists from Africa perform at music festivals in 2022?
CREATE TABLE Artists (region VARCHAR(50),festival_performance INT); INSERT INTO Artists (region,festival_performance) VALUES ('Africa',1); INSERT INTO Artists (region,festival_performance) VALUES ('Africa',2);
SELECT COUNT(DISTINCT genre) FROM Festivals WHERE region = 'Africa' AND festival_performance = 1;
Delete audience demographics records from 'Russia' where age is less than 18.
CREATE TABLE audience_demographics (id INT,age INT,country TEXT);
DELETE FROM audience_demographics WHERE age < 18 AND country = 'Russia';
Delete players who have not played any VR games and are under 25 years old.
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),HasPlayedVR BOOLEAN); INSERT INTO Players (PlayerID,Age,Gender,HasPlayedVR) VALUES (1,25,'Male',TRUE),(2,30,'Female',FALSE),(3,22,'Male',TRUE),(4,19,'Non-binary',FALSE);
DELETE FROM Players WHERE HasPlayedVR = FALSE AND Age < 25;
What is the average prize pool of RPG games in North America?
CREATE TABLE PrizePools (EventID INT,Game VARCHAR(10),PrizePool DECIMAL(10,2),Region VARCHAR(10)); INSERT INTO PrizePools (EventID,Game,PrizePool,Region) VALUES (1,'WoW',100000,'North America');
SELECT AVG(PrizePool) FROM PrizePools WHERE Game = 'WoW' AND Region = 'North America';
Count the number of sensors
CREATE TABLE sensor (id INT); INSERT INTO sensor (id) VALUES (1),(2),(3),(4),(5);
SELECT COUNT(*) FROM sensor;
Remove the irrigation record with ID I031
CREATE TABLE irrigation_data (irrigation_id INT,farm_id INT,irrigation_percentage INT);
DELETE FROM irrigation_data WHERE irrigation_id = 31;
Calculate the percentage of total Europium production for each country.
CREATE TABLE europium_production (country VARCHAR(50),quantity INT);
SELECT country, quantity * 100.0 / SUM(quantity) OVER (PARTITION BY NULL) AS percentage FROM europium_production;
What is the maximum revenue generated from selling Yttrium in India in the past 3 years?
CREATE TABLE Yttrium_Sales (id INT PRIMARY KEY,year INT,country VARCHAR(20),quantity INT,price PER_KG); INSERT INTO Yttrium_Sales (id,year,country,quantity,price) VALUES (1,2019,'India',120,40),(2,2020,'India',130,45),(3,2021,'India',140,50),(4,2019,'China',150,35),(5,2020,'China',160,40),(6,2021,'China',170,45);
SELECT MAX(quantity * price) FROM Yttrium_Sales WHERE country = 'India' GROUP BY year ORDER BY year DESC LIMIT 3;
Update the price of 'Tofu Stir Fry' to 12.99 in 'Green Garden' restaurant if the current price is less than 12.99.
CREATE TABLE menu (menu_id INT,item_name VARCHAR(50),price DECIMAL(5,2),category VARCHAR(20),restaurant_id INT); INSERT INTO menu (menu_id,item_name,price,category,restaurant_id) VALUES (6,'Tofu Stir Fry',11.99,'Vegan',5),(7,'Chickpea Curry',13.99,'Vegan',5);
UPDATE menu SET price = 12.99 WHERE item_name = 'Tofu Stir Fry' AND restaurant_id = 5 AND price < 12.99;
What is the minimum revenue for restaurants serving Ethiopian food?
CREATE TABLE Restaurants (id INT,name TEXT,type TEXT,revenue FLOAT); INSERT INTO Restaurants (id,name,type,revenue) VALUES (1,'Restaurant A','Italian',5000.00),(2,'Restaurant B','Ethiopian',6000.00),(3,'Restaurant C','Ethiopian',5500.00),(4,'Restaurant D','Ethiopian',5000.00);
SELECT MIN(revenue) FROM Restaurants WHERE type = 'Ethiopian';
What is the total revenue generated from ethical labor practices in South America?
CREATE TABLE Revenue (RID INT,Practice VARCHAR(20),Revenue FLOAT,Country VARCHAR(20)); INSERT INTO Revenue VALUES (1,'Ethical Labor',5000,'South America'); INSERT INTO Revenue VALUES (2,'Ethical Labor',7000,'South America');
SELECT SUM(Revenue) FROM Revenue WHERE Practice = 'Ethical Labor' AND Country = 'South America';
What is the name of the spacecraft with the highest mass in GTO (Geostationary Transfer Orbit)?
CREATE TABLE space_craft (id INT,name VARCHAR(50),type VARCHAR(50),mass FLOAT,orbit VARCHAR(50)); INSERT INTO space_craft (id,name,type,mass,orbit) VALUES (1,'Tianhe-1','Space Station Module',22000,'GTO'); INSERT INTO space_craft (id,name,type,mass,orbit) VALUES (2,'Spaceway-1','Communications Satellite',6000,'GTO');
SELECT name FROM space_craft WHERE orbit = 'GTO' ORDER BY mass DESC LIMIT 1;
What is the total mass of all space debris in orbit?
CREATE TABLE Space_Debris (ID INT,Object_Type VARCHAR(50),Mass FLOAT); INSERT INTO Space_Debris (ID,Object_Type,Mass) VALUES (1,'Defunct Satellite',1500.0),(2,'Rocket Body',2000.0),(3,'Fuel Tank',500.0),(4,'Nuts and Bolts',100.0),(5,'Spent Rocket Stage',3000.0);
SELECT SUM(Mass) FROM Space_Debris;
What are the total ticket sales for each team's home games, excluding any complimentary tickets?
CREATE TABLE team_performance (team_id INT,home_game BOOLEAN,total_sales DECIMAL(10,2)); INSERT INTO team_performance (team_id,home_game,total_sales) VALUES (1,true,5000.00),(1,false,0.00),(2,true,7000.00),(2,false,3000.00);
SELECT team_id, SUM(total_sales) FROM team_performance WHERE home_game = true AND total_sales > 0 GROUP BY team_id;
Find the number of sales for each salesperson, and the total revenue for each salesperson, ordered by the number of sales in descending order.
CREATE TABLE sales (sale_id INT,salesperson_id INT,revenue DECIMAL(10,2)); INSERT INTO sales VALUES (1,1,100.00),(2,1,200.00),(3,2,300.00),(4,2,400.00),(5,3,50.00),(6,3,100.00);
SELECT salesperson_id, COUNT(*) as num_sales, SUM(revenue) as total_revenue FROM sales GROUP BY salesperson_id ORDER BY num_sales DESC;
Identify the top 3 countries with the highest average sustainability rating among suppliers.
CREATE TABLE suppliers (id INT PRIMARY KEY,name VARCHAR(50),country VARCHAR(50),sustainability_rating DECIMAL(3,2)); INSERT INTO suppliers (id,name,country,sustainability_rating) VALUES (1,'Green Fabrics','Bangladesh',4.50); INSERT INTO suppliers (id,name,country,sustainability_rating) VALUES (2,'Eco Yarns','Indonesia',4.75); INSERT INTO suppliers (id,name,country,sustainability_rating) VALUES (3,'Sustainable Weaves','India',4.25); INSERT INTO suppliers (id,name,country,sustainability_rating) VALUES (4,'Eco Fibres','Nepal',4.85); INSERT INTO suppliers (id,name,country,sustainability_rating) VALUES (5,'Organic Textiles','Pakistan',4.10);
SELECT country, AVG(sustainability_rating) as avg_sustainability_rating, RANK() OVER (ORDER BY AVG(sustainability_rating) DESC) as ranking FROM suppliers GROUP BY country HAVING COUNT(*) FILTER (WHERE sustainability_rating > 0) >= 3 ORDER BY avg_sustainability_rating DESC, country;
Which policyholders in the Midwest have had claims worth more than $1000?
CREATE TABLE Policyholder (PolicyholderID INT,Name VARCHAR(50),Region VARCHAR(20)); CREATE TABLE Policy (PolicyID INT,PolicyholderID INT,PolicyType VARCHAR(20)); CREATE TABLE Claim (ClaimID INT,PolicyID INT,ClaimAmount INT); INSERT INTO Policyholder (PolicyholderID,Name,Region) VALUES (1,'John Doe','Midwest'),(2,'Jane Smith','Northeast'); INSERT INTO Policy (PolicyID,PolicyholderID,PolicyType) VALUES (1,1,'Auto'),(2,1,'Home'),(3,2,'Life'); INSERT INTO Claim (ClaimID,PolicyID,ClaimAmount) VALUES (1,1,500),(2,2,2000),(3,3,50000);
SELECT PolicyholderID, Name FROM (SELECT PolicyholderID, Name, PolicyType, ClaimAmount, ROW_NUMBER() OVER (PARTITION BY PolicyholderID ORDER BY ClaimAmount DESC) AS RankClaimAmount FROM Policyholder JOIN Policy ON Policyholder.PolicyholderID = Policy.PolicyholderID JOIN Claim ON Policy.PolicyID = Claim.PolicyID WHERE Region = 'Midwest') AS Subquery WHERE RankClaimAmount = 1 AND ClaimAmount > 1000;
What is the average number of employees in unionized workplaces in the USA?
CREATE TABLE workplaces (id INT,country VARCHAR(50),num_employees INT,is_unionized BOOLEAN); INSERT INTO workplaces (id,country,num_employees,is_unionized) VALUES (1,'Canada',200,true),(2,'USA',300,true),(3,'Mexico',150,false);
SELECT AVG(num_employees) FROM workplaces WHERE country = 'USA' AND is_unionized = true;
What is the average number of workers per industry?
CREATE TABLE if not exists industry (industry_id INT,industry_name TEXT,total_workers INT); INSERT INTO industry (industry_id,industry_name,total_workers) VALUES (1,'manufacturing',5000),(2,'technology',7000),(3,'healthcare',6000),(4,'finance',4000),(5,'retail',3000);
SELECT AVG(total_workers) FROM industry;
Compute the average speed for 'VesselL' during its journeys
CREATE TABLE vessel_speed (vessel_name TEXT,journey_id INTEGER,speed INTEGER); INSERT INTO vessel_speed (vessel_name,journey_id,speed) VALUES ('VesselL',4001,25); INSERT INTO vessel_speed (vessel_name,journey_id,speed) VALUES ('VesselL',4002,28);
SELECT AVG(speed) FROM vessel_speed WHERE vessel_name = 'VesselL';
List all visitors who have visited more than one exhibition
CREATE TABLE Visitor (id INT,name TEXT); CREATE TABLE Visitor_Exhibition (visitor_id INT,exhibition_id INT); INSERT INTO Visitor (id,name) VALUES (1,'Alice'),(2,'Bob'),(3,'Charlie'); INSERT INTO Visitor_Exhibition (visitor_id,exhibition_id) VALUES (1,1),(1,2),(2,1),(3,1),(3,2);
SELECT Visitor.name FROM Visitor JOIN Visitor_Exhibition ON Visitor.id = Visitor_Exhibition.visitor_id GROUP BY Visitor.name HAVING COUNT(DISTINCT Visitor_Exhibition.exhibition_id) > 1;
Delete records of recycling rates for the year 2018
CREATE TABLE recycling_rates (country VARCHAR(50),year INT,recycling_rate FLOAT); INSERT INTO recycling_rates (country,year,recycling_rate) VALUES ('India',2018,0.25),('India',2019,0.30);
DELETE FROM recycling_rates WHERE year = 2018;
What is the total volume of water saved by water conservation initiatives in San Diego in 2019?
CREATE TABLE WaterConservationInitiatives (id INT,city VARCHAR,year INT,savings INT); INSERT INTO WaterConservationInitiatives (id,city,year,savings) VALUES (1,'San Diego',2019,1200000),(2,'San Diego',2018,1150000),(3,'San Francisco',2019,1300000);
SELECT SUM(savings) FROM WaterConservationInitiatives WHERE city = 'San Diego' AND year = 2019;
Delete the workout row with the id of 2.
CREATE TABLE Workouts (id INT,user_id INT,workout_name TEXT,calories INT); INSERT INTO Workouts (id,user_id,workout_name,calories) VALUES (1,1,'Running',300); INSERT INTO Workouts (id,user_id,workout_name,calories) VALUES (2,1,'Cycling',400); INSERT INTO Workouts (id,user_id,workout_name,calories) VALUES (3,2,'Yoga',200);
DELETE FROM Workouts WHERE id = 2;
How many algorithmic fairness incidents were reported in Asia in the last quarter?
CREATE TABLE fairness_incidents (incident_id INT,incident_date DATE,region TEXT); INSERT INTO fairness_incidents (incident_id,incident_date,region) VALUES (1,'2022-04-15','Asia'),(2,'2022-05-11','Asia'),(3,'2022-06-01','Asia');
SELECT COUNT(*) FROM fairness_incidents WHERE region = 'Asia' AND incident_date >= '2022-04-01' AND incident_date < '2022-07-01';
What is the average number of explainable AI models developed per month in Singapore in 2021?
CREATE TABLE explainable_ai (model_id INT,model_name TEXT,launch_date DATE,country TEXT); INSERT INTO explainable_ai (model_id,model_name,launch_date,country) VALUES (1,'XAI_Healthcare','2021-02-14','Singapore'),(2,'TransparentML','2021-06-22','Singapore'),(3,'ClearAI','2021-09-03','Singapore');
SELECT AVG(num_models) as avg_models_per_month FROM (SELECT COUNT(*) as num_models, EXTRACT(MONTH FROM launch_date) as month FROM explainable_ai WHERE country = 'Singapore' AND launch_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY month) as subquery;
Count the number of accidents for each spacecraft.
CREATE TABLE Accidents (accident_id INT,spacecraft VARCHAR(50),accident_date DATE);
SELECT spacecraft, COUNT(*) FROM Accidents GROUP BY spacecraft;
How many successful satellite deployments has SpaceX achieved in the last 5 years?
CREATE TABLE Satellite_Deployments (id INT,name VARCHAR(50),manufacturer VARCHAR(50),deployment_date DATE,success BOOLEAN); INSERT INTO Satellite_Deployments (id,name,manufacturer,deployment_date,success) VALUES (1,'Starlink 1','SpaceX','2018-05-23',true),(2,'Starlink 2','SpaceX','2019-11-11',true),(3,'Starship','SpaceX','2023-03-14',false);
SELECT COUNT(*) FROM Satellite_Deployments WHERE manufacturer = 'SpaceX' AND success = true AND YEAR(deployment_date) >= 2017;
Count the number of community education programs for each country
CREATE TABLE community_education (id INT,country VARCHAR(50),program VARCHAR(50)); INSERT INTO community_education (id,country,program) VALUES (1,'Brazil','Rainforest Awareness'),(2,'Kenya','Wildlife Conservation'),(3,'Canada','Polar Bear Protection'),(4,'Brazil','Amazon Conservation');
SELECT country, COUNT(program) FROM community_education GROUP BY country;
Create a view that lists fish species and their average biomass
CREATE TABLE fish_stock (fish_id INT PRIMARY KEY,species VARCHAR(50),location VARCHAR(50),biomass FLOAT); INSERT INTO fish_stock (fish_id,species,location,biomass) VALUES (1,'Tuna','Pacific',250.5),(2,'Salmon','Atlantic',180.3),(3,'Cod','Baltic',120.0);
CREATE VIEW fish_biomass AS SELECT species, AVG(biomass) as avg_biomass FROM fish_stock GROUP BY species;
Calculate the average age of attendees who attended 'Dance' events.
CREATE TABLE attendee_demographics (attendee_id INT,attendee_name VARCHAR(50),attendee_age INT); INSERT INTO attendee_demographics (attendee_id,attendee_name,attendee_age) VALUES (1,'Jane Smith',25),(2,'Michael Johnson',17),(3,'Sophia Rodriguez',16),(4,'David Kim',22); CREATE TABLE event_attendance (attendee_id INT,event_name VARCHAR(50)); INSERT INTO event_attendance (attendee_id,event_name) VALUES (1,'Art Exhibit'),(2,'Art Workshop'),(3,'Art Exhibit'),(4,'Dance Performance'),(5,'Dance Festival');
SELECT AVG(ad.attendee_age) FROM attendee_demographics ad JOIN event_attendance ea ON ad.attendee_id = ea.attendee_id WHERE ea.event_name LIKE '%Dance%';
Delete a record from the "genres" table where the genre is from Russia
CREATE TABLE genres (id INT PRIMARY KEY,name VARCHAR(100),country VARCHAR(50));
DELETE FROM genres WHERE country = 'Russia';
What is the total funding received by dance programs in California since 2017?
CREATE TABLE Funding (id INT,program VARCHAR(50),location VARCHAR(50),date DATE,amount DECIMAL(10,2)); INSERT INTO Funding (id,program,location,date,amount) VALUES (1,'Dance','California','2017-01-01',5000);
SELECT SUM(amount) FROM Funding WHERE program = 'Dance' AND location = 'California' AND date >= '2017-01-01';
What's the average production budget for action movies released between 2010 and 2020, and their respective release years?
CREATE TABLE movies (id INT,title VARCHAR(100),genre VARCHAR(20),release_year INT,production_budget INT); INSERT INTO movies (id,title,genre,release_year,production_budget) VALUES (1,'MovieA','Action',2015,150000000); INSERT INTO movies (id,title,genre,release_year,production_budget) VALUES (2,'MovieB','Action',2018,200000000);
SELECT release_year, AVG(production_budget) FROM movies WHERE genre = 'Action' AND release_year BETWEEN 2010 AND 2020 GROUP BY release_year;
Rank projects by the number of labor hours in descending order in the Northeast.
CREATE TABLE project (project_id INT,region VARCHAR(20),labor_hours INT); INSERT INTO project VALUES (1,'Northeast',500); INSERT INTO project VALUES (2,'Northeast',700);
SELECT project_id, region, labor_hours, RANK() OVER (ORDER BY labor_hours DESC) as labor_rank FROM project WHERE region = 'Northeast';
What is the average quantity of Sulfuric Acid disposed in July?
CREATE TABLE Waste_Disposal (id INT,chemical_name VARCHAR(255),disposal_date DATE,quantity INT); INSERT INTO Waste_Disposal (id,chemical_name,disposal_date,quantity) VALUES (1,'Sulfuric Acid','2022-07-15',300);
SELECT AVG(quantity) FROM Waste_Disposal WHERE chemical_name = 'Sulfuric Acid' AND disposal_date BETWEEN '2022-07-01' AND '2022-07-31';
What is the maximum safety score for chemical products manufactured in the Asian region?
CREATE TABLE Manufacturers (ManufacturerID INT,ManufacturerName TEXT,Region TEXT); INSERT INTO Manufacturers (ManufacturerID,ManufacturerName,Region) VALUES (1,'ABC Chemicals','Asia'),(2,'XYZ Chemicals','North America'),(3,' DEF Chemicals','Asia'); CREATE TABLE ChemicalProducts (ProductID INT,Chemical TEXT,ManufacturerID INT,SafetyScore DECIMAL(3,2)); INSERT INTO ChemicalProducts (ProductID,Chemical,ManufacturerID,SafetyScore) VALUES (1,'Acetone',1,3.2),(2,'Ethanol',1,4.5),(3,'Methanol',2,5.0),(4,'Propanol',3,4.8),(5,'Butanol',3,5.0);
SELECT MAX(CP.SafetyScore) AS MaxScore FROM ChemicalProducts CP INNER JOIN Manufacturers M ON CP.ManufacturerID = M.ManufacturerID WHERE M.Region = 'Asia';
What is the total number of climate finance projects in Asia?
CREATE TABLE climate_finance (id INT,project_name TEXT,location TEXT,sector TEXT); INSERT INTO climate_finance (id,project_name,location,sector) VALUES (1,'Solar Farm','Asia','Renewable Energy'); INSERT INTO climate_finance (id,project_name,location,sector) VALUES (2,'Wind Turbines','Europe','Renewable Energy');
SELECT COUNT(*) FROM climate_finance WHERE location = 'Asia';
What is the total revenue for drugs approved between 2017 and 2019?
CREATE TABLE drug_sales_3 (drug_name TEXT,revenue FLOAT,year INT); INSERT INTO drug_sales_3 (drug_name,revenue,year) VALUES ('DrugG',20000000,2019),('DrugG',19000000,2018),('DrugH',15000000,2017),('DrugH',16000000,2018);
SELECT drug_name, SUM(revenue) FROM drug_sales_3 WHERE year BETWEEN 2017 AND 2019 GROUP BY drug_name;
How many community health centers are there in urban areas?
CREATE TABLE community_health_centers (id INT,name TEXT,location TEXT); INSERT INTO community_health_centers (id,name,location) VALUES (1,'Center A','urban'),(2,'Center B','rural');
SELECT COUNT(*) FROM community_health_centers WHERE location = 'urban';
What is the average date of hire for employees in the 'GreenTech' industry?
CREATE TABLE Company (id INT,name TEXT,industry TEXT,location TEXT); INSERT INTO Company (id,name,industry,location) VALUES (1,'EcoInnovations','GreenTech','Nigeria'),(2,'BioSolutions','Biotech','Brazil'),(3,'TechBoost','Tech','India'); CREATE TABLE Employee (id INT,company_id INT,name TEXT,role TEXT,gender TEXT,ethnicity TEXT,date_hired DATE); INSERT INTO Employee (id,company_id,name,role,gender,ethnicity,date_hired) VALUES (1,1,'Amina','Software Engineer','Female','Black','2021-01-10'),(2,1,'Bruno','Data Scientist','Male','Latino','2020-06-01'),(3,2,'Chen','Hardware Engineer','Non-binary','Asian','2019-12-20'),(4,3,'Dana','Product Manager','Female','White','2022-03-01');
SELECT AVG(Employee.date_hired) FROM Employee INNER JOIN Company ON Company.id = Employee.company_id WHERE Company.industry = 'GreenTech';
Which countries have the most urban agriculture initiatives in the 'urban_agriculture' table?
CREATE TABLE urban_agriculture (id INT,country VARCHAR(255),initiatives INT); INSERT INTO urban_agriculture (id,country,initiatives) VALUES (1,'Brazil',500),(2,'India',750),(3,'China',800),(4,'South Africa',300);
SELECT country, initiatives FROM urban_agriculture ORDER BY initiatives DESC;
What is the minimum budget spent on disability support programs for each type of accommodation?
CREATE TABLE AccommodationTypes (id INT,type TEXT,budget DECIMAL(10,2)); INSERT INTO AccommodationTypes (id,type,budget) VALUES (1,'Ramp',10000.00),(2,'Elevator',20000.00),(3,'Handrail',5000.00);
SELECT type, MIN(budget) FROM AccommodationTypes GROUP BY type;
Find the number of conservation programs in the Pacific Ocean.
CREATE TABLE conservation_efforts (id INT PRIMARY KEY,species VARCHAR(255),country VARCHAR(255),program VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO conservation_efforts (id,species,country,program,start_date,end_date) VALUES (1,'tuna','USA','Pacific_conservation','2020-01-01','2023-12-31');
SELECT COUNT(program) FROM conservation_efforts WHERE country = 'Pacific Ocean';
Find the top 2 sustainable ingredients with the highest average rating, along with the total number of products that contain each ingredient.
CREATE TABLE ingredients (ingredient_id INT,ingredient_name VARCHAR(50),sustainability_rating INT,product_id INT); INSERT INTO ingredients (ingredient_id,ingredient_name,sustainability_rating,product_id) VALUES (1,'Argan Oil',5,1001),(2,'Shea Butter',5,1002),(3,'Jojoba Oil',4,1003),(4,'Coconut Oil',5,1004),(5,'Aloe Vera',4,1005);
SELECT ingredient_name, AVG(sustainability_rating) as avg_rating, COUNT(product_id) as total_products FROM ingredients GROUP BY ingredient_name ORDER BY avg_rating DESC, total_products DESC LIMIT 2;
What is the average carbon footprint of cosmetic products up to a given product_id?
CREATE TABLE sustainability_metrics (product_id INT,carbon_footprint FLOAT); INSERT INTO sustainability_metrics (product_id,carbon_footprint) VALUES (1,5.0),(2,7.5),(3,3.0),(4,6.0),(5,4.5),(6,8.0);
SELECT product_id, carbon_footprint, AVG(carbon_footprint) OVER (ORDER BY product_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as running_avg_cf FROM sustainability_metrics;
List the total number of calls for each call type in the 'search_and_rescue' table.
CREATE TABLE search_and_rescue (id INT,call_type VARCHAR(20),call_date TIMESTAMP); INSERT INTO search_and_rescue VALUES (1,'search','2022-01-01 17:00:00'),(2,'rescue','2022-01-02 18:00:00');
SELECT call_type, COUNT(*) FROM search_and_rescue GROUP BY call_type;
What are the different types of emergency calls and their average response times?
CREATE TABLE emergency_calls (call_id INT,call_date DATE,call_type VARCHAR(255),response_time INT); INSERT INTO emergency_calls (call_id,call_date,call_type,response_time) VALUES (1,'2021-01-01','Medical',10),(2,'2021-02-03','Fire',15);
SELECT call_type, AVG(response_time) FROM emergency_calls GROUP BY call_type;
What is the total number of community policing initiatives in the country?
CREATE TABLE community_policing (id INT,country VARCHAR(20),initiative VARCHAR(50)); INSERT INTO community_policing (id,country,initiative) VALUES (1,'USA','Neighborhood Watch'),(2,'Canada','Coffee with a Cop'),(3,'USA','Citizens Police Academy');
SELECT COUNT(*) FROM community_policing WHERE country = 'USA';
What is the total number of emergency incidents in the city of Oakland?
CREATE TABLE emergency_incidents (id INT,city VARCHAR(20),type VARCHAR(20),date DATE); INSERT INTO emergency_incidents (id,city,type,date) VALUES (1,'Oakland','Fire','2021-01-01'); INSERT INTO emergency_incidents (id,city,type,date) VALUES (2,'Oakland','Medical','2021-01-02');
SELECT COUNT(*) FROM emergency_incidents WHERE city = 'Oakland';
What is the maximum value of investments in the US stock market?
CREATE TABLE Investments (CustomerID INT,Market VARCHAR(20),Value DECIMAL(10,2)); INSERT INTO Investments (CustomerID,Market,Value) VALUES (1,'US',5000); INSERT INTO Investments (CustomerID,Market,Value) VALUES (2,'US',7000);
SELECT MAX(Value) FROM Investments WHERE Market = 'US'
What is the minimum and maximum age of customers from Japan?
CREATE TABLE customers (id INT,name TEXT,age INT,country TEXT,assets FLOAT); INSERT INTO customers (id,name,age,country,assets) VALUES (1,'John Doe',45,'USA',250000.00); INSERT INTO customers (id,name,age,country,assets) VALUES (2,'Jane Smith',34,'Canada',320000.00); INSERT INTO customers (id,name,age,country,assets) VALUES (3,'Alice Johnson',29,'UK',450000.00); INSERT INTO customers (id,name,age,country,assets) VALUES (4,'Bob Brown',51,'UK',150000.00); INSERT INTO customers (id,name,age,country,assets) VALUES (5,'Charlie Davis',48,'USA',800000.00); INSERT INTO customers (id,name,age,country,assets) VALUES (6,'David Kim',38,'Singapore',520000.00); INSERT INTO customers (id,name,age,country,assets) VALUES (7,'Hiroshi Tanaka',35,'Japan',300000.00); INSERT INTO customers (id,name,age,country,assets) VALUES (8,'Kim Lee',42,'Japan',600000.00);
SELECT MIN(age), MAX(age) FROM customers WHERE country = 'Japan';
List all the employees in the 'Quality Control' department
CREATE TABLE Employee (EmployeeID INT PRIMARY KEY,FirstName VARCHAR(50),LastName VARCHAR(50),Position VARCHAR(50),Department VARCHAR(50),Salary DECIMAL(10,2)); INSERT INTO Employee (EmployeeID,FirstName,LastName,Position,Department,Salary) VALUES (1,'John','Doe','Quality Engineer','Quality Control',50000.00),(2,'Jane','Doe','Quality Technician','Quality Control',40000.00);
SELECT * FROM Employee WHERE Department = 'Quality Control';
What is the average age of patients who visited a hospital in rural areas of Louisiana in 2021?
CREATE TABLE hospital_visits (visit_id INT,patient_id INT,visit_date DATE,location VARCHAR(20)); INSERT INTO hospital_visits (visit_id,patient_id,visit_date,location) VALUES (1,45,'2021-01-01','Rural Louisiana');
SELECT AVG(age) FROM (SELECT patient_id, age FROM patients JOIN hospital_visits ON patients.patient_id = hospital_visits.patient_id WHERE hospital_visits.location = 'Rural Louisiana' AND EXTRACT(YEAR FROM hospital_visits.visit_date) = 2021) AS subquery;
Calculate the moving average of cybersecurity incidents for the last 3 quarters, per region.
CREATE TABLE incident_data (region_id INT,incident_quarter INT,incident_count INT); INSERT INTO incident_data (region_id,incident_quarter,incident_count) VALUES (1,1,50),(1,2,75),(1,3,60),(1,4,80),(2,1,30),(2,2,40),(2,3,60),(2,4,70);
SELECT region_id, incident_quarter, AVG(incident_count) OVER (PARTITION BY region_id ORDER BY incident_quarter ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as moving_avg FROM incident_data;
List all national security advisors in the advisors table who have a security clearance level of "Top Secret".
CREATE TABLE advisors (name TEXT,agency TEXT,clearance TEXT); INSERT INTO advisors (name,agency,clearance) VALUES ('John Smith','CIA','Top Secret'),('Jane Doe','FBI','Secret'),('Jim Brown','NSA','Top Secret');
SELECT name FROM advisors WHERE clearance = 'Top Secret';
What are the names of military aircrafts manufactured in the USA after 2000?
CREATE TABLE MilitaryAircrafts (ID INT,Name TEXT,ManufacturingDate DATE,Country TEXT); INSERT INTO MilitaryAircrafts (ID,Name,ManufacturingDate,Country) VALUES (1,'F-35 Lightning II','2006-01-01','USA'),(2,'F-22 Raptor','2005-01-01','USA');
SELECT Name FROM MilitaryAircrafts WHERE ManufacturingDate >= '2000-01-01' AND Country = 'USA';
What is the total budget spent on each program category in H1 2022?
CREATE TABLE Programs (ProgramID int,ProgramName varchar(50),ProgramCategory varchar(50),Budget decimal(10,2),Spent decimal(10,2));
SELECT ProgramCategory, SUM(Spent) as TotalSpent FROM Programs WHERE YEAR(ProgramStartDate) = 2022 AND QUARTER(ProgramStartDate) <= 2 GROUP BY ProgramCategory;
What is the number of teachers who have completed professional development courses in the past year, broken down by their teaching subject?
CREATE TABLE teachers (teacher_id INT,subject VARCHAR(255),professional_development_course_completion_date DATE); INSERT INTO teachers (teacher_id,subject,professional_development_course_completion_date) VALUES (1,'Mathematics','2022-01-01'),(2,'Science','2021-12-15'),(3,'English','2022-03-05');
SELECT subject, COUNT(*) as number_of_teachers FROM teachers WHERE professional_development_course_completion_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY subject;
How many employees have been hired in the HR department in the last 6 months?
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),HireDate DATE); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,HireDate) VALUES (1,'John','Doe','HR','2021-06-15'); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,HireDate) VALUES (2,'Jane','Smith','IT','2021-01-05'); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,HireDate) VALUES (3,'Mike','Johnson','HR','2020-12-10'); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,HireDate) VALUES (4,'Alice','Williams','HR','2022-02-20');
SELECT COUNT(*) FROM Employees WHERE Department = 'HR' AND HireDate >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
What is the average energy efficiency rating for residential buildings in India?
CREATE TABLE energy_efficiency (id INT PRIMARY KEY,building_type VARCHAR(50),efficiency_rating FLOAT,country VARCHAR(50)); INSERT INTO energy_efficiency (id,building_type,efficiency_rating,country) VALUES (1,'Residential',70.0,'India'),(2,'Commercial',75.0,'India');
SELECT AVG(efficiency_rating) FROM energy_efficiency WHERE building_type = 'Residential' AND country = 'India';
What is the average age of female athletes in the 'basketball_players' table?
CREATE TABLE basketball_players (id INT,name VARCHAR(50),position VARCHAR(50),age INT,team VARCHAR(50)); INSERT INTO basketball_players (id,name,position,age,team) VALUES (1,'Alice Johnson','Guard',25,'Lakers'); INSERT INTO basketball_players (id,name,position,age,team) VALUES (2,'Bella Smith','Forward',28,'Celtics');
SELECT AVG(age) FROM basketball_players WHERE gender = 'female';
Delete the shelter with ID '2' from the 'shelters' table
CREATE TABLE shelters (shelter_id INT,shelter_name VARCHAR(30),region_id INT); INSERT INTO shelters (shelter_id,shelter_name,region_id) VALUES (1,'Emergency Shelter 1',3),(2,'Temporary Home',3),(3,'Relief House',1),(4,'New Shelter Name',4);
DELETE FROM shelters WHERE shelter_id = 2;
What is the total amount donated to each disaster type in the last 3 months?
CREATE TABLE donations (id INT PRIMARY KEY,donor_name VARCHAR(50),disaster_type VARCHAR(50),donation_date DATE,donation_amount DECIMAL(10,2)); INSERT INTO donations (id,donor_name,disaster_type,donation_date,donation_amount) VALUES (1,'John Doe','Earthquake','2022-01-01',100.00),(2,'Jane Smith','Flood','2022-02-01',200.00),(3,'Mike Johnson','Tornado','2021-12-31',50.00);
SELECT disaster_type, SUM(donation_amount) as total_donations FROM donations WHERE donation_date >= DATE_SUB(NOW(), INTERVAL 3 MONTH) GROUP BY disaster_type;
What is the average fare for each train route?
CREATE TABLE train_routes (route_id INT,route_name TEXT,starting_point TEXT,ending_point TEXT); CREATE TABLE train_fares (fare_id INT,route_id INT,fare_amount DECIMAL);
SELECT tr.route_name, AVG(tf.fare_amount) as avg_fare FROM train_routes tr INNER JOIN train_fares tf ON tr.route_id = tf.route_id GROUP BY tr.route_name;
How many posts were shared on Twitter in June 2021 by users in the 'brand' category?
CREATE TABLE posts (post_id INT,user_id INT,platform VARCHAR(255),post_date DATE); INSERT INTO posts (post_id,user_id,platform,post_date) VALUES (1,1,'Twitter','2021-06-01'),(2,2,'Instagram','2021-06-03'),(3,3,'Twitter','2021-06-05');
SELECT COUNT(*) FROM posts WHERE platform = 'Twitter' AND MONTH(post_date) = 6 AND YEAR(post_date) = 2021 AND user_id IN (SELECT user_id FROM users WHERE category = 'brand');
What is the average number of likes received by posts in the last month, for users who have posted more than once in that timeframe?
CREATE TABLE posts (id INT,user_id INT,timestamp DATETIME,likes INT); INSERT INTO posts (id,user_id,timestamp,likes) VALUES (1,1,'2022-01-01 10:00:00',10),(2,1,'2022-01-02 11:00:00',5),(3,2,'2022-01-03 12:00:00',15);
SELECT AVG(posts.likes) as avg_likes FROM posts WHERE posts.user_id IN (SELECT user_id FROM posts GROUP BY user_id HAVING COUNT(*) > 1) AND posts.timestamp >= DATE_SUB(NOW(), INTERVAL 1 MONTH);
What is the most common hashtag used in posts made by users from Brazil?
CREATE TABLE posts (id INT,user_id INT,content TEXT,hashtags TEXT,post_date DATE); INSERT INTO posts (id,user_id,content,hashtags,post_date) VALUES (1,1,'Hello World','#datascience','2022-06-01'),(2,1,'I love data','#ai','2022-06-02'),(3,2,'Olá Mundo','#brasil','2022-06-03'); CREATE TABLE users (id INT,name VARCHAR(100),country VARCHAR(50)); INSERT INTO users (id,name,country) VALUES (1,'João Silva','Brazil'),(2,'Maria Souza','Brazil');
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(hashtags, ' ', n.n), ' ', -1) hashtag, COUNT(*) count FROM posts JOIN users ON posts.user_id = users.id CROSS JOIN (SELECT 1 n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) n WHERE users.country = 'Brazil' GROUP BY hashtag ORDER BY count DESC LIMIT 1;
How many financial capability training sessions were conducted in Germany in Q1 of 2022?
CREATE TABLE financial_capability_training (id INT,quarter INT,year INT,country VARCHAR(255),sessions INT); INSERT INTO financial_capability_training (id,quarter,year,country,sessions) VALUES (1,1,2022,'Germany',25),(2,1,2022,'Germany',30);
SELECT COUNT(*) FROM financial_capability_training WHERE quarter = 1 AND year = 2022 AND country = 'Germany';
Update the calorie count of the dish 'Pão de Queijo' in Brazil to 350.
CREATE TABLE dishes (id INT,name TEXT,cuisine TEXT,calorie_count INT,country TEXT); INSERT INTO dishes (id,name,cuisine,calorie_count,country) VALUES (1,'Pão de Queijo','Brazilian',300,'Brazil'); INSERT INTO dishes (id,name,cuisine,calorie_count,country) VALUES (2,'Feijoada','Brazilian',800,'Brazil');
UPDATE dishes SET calorie_count = 350 WHERE name = 'Pão de Queijo' AND country = 'Brazil';
Calculate the average expression level of the top 5 genes in the cardiovascular system.
CREATE SCHEMA if not exists genetic;CREATE TABLE if not exists genetic.gene_expression (id INT,gene_id INT,gene_name TEXT,tissue TEXT,expression DECIMAL(5,2));INSERT INTO genetic.gene_expression (id,gene_id,gene_name,tissue,expression) VALUES (1,1,'Gene1','Cardiovascular',9.87),(2,2,'Gene2','Nervous',7.34),(3,3,'Gene3','Cardiovascular',10.12),(4,4,'GeneX','Nervous',6.55),(5,5,'GeneX','Cardiovascular',8.21);
SELECT AVG(expression) FROM (SELECT expression FROM genetic.gene_expression WHERE tissue = 'Cardiovascular' ORDER BY expression DESC LIMIT 5);
What is the average energy output for wind projects?
CREATE TABLE renewable_energy (id INT,project_id INT,energy_type VARCHAR(50),energy_output FLOAT); INSERT INTO renewable_energy (id,project_id,energy_type,energy_output) VALUES (2,2,'Wind',1500000);
SELECT energy_type, AVG(energy_output) as avg_energy_output FROM renewable_energy WHERE energy_type = 'Wind' GROUP BY energy_type;
Calculate the percentage of health equity metrics met by each community health worker in the West region for 2020 and 2021.
CREATE TABLE health_equity_metrics_worker (id INT,worker_id INT,region VARCHAR(50),year INT,metric1 BOOLEAN,metric2 BOOLEAN,metric3 BOOLEAN); INSERT INTO health_equity_metrics_worker (id,worker_id,region,year,metric1,metric2,metric3) VALUES (1,1,'West',2020,true,true,false),(2,2,'West',2020,true,false,true),(3,3,'West',2020,false,true,true),(4,1,'West',2021,true,true,true),(5,2,'West',2021,true,true,false),(6,3,'West',2021,true,false,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_worker WHERE region = 'West' AND year IN (2020, 2021) GROUP BY worker_id;
What is the average virtual tour rating for Southeast Asia in Q2 2022?
CREATE TABLE virtual_tours (country VARCHAR(255),quarter VARCHAR(10),rating FLOAT); INSERT INTO virtual_tours (country,quarter,rating) VALUES ('Indonesia','Q2',4.5),('Malaysia','Q2',4.6),('Thailand','Q2',4.7);
SELECT AVG(rating) FROM virtual_tours WHERE country IN ('Indonesia', 'Malaysia', 'Thailand') AND quarter = 'Q2';
What is the maximum revenue generated by a single sustainable tour in Japan?
CREATE TABLE sustainable_tours (id INT,country VARCHAR(20),revenue FLOAT); INSERT INTO sustainable_tours (id,country,revenue) VALUES (1,'Japan',2000.0),(2,'Japan',2500.0),(3,'Japan',3000.0);
SELECT MAX(revenue) FROM sustainable_tours WHERE country = 'Japan';
Find the number of modern art exhibitions held in France and Spain.
CREATE TABLE Exhibitions (id INT,title VARCHAR(50),location VARCHAR(50),movement VARCHAR(20));
SELECT COUNT(*) FROM Exhibitions WHERE (location = 'France' OR location = 'Spain') AND movement = 'Modern Art';
Delete the language preservation record for 'Vanuatu', 'Bislama', 'Vulnerable'.
CREATE TABLE LanguagePreservation (id INT,country VARCHAR(50),language VARCHAR(50),status VARCHAR(50)); INSERT INTO LanguagePreservation (id,country,language,status) VALUES (1,'Vanuatu','Bislama','Vulnerable'),(2,'Papua New Guinea','Tok Pisin','Endangered');
DELETE FROM LanguagePreservation WHERE id = 1;
What is the percentage of endangered languages in each continent, and the name of the most widely spoken endangered language in each continent?
CREATE TABLE Endangered_Languages_Continent (Language_Name VARCHAR(50),Continent VARCHAR(50),Number_Speakers INT); INSERT INTO Endangered_Languages_Continent (Language_Name,Continent,Number_Speakers) VALUES ('Quechua','South America',8000000),('Mapudungun','South America',200000);
SELECT Continent, AVG(Number_Speakers) AS Avg_Speakers, MIN(Language_Name) AS Most_Spoken FROM Endangered_Languages_Continent WHERE Continent IN ('South America') GROUP BY Continent;
How many defendants were represented by public defenders in New York City in 2020?
CREATE TABLE court_cases (case_id INT,defendant_id INT,defender_type VARCHAR(10),court_date DATE); INSERT INTO court_cases (case_id,defendant_id,defender_type,court_date) VALUES (1,1001,'Public Defender','2020-02-01'),(2,1002,'Private Attorney','2019-03-15');
SELECT COUNT(*) FROM court_cases WHERE defender_type = 'Public Defender' AND YEAR(court_date) = 2020 AND city(court_date) = 'New York';
What is the number of legal aid clinics in each province or territory in Canada, and how many clients do they serve on average?
CREATE TABLE canada_legal_aid(id INT,province_territory VARCHAR(255),clients_served INT);
SELECT province_territory, AVG(clients_served) AS average_clients_served FROM canada_legal_aid GROUP BY province_territory;
Delete records with sales amount over $50,000 in the MilitaryEquipmentSales table
CREATE TABLE MilitaryEquipmentSales (id INT,equipment_name VARCHAR(50),sale_amount INT,sale_date DATE); INSERT INTO MilitaryEquipmentSales (id,equipment_name,sale_amount,sale_date) VALUES (1,'Fighter Jet',45000,'2021-01-01'),(2,'Tank',75000,'2021-02-01');
DELETE FROM MilitaryEquipmentSales WHERE sale_amount > 50000;
What is the total production of iron mines in Russia?
CREATE TABLE mine (id INT,name TEXT,location TEXT,mineral TEXT,production INT); INSERT INTO mine (id,name,location,mineral,production) VALUES (1,'Mikhailovsky GOK','Russia','Iron',12000),(2,'Lebedinsky GOK','Russia','Iron',15000);
SELECT SUM(production) FROM mine WHERE mineral = 'Iron' AND location = 'Russia';
Which mining operations have a higher than average monthly CO2 emission?
CREATE TABLE co2_emissions (mine_id INT,emission_date DATE,co2_amount INT); INSERT INTO co2_emissions (mine_id,emission_date,co2_amount) VALUES (1,'2021-01-01',30000),(1,'2021-02-01',32000),(1,'2021-03-01',35000),(2,'2021-01-01',28000),(2,'2021-02-01',30000),(2,'2021-03-01',33000),(3,'2021-01-01',25000),(3,'2021-02-01',27000),(3,'2021-03-01',29000); CREATE TABLE mine_info (mine_id INT,mine_name TEXT); INSERT INTO mine_info (mine_id,mine_name) VALUES (1,'Golden Mine'),(2,'Silver Mine'),(3,'Bronze Mine');
SELECT mine_name, AVG(co2_amount) AS avg_monthly_emission FROM co2_emissions JOIN mine_info ON co2_emissions.mine_id = mine_info.mine_id GROUP BY mine_id HAVING AVG(co2_amount) > (SELECT AVG(co2_amount) FROM co2_emissions);
Find the number of unique authors who have contributed to each news source in the western region.
CREATE SCHEMA news;CREATE TABLE NewsSource (name varchar(255),author varchar(255));CREATE TABLE Region (name varchar(255),location varchar(10));INSERT INTO NewsSource (name,author) VALUES ('NewsSource1','Author1'),('NewsSource1','Author2'),('NewsSource2','Author3'),('NewsSource2','Author4'),('NewsSource3','Author5');INSERT INTO Region (name,location) VALUES ('NewsSource1','western'),('NewsSource2','western'),('NewsSource3','eastern');
SELECT NewsSource.name, COUNT(DISTINCT NewsSource.author) AS unique_authors FROM news.NewsSource INNER JOIN news.Region ON NewsSource.name = Region.name WHERE Region.location = 'western' GROUP BY NewsSource.name