instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total biomass of fish in the ocean by region and month?
CREATE TABLE Region (RegionID INT,RegionName TEXT); CREATE TABLE Fish (FishID INT,RegionID INT,BirthDate DATE,Weight DECIMAL); INSERT INTO Region VALUES (1,'North'); INSERT INTO Region VALUES (2,'South'); INSERT INTO Fish VALUES (1,1,'2021-01-01',5.0); INSERT INTO Fish VALUES (2,1,'2021-02-01',6.0); INSERT INTO Fish VALUES (3,2,'2021-03-01',7.0);
SELECT RegionName, EXTRACT(MONTH FROM BirthDate) AS Month, SUM(Weight) AS TotalBiomass FROM Region INNER JOIN Fish ON Region.RegionID = Fish.RegionID GROUP BY RegionName, Month;
What is the mortality rate of fish per day for each species at Farm F?
CREATE TABLE aquafarms (id INT,name TEXT); INSERT INTO aquafarms (id,name) VALUES (1,'Farm A'),(2,'Farm B'),(3,'Farm C'),(6,'Farm F'); CREATE TABLE mortality_data (aquafarm_id INT,species TEXT,mortality_quantity INT,timestamp TIMESTAMP);
SELECT species, DATE(timestamp) AS date, AVG(mortality_quantity) AS avg_mortality_rate FROM mortality_data JOIN aquafarms ON mortality_data.aquafarm_id = aquafarms.id WHERE aquafarm_id = 6 GROUP BY species, date;
Determine the percentage of workers who are female in each department
CREATE TABLE workers_gender_dept (id INT,name VARCHAR(50),department VARCHAR(50),gender VARCHAR(50)); INSERT INTO workers_gender_dept (id,name,department,gender) VALUES (1,'John Doe','manufacturing','male'),(2,'Jane Smith','engineering','female'),(3,'Alice Johnson','engineering','female'),(4,'Bob Brown','manufacturing','male'),(5,'Charlie Green','manufacturing','non-binary');
SELECT department, (COUNT(*) FILTER (WHERE gender = 'female') * 100.0 / COUNT(*)) as female_percentage FROM workers_gender_dept GROUP BY department;
Delete all records from the 'water_usage' table where the 'region' is 'Northeast'
CREATE TABLE water_usage (id INT PRIMARY KEY,region VARCHAR(20),usage INT);
DELETE FROM water_usage WHERE region = 'Northeast';
How many female readers are there in 'readers' table?
CREATE TABLE readers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),country VARCHAR(50));
SELECT COUNT(*) FROM readers WHERE gender = 'female';
How many students were enrolled in each school at the end of the last month?
CREATE TABLE student_enrollment (student_id INT,school_id INT,enrollment_date DATE);
SELECT school_id, COUNT(student_id) FROM student_enrollment WHERE enrollment_date < DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND school_id IS NOT NULL GROUP BY school_id;
What is the percentage of cases won by attorneys who have a last name starting with the letter 'S'?
CREATE TABLE attorneys (attorney_id INT,name VARCHAR(50),last_name VARCHAR(20)); INSERT INTO attorneys (attorney_id,name,last_name) VALUES (1,'Jane Smith','Smith'),(2,'Michael Johnson','Johnson'); CREATE TABLE cases (case_id INT,attorney_id INT,case_outcome VARCHAR(10)); INSERT INTO cases (case_id,attorney_id,case_outcome) VALUES (1,1,'Won'),(2,1,'Won'),(3,2,'Lost');
SELECT 100.0 * COUNT(*) / (SELECT COUNT(*) FROM cases) FROM cases JOIN attorneys ON cases.attorney_id = attorneys.attorney_id WHERE attorneys.last_name LIKE 'S%' AND cases.case_outcome = 'Won';
Identify the top 5 most frequently accessed bus stops along a route (route_id 104)?
CREATE TABLE stop_sequence (stop_id INT,stop_sequence INT,route_id INT); INSERT INTO stop_sequence (stop_id,stop_sequence,route_id) VALUES (1001,1,104),(1002,2,104),(1003,3,104),(1004,4,104),(1005,5,104),(1006,6,104),(1007,7,104);
SELECT stop_sequence, stop_id, COUNT(*) as access_count FROM stop_sequence WHERE route_id = 104 GROUP BY stop_sequence ORDER BY access_count DESC LIMIT 5;
What is the total number of satellites launched by China and India between 2015 and 2022?
CREATE TABLE satellites_launch (satellite_id INT,launch_company VARCHAR(50),launch_year INT); INSERT INTO satellites_launch (satellite_id,launch_company,launch_year) VALUES (1,'China',2015),(2,'China',2017),(3,'India',2016),(4,'India',2020);
SELECT SUM(launch_company IN ('China', 'India')) FROM satellites_launch WHERE launch_year BETWEEN 2015 AND 2022;
What is the total budget for accessibility initiatives for the Deaf community in New York in the last 12 months?
CREATE TABLE accessibility_budget (id INT PRIMARY KEY,initiative VARCHAR(255),community VARCHAR(255),state VARCHAR(255),budget DECIMAL(10,2),date DATE);
SELECT SUM(budget) FROM accessibility_budget WHERE initiative = 'accessibility' AND community = 'Deaf' AND state = 'New York' AND date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH);
Delete policies that have been inactive for the last 6 months.
CREATE TABLE Policy (PolicyID INT,PolicyholderID INT,Product VARCHAR(10),LastActive DATE); INSERT INTO Policy (PolicyID,PolicyholderID,Product,LastActive) VALUES (1,1,'Auto','2022-01-01'),(2,2,'Home','2021-01-01'),(3,3,'Auto','2022-05-09'),(4,4,'Home','2021-04-04'),(5,5,'Auto','2021-12-12');
DELETE FROM Policy WHERE LastActive < DATEADD(MONTH, -6, GETDATE());
What is the total number of carbon offset initiatives in the 'carbon_offsets' table, by location?
CREATE TABLE if not exists carbon_offsets (initiative_id INT,initiative_name VARCHAR(255),location VARCHAR(255),offset_amount INT);
SELECT location, COUNT(*) as total_initiatives FROM carbon_offsets GROUP BY location;
What is the distribution of military technologies by country based on year?
CREATE TABLE MilitaryTech (id INT,name VARCHAR(255),type VARCHAR(255),country VARCHAR(255),year INT); INSERT INTO MilitaryTech (id,name,type,country,year) VALUES (1,'F-15','Fighter','USA',1976),(2,'MiG-29','Fighter','Russia',1982);
SELECT country, type, year, NTILE(3) OVER(ORDER BY year) as tercile FROM MilitaryTech;
Which smart contract has the highest total transaction amount, partitioned by day?
CREATE TABLE smart_contracts (smart_contract_id INT,digital_asset VARCHAR(20),smart_contract_name VARCHAR(30),transaction_amount DECIMAL(10,2),transaction_time DATETIME);
SELECT smart_contract_name, SUM(transaction_amount) as total_transaction_amount, DATE_TRUNC('day', transaction_time) as day FROM smart_contracts GROUP BY smart_contract_name, day ORDER BY total_transaction_amount DESC;
What is the number of accommodations provided per disability type, ordered by the most accommodated?
CREATE TABLE AccommodationsByDisability (AccommodationID INT,AccommodationName VARCHAR(50),DisabilityType VARCHAR(50),Number INT); INSERT INTO AccommodationsByDisability (AccommodationID,AccommodationName,DisabilityType,Number) VALUES (1,'Sign Language Interpretation','Hearing Loss',500),(2,'Wheelchair Access','Physical Disability',700),(3,'Braille Materials','Visual Impairment',350),(4,'Adaptive Equipment','Physical Disability',600),(5,'Assistive Technology','Intellectual Disability',400),(6,'Sensory Rooms','Autism Spectrum Disorder',300);
SELECT DisabilityType, SUM(Number) as TotalAccommodations, ROW_NUMBER() OVER (ORDER BY SUM(Number) DESC) as Rank FROM AccommodationsByDisability GROUP BY DisabilityType;
What is the maximum amount of chemical waste produced daily by chemical plants in Canada, grouped by province?
CREATE TABLE chemical_waste (plant_id INT,plant_name TEXT,location TEXT,daily_waste_amount FLOAT); INSERT INTO chemical_waste (plant_id,plant_name,location,daily_waste_amount) VALUES (1,'Plant F','CA-ON',12.3),(2,'Plant G','CA-QC',15.5),(3,'Plant H','CA-BC',10.8),(4,'Plant I','US-NY',14.2),(5,'Plant J','MX-MX',8.9);
SELECT location, MAX(daily_waste_amount) as max_daily_waste_amount FROM chemical_waste WHERE location LIKE 'CA-%' GROUP BY location;
Delete products with both fragrance-free and vegan labels.
CREATE TABLE labels (id INT,product VARCHAR(255),is_fragrance_free BOOLEAN,is_vegan BOOLEAN); INSERT INTO labels (id,product,is_fragrance_free,is_vegan) VALUES (1,'Lotion',true,true),(2,'Shampoo',false,false),(3,'Conditioner',true,true),(4,'Body Wash',false,false),(5,'Deodorant',true,false);
DELETE FROM labels WHERE is_fragrance_free = true AND is_vegan = true;
What are the details of students who have not completed their mandatory mental health training in the last year?
CREATE TABLE students (id INT,name VARCHAR(255)); CREATE TABLE mental_health_training (id INT,student_id INT,completed_date DATE); INSERT INTO students (id,name) VALUES (1,'Student G'),(2,'Student H'),(3,'Student I'); INSERT INTO mental_health_training (id,student_id,completed_date) VALUES (1,1,'2021-06-01'),(2,2,NULL),(3,3,'2020-12-15');
SELECT s.name, m.completed_date FROM students s LEFT JOIN mental_health_training m ON s.id = m.student_id WHERE m.completed_date IS NULL AND m.completed_date < DATEADD(year, -1, GETDATE());
What is the average number of followers for users in a given age range?
CREATE TABLE users (id INT,age INT,country VARCHAR(255),followers INT); INSERT INTO users (id,age,country,followers) VALUES (1,25,'Italy',500),(2,30,'Nigeria',600),(3,35,'Argentina',700),(4,40,'Poland',800);
SELECT AVG(followers) FROM users WHERE age BETWEEN 25 AND 35;
What is the total number of fire incidents in February 2022?
CREATE TABLE fire_incidents (id INT,incident_date DATE,response_time INT); INSERT INTO fire_incidents (id,incident_date,response_time) VALUES (1,'2022-02-01',20),(2,'2022-02-02',25),(3,'2022-02-03',30);
SELECT COUNT(*) FROM fire_incidents WHERE incident_date BETWEEN '2022-02-01' AND '2022-02-28';
What is the minimum and maximum distance from shore for vessels in the Pacific Ocean, grouped by vessel type?
CREATE TABLE vessels (id INT,name TEXT,type TEXT,gps_position TEXT); CREATE TABLE gps_positions (id INT,latitude FLOAT,longitude FLOAT,country TEXT,distance_from_shore FLOAT);
SELECT v.type, MIN(g.distance_from_shore), MAX(g.distance_from_shore) FROM vessels v JOIN gps_positions g ON v.gps_position = g.id WHERE g.country = 'Pacific Ocean' GROUP BY v.type;
Find the number of coal and gold mining operations in Zimbabwe?
CREATE TABLE mining_operations (id INT,name VARCHAR(50),type VARCHAR(20),location VARCHAR(50)); INSERT INTO mining_operations (id,name,type,location) VALUES (1,'Mining Operation 1','Coal','Zimbabwe'),(2,'Mining Operation 2','Gold','Zimbabwe');
SELECT type, COUNT(*) FROM mining_operations WHERE location = 'Zimbabwe' GROUP BY type;
What is the average financial wellbeing score of clients in the age group 25-34 who have taken socially responsible loans?
CREATE TABLE clients (id INT,age INT,financial_wellbeing_score INT); CREATE TABLE loans (id INT,client_id INT,is_socially_responsible BOOLEAN); INSERT INTO clients (id,age,financial_wellbeing_score) VALUES (1,27,7),(2,35,8),(3,23,6),(4,31,9),(5,45,10); INSERT INTO loans (id,client_id,is_socially_responsible) VALUES (1,1,true),(2,1,false),(3,2,true),(4,3,false),(5,4,true),(6,5,true);
SELECT AVG(c.financial_wellbeing_score) as avg_score FROM clients c JOIN loans l ON c.id = l.client_id WHERE c.age BETWEEN 25 AND 34 AND l.is_socially_responsible = true;
List the names of all journalists who have never published a news story.
CREATE TABLE reporters (id INT,name VARCHAR(50),gender VARCHAR(10),age INT,country VARCHAR(50)); CREATE TABLE published_stories (reporter_id INT,news_id INT);
SELECT r.name FROM reporters r LEFT JOIN published_stories ps ON r.id = ps.reporter_id WHERE ps.news_id IS NULL;
What is the minimum donation amount given by individual donors in the 'education' sector?
CREATE TABLE donations (donation_id INT,donor_type TEXT,sector TEXT,donation_amount FLOAT); INSERT INTO donations (donation_id,donor_type,sector,donation_amount) VALUES (1,'individual','education',100.00),(2,'corporate','education',5000.00);
SELECT MIN(donation_amount) FROM donations WHERE donor_type = 'individual' AND sector = 'education';
Which movies had a production budget higher than the average marketing cost?
CREATE TABLE MovieData (id INT,title VARCHAR(100),budget FLOAT,marketing FLOAT);
SELECT title FROM MovieData WHERE budget > (SELECT AVG(marketing) FROM MovieData);
get the number of games won by the basketball team
CREATE TABLE games (id INT PRIMARY KEY,team VARCHAR(50),opponent VARCHAR(50),date DATE,result VARCHAR(10));
SELECT COUNT(*) FROM games WHERE team = 'Chicago Bulls' AND result = 'Win';
What is the average altitude of Boeing and Airbus aircrafts?
CREATE TABLE aircraft (maker TEXT,model TEXT,altitude INTEGER); INSERT INTO aircraft (maker,model,altitude) VALUES ('Boeing','747',35000),('Boeing','777',37000),('Airbus','A320',33000),('Airbus','A350',35000);
SELECT AVG(altitude) FROM aircraft WHERE maker IN ('Boeing', 'Airbus');
Find the average production rate of wells in the 'Baltic Sea' and the 'North Sea'.
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),region VARCHAR(50),production_rate FLOAT); INSERT INTO wells (well_id,well_name,region,production_rate) VALUES (9,'Well I','Baltic Sea',5000),(10,'Well J','North Sea',6000),(11,'Well K','Baltic Sea',8000),(12,'Well L','North Sea',9000);
SELECT AVG(production_rate) FROM wells WHERE region IN ('Baltic Sea', 'North Sea');
What are the research grant titles that do not have a corresponding publication?
CREATE TABLE grant (id INT,title VARCHAR(100)); CREATE TABLE publication (id INT,title VARCHAR(100),grant_id INT);
SELECT g.title FROM grant g LEFT JOIN publication p ON g.title = p.title WHERE p.id IS NULL;
What is the average ticket price for football matches in the EastCoast region?
CREATE TABLE Stadiums(id INT,name TEXT,location TEXT,sport TEXT,capacity INT); INSERT INTO Stadiums(id,name,location,sport,capacity) VALUES (1,'Fenway Park','Boston','Baseball',37755),(2,'MetLife Stadium','East Rutherford','Football',82500);
SELECT AVG(price) FROM TicketSales WHERE stadium_id IN (SELECT id FROM Stadiums WHERE location = 'EastCoast' AND sport = 'Football')
Who are the developers working on projects in the 'technology for social good' sector?
CREATE TABLE teams (team_id INT,name VARCHAR(50),sector VARCHAR(50)); INSERT INTO teams (team_id,name,sector) VALUES (1,'Tech4Good','technology for social good'); INSERT INTO teams (team_id,name,sector) VALUES (2,'Equalize','digital divide'); INSERT INTO teams (team_id,name,sector) VALUES (3,'Ethical AI','ethical AI');
SELECT developers.name FROM developers INNER JOIN teams ON developers.team_id = teams.team_id WHERE teams.sector = 'technology for social good';
Who is the governor in the state with the lowest average income?
CREATE TABLE State (id INT,name VARCHAR(50),avg_income FLOAT); INSERT INTO State (id,name,avg_income) VALUES (1,'StateA',40000); INSERT INTO State (id,name,avg_income) VALUES (2,'StateB',45000); INSERT INTO State (id,name,avg_income) VALUES (3,'StateC',35000);
SELECT State.name, GovernmentEmployee.name FROM State INNER JOIN GovernmentEmployee ON State.name = GovernmentEmployee.state_name WHERE State.avg_income = (SELECT MIN(avg_income) FROM State);
Which country has the highest average funding amount for women-led startups?
CREATE TABLE startups (id INT,name TEXT,location TEXT,founder_gender TEXT,funding_amount INT); INSERT INTO startups (id,name,location,founder_gender,funding_amount) VALUES (1,'Startup A','USA','female',5000000); INSERT INTO startups (id,name,location,founder_gender,funding_amount) VALUES (2,'Startup B','Canada','female',7000000);
SELECT location, AVG(funding_amount) as avg_funding FROM startups WHERE founder_gender = 'female' GROUP BY location ORDER BY avg_funding DESC LIMIT 1;
What is the minimum and maximum data allowance for broadband plans?
CREATE TABLE broadband_plans (plan_name TEXT,data_allowance INT);
SELECT MIN(data_allowance), MAX(data_allowance) FROM broadband_plans;
How many unique cities are represented in the International Arts Festival in 2023?
CREATE TABLE Attendees (id INT PRIMARY KEY,city VARCHAR(30),event VARCHAR(30),year INT); INSERT INTO Attendees (id,city,event,year) VALUES (1,'New York','International Arts Festival',2023); INSERT INTO Attendees (id,city,event,year) VALUES (2,'Toronto','International Arts Festival',2022);
SELECT COUNT(DISTINCT city) FROM Attendees WHERE event = 'International Arts Festival' AND year = 2023;
How many factories are in each country?
CREATE TABLE factories (factory_id INT,country VARCHAR(20)); INSERT INTO factories VALUES (1,'USA'),(2,'Canada'),(3,'Mexico'),(4,'USA'); CREATE TABLE countries (country_id INT,country VARCHAR(20)); INSERT INTO countries VALUES (1,'USA'),(2,'Canada'),(3,'Mexico');
SELECT f.country, COUNT(DISTINCT f.factory_id) FROM factories f INNER JOIN countries c ON f.country = c.country GROUP BY f.country;
How many local vendors have partnered with our virtual tourism platform in Latin America?
CREATE TABLE vendors (id INT,name VARCHAR(50),country VARCHAR(50),partnership BOOLEAN);
SELECT COUNT(*) FROM vendors WHERE vendors.partnership = TRUE AND vendors.country LIKE '%Latin America%';
What are the names of heritage dance programs in Indonesia with more than 1 associated event in the last year and an average attendance greater than 25?
CREATE TABLE HeritageDance (id INT,name VARCHAR(255),country VARCHAR(255),UNIQUE (id)); CREATE TABLE Events (id INT,name VARCHAR(255),heritage_dance_id INT,year INT,UNIQUE (id),FOREIGN KEY (heritage_dance_id) REFERENCES HeritageDance(id)); CREATE TABLE Attendance (id INT,event_id INT,attendees INT,UNIQUE (id),FOREIGN KEY (event_id) REFERENCES Events(id));
SELECT hd.name FROM HeritageDance hd JOIN Events e ON hd.id = e.heritage_dance_id JOIN Attendance a ON e.id = a.event_id WHERE hd.country = 'Indonesia' GROUP BY hd.name HAVING COUNT(DISTINCT e.id) > 1 AND AVG(a.attendees) > 25 AND e.year = 2022;
What is the total number of smart contracts deployed on the 'solana' network?
CREATE TABLE blockchain (id INT,network VARCHAR(20),tx_type VARCHAR(20),contract_count INT); INSERT INTO blockchain (id,network,tx_type,contract_count) VALUES (1,'solana','smart_contract',4000);
SELECT SUM(contract_count) FROM blockchain WHERE network = 'solana' AND tx_type = 'smart_contract';
Identify the top 3 countries with the highest total production of Gadolinium in 2021, and rank them.
CREATE TABLE Country (Code TEXT,Name TEXT,Continent TEXT); INSERT INTO Country (Code,Name,Continent) VALUES ('CN','China','Asia'),('AU','Australia','Australia'),('KR','South Korea','Asia'),('IN','India','Asia'); CREATE TABLE ProductionYearly (Year INT,Country TEXT,Element TEXT,Quantity INT); INSERT INTO ProductionYearly (Year,Country,Element,Quantity) VALUES (2021,'CN','Gadolinium',2000),(2021,'AU','Gadolinium',1800),(2021,'KR','Gadolinium',1500),(2021,'IN','Gadolinium',1900);
SELECT Country, SUM(Quantity) AS TotalProduction FROM ProductionYearly WHERE Element = 'Gadolinium' AND Year = 2021 GROUP BY Country ORDER BY TotalProduction DESC LIMIT 3;
What is the average number of matches won by players from the United States, for games that started in the last 30 days?
CREATE TABLE games (game_id INT,player_id INT,game_date DATE);CREATE TABLE players (player_id INT,player_country VARCHAR(255));
SELECT AVG(wins) FROM (SELECT COUNT(games.game_id) AS wins FROM games JOIN players ON games.player_id = players.player_id WHERE players.player_country = 'United States' AND games.game_date >= (CURRENT_DATE - INTERVAL '30' DAY) GROUP BY games.player_id) AS subquery;
What is the average time to repair military equipment, grouped by equipment type and manufacturer?
CREATE TABLE Equipment (id INT,name VARCHAR(100),manufacturer_id INT,repair_time DECIMAL(10,2));CREATE TABLE Manufacturers (id INT,name VARCHAR(100)); INSERT INTO Equipment (id,name,manufacturer_id,repair_time) VALUES (1,'Tank',1,10),(2,'Fighter Jet',2,15),(3,'Helicopter',2,20); INSERT INTO Manufacturers (id,name) VALUES (1,'Boeing'),(2,'Airbus');
SELECT m.name AS manufacturer, e.name AS equipment_type, AVG(e.repair_time) AS avg_repair_time FROM Equipment e JOIN Manufacturers m ON e.manufacturer_id = m.id GROUP BY m.name, e.name;
What is the total revenue for mobile and broadband plans combined in each region?
CREATE TABLE mobile_plans (id INT,name VARCHAR(255),type VARCHAR(255),price DECIMAL(10,2)); CREATE TABLE broadband_plans (id INT,name VARCHAR(255),type VARCHAR(255),price DECIMAL(10,2)); CREATE TABLE subscribers (id INT,name VARCHAR(255),plan_id INT,region VARCHAR(255)); CREATE TABLE regions (id INT,name VARCHAR(255));
SELECT regions.name AS region, SUM(mobile_plans.price + broadband_plans.price) FROM subscribers JOIN mobile_plans ON subscribers.plan_id = mobile_plans.id JOIN broadband_plans ON subscribers.plan_id = broadband_plans.id JOIN regions ON subscribers.region = regions.id GROUP BY regions.name;
Count the number of employees who are still working
CREATE TABLE Employees (id INT,name VARCHAR(50),position VARCHAR(50),left_company BOOLEAN);
SELECT COUNT(*) FROM Employees WHERE left_company = FALSE;
Identify the top 3 product categories with the highest percentage of products made from recycled materials, for each region.
CREATE TABLE products (id INT,name VARCHAR(50),category VARCHAR(50),made_from_recycled_materials BOOLEAN,region VARCHAR(50));
SELECT region, category, 100.0 * COUNT(*) / SUM(COUNT(*)) OVER (PARTITION BY region) as percentage FROM products WHERE made_from_recycled_materials = TRUE GROUP BY region, category ORDER BY region, percentage DESC LIMIT 3;
Show the monthly water consumption trend for the top 3 water consumers.
CREATE TABLE monthly_water_usage (state TEXT,year INT,month INT,water_usage FLOAT); INSERT INTO monthly_water_usage (state,year,month,water_usage) VALUES ('CA',2020,1,500000),('TX',2020,1,700000),('FL',2020,1,300000),('CA',2020,2,550000),('TX',2020,2,750000),('FL',2020,2,350000);
SELECT state, EXTRACT(MONTH FROM DATE '2020-01-01' + INTERVAL month MONTH) AS month, AVG(water_usage) AS avg_usage FROM monthly_water_usage WHERE state IN (SELECT state FROM monthly_water_usage GROUP BY state ORDER BY SUM(water_usage) DESC LIMIT 3) GROUP BY state, month ORDER BY state, month;
How many car insurance policies were sold in 'TX'?
CREATE TABLE policies (id INT,policy_type VARCHAR(10),state VARCHAR(2)); INSERT INTO policies (id,policy_type,state) VALUES (1,'car','NY'),(2,'home','CA'),(3,'car','TX');
SELECT COUNT(*) FROM policies WHERE policy_type = 'car' AND state = 'TX';
How many sales of vegan skincare products were made in the last month in the UK?
CREATE TABLE sales(product_name TEXT,is_vegan BOOLEAN,sale_date DATE); INSERT INTO sales VALUES ('Cleanser',true,'2022-03-01'); INSERT INTO sales VALUES ('Toner',false,'2022-03-05'); INSERT INTO sales VALUES ('Moisturizer',true,'2022-03-07');
SELECT COUNT(*) FROM sales WHERE is_vegan = true AND sale_date BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() AND country = 'UK';
Which virtual reality headset is most commonly used in esports events?
CREATE TABLE EsportsEvents (EventID INT,VRHeadset VARCHAR(20)); INSERT INTO EsportsEvents (EventID,VRHeadset) VALUES (1,'Oculus Rift');
SELECT VRHeadset, COUNT(*) FROM EsportsEvents GROUP BY VRHeadset ORDER BY COUNT(*) DESC LIMIT 1;
What is the total number of 'vegan' and 'vegetarian' meals in the 'menu' table?
CREATE TABLE menu (meal VARCHAR(255),diet VARCHAR(255)); INSERT INTO menu (meal,diet) VALUES ('Spaghetti Bolognese','Non-vegetarian'),('Vegetable Stir Fry','Vegetarian'),('Grilled Chicken Salad','Non-vegetarian'),('Tofu Scramble','Vegan');
SELECT COUNT(*) as total_vegan_vegetarian_meals FROM menu WHERE diet IN ('Vegan', 'Vegetarian');
What is the total length of all railroads in Canada and the United States?
CREATE TABLE railroads (id INT,country VARCHAR(255),total_length FLOAT); INSERT INTO railroads (id,country,total_length) VALUES (1,'Canada',48000),(2,'United States',246000);
SELECT SUM(total_length) FROM railroads WHERE country IN ('Canada', 'United States');
How many exoplanets have been discovered using the transit method?
CREATE TABLE exoplanets (id INT,name VARCHAR(255),discovery_date DATE,discovery_method VARCHAR(255));
SELECT COUNT(*) FROM exoplanets WHERE exoplanets.discovery_method = 'Transit';
Insert new records into the 'rural_health' table for a new health center in Bangladesh
CREATE TABLE rural_health (id INT,facility_name VARCHAR(255),country VARCHAR(255),sector VARCHAR(255));
INSERT INTO rural_health (id, facility_name, country, sector) VALUES (1, 'Health Center', 'Bangladesh', 'Health');
What is the average medical data record size for Chinese astronauts?
CREATE TABLE Astronaut_Medical_Data (id INT,astronaut_name VARCHAR(50),nationality VARCHAR(50),data_size INT); INSERT INTO Astronaut_Medical_Data (id,astronaut_name,nationality,data_size) VALUES (1,'Taylor Wang','China',1000);
SELECT AVG(data_size) FROM Astronaut_Medical_Data WHERE nationality = 'China';
What are the energy efficiency stats for each state and region?
CREATE TABLE regions (region_id INT,region_name VARCHAR(255)); CREATE TABLE states (state_id INT,state VARCHAR(255)); CREATE TABLE energy_efficiency (efficiency_id INT,state VARCHAR(255),region_id INT,energy_efficiency_score INT); INSERT INTO regions (region_id,region_name) VALUES (1,'West'); INSERT INTO states (state_id,state) VALUES (1,'California'); INSERT INTO energy_efficiency (efficiency_id,state,region_id,energy_efficiency_score) VALUES (1,'California',1,90);
SELECT s.state, r.region_name, ee.energy_efficiency_score FROM states s INNER JOIN energy_efficiency ee ON s.state = ee.state INNER JOIN regions r ON ee.region_id = r.region_id;
What is the percentage of peacekeeping operations led by countries in the European Union between 2015 and 2020?
CREATE TABLE PeacekeepingOperations (Year INT,Country VARCHAR(50),Operations INT); INSERT INTO PeacekeepingOperations (Year,Country,Operations) VALUES (2015,'France',12),(2015,'Germany',16),(2016,'France',14),(2016,'Germany',17);
SELECT Country, SUM(Operations) as Total_Operations, SUM(Operations)/(SELECT SUM(Operations) FROM PeacekeepingOperations WHERE Year BETWEEN 2015 AND 2020 AND Country IN ('France', 'Germany', 'Italy', 'Poland', 'Spain'))*100 as EU_Percentage FROM PeacekeepingOperations WHERE Year BETWEEN 2015 AND 2020 AND Country IN ('France', 'Germany', 'Italy', 'Poland', 'Spain') GROUP BY Country;
List the number of education projects funded by Oxfam in each country in 2013.
CREATE TABLE education_projects (funding_agency VARCHAR(255),country VARCHAR(255),project_type VARCHAR(255),year INT);
SELECT country, COUNT(*) FROM education_projects WHERE funding_agency = 'Oxfam' AND project_type = 'education' GROUP BY country;
Who are the top 10 users with the most followers in the "beauty" category as of January 1, 2023?
CREATE TABLE users (id INT,username VARCHAR(255),role VARCHAR(255),followers INT,created_at TIMESTAMP,category VARCHAR(255));
SELECT username FROM users WHERE category = 'beauty' ORDER BY followers DESC LIMIT 10;
What is the total number of military technologies, cybersecurity strategies, and intelligence operations in the 'military_tech', 'cybersecurity', and 'intelligence_ops' tables?
CREATE TABLE military_tech (code INT,name VARCHAR(50),type VARCHAR(50),manufacturer VARCHAR(50),last_updated TIMESTAMP); CREATE TABLE cybersecurity (strategy_id INT,strategy_name VARCHAR(50),description TEXT,last_updated TIMESTAMP); CREATE TABLE intelligence_ops (operation_id INT,name VARCHAR(50),description TEXT,start_date DATE,end_date DATE,last_updated TIMESTAMP);
SELECT COUNT(*) FROM military_tech; SELECT COUNT(*) FROM cybersecurity; SELECT COUNT(*) FROM intelligence_ops;
What is the total carbon offset of renewable energy projects in the state of California?
CREATE TABLE RenewableEnergyProjects (id INT,state VARCHAR(50),carbon_offsets INT); INSERT INTO RenewableEnergyProjects (id,state,carbon_offsets) VALUES (1,'California',10000),(2,'Texas',15000),(3,'California',12000);
SELECT SUM(carbon_offsets) as total_carbon_offsets FROM RenewableEnergyProjects WHERE state = 'California';
Who are the traditional instrument makers in Senegal?
CREATE TABLE instrument_makers (id INT PRIMARY KEY,name TEXT,instrument TEXT,country TEXT);
SELECT name FROM instrument_makers WHERE country = 'Senegal';
List all co-ownership agreements in the state of New York from 2015 that have a size greater than 2000 square feet.
CREATE TABLE CoOwnership (id INT,state VARCHAR(20),year INT,size INT,agreement TEXT);
SELECT agreement FROM CoOwnership WHERE state = 'New York' AND year = 2015 AND size > 2000;
What is the average salary of employees working in the marketing department?
CREATE TABLE employees (id INT,name VARCHAR(50),department VARCHAR(50),salary FLOAT); INSERT INTO employees (id,name,department,salary) VALUES (1,'John Doe','Marketing',50000.00),(2,'Jane Smith','Marketing',55000.00),(3,'Mike Johnson','IT',60000.00);
SELECT AVG(salary) FROM employees WHERE department = 'Marketing';
What is the average mental health score for students in each institution?
CREATE TABLE students (id INT,name VARCHAR(50),institution_id INT,mental_health_score INT); INSERT INTO students (id,name,institution_id,mental_health_score) VALUES (1,'Jane Smith',1,80),(2,'Jim Brown',2,70),(3,'Ava Johnson',1,85),(4,'Ben Wilson',2,75); CREATE TABLE institutions (id INT,name VARCHAR(50),type VARCHAR(20)) INSERT INTO institutions (id,name,type) VALUES (1,'Uni A','Public'),(2,'College B','Private');
SELECT i.name AS institution, AVG(s.mental_health_score) AS avg_score FROM students s JOIN institutions i ON s.institution_id = i.id GROUP BY i.name;
What is the latest launch date for a Mars rover mission, and which mission was it?
CREATE TABLE Rovers (RoverID INT,Name VARCHAR(50),LaunchDate DATE,Destination VARCHAR(50)); INSERT INTO Rovers VALUES (1,'Perseverance','2020-07-30','Mars'); INSERT INTO Rovers VALUES (2,'Curiosity','2011-11-26','Mars');
SELECT * FROM Rovers WHERE Destination = 'Mars' AND ROW_NUMBER() OVER (ORDER BY LaunchDate DESC) = 1
What's the name and network of the digital asset with the highest market capitalization?
CREATE TABLE digital_assets (id INT,name VARCHAR(255),network VARCHAR(255),market_cap DECIMAL(10,2)); INSERT INTO digital_assets (id,name,network,market_cap) VALUES (1,'Asset1','network1',500),(2,'Asset2','network2',600);
SELECT name, network FROM digital_assets WHERE market_cap = (SELECT MAX(market_cap) FROM digital_assets);
List all employees with their corresponding job position, salary, and department from the 'employee', 'position', and 'department' tables
CREATE TABLE employee (id INT,name VARCHAR(50),gender VARCHAR(50),department_id INT,position_id INT,salary INT); CREATE TABLE position (id INT,title VARCHAR(50),department_id INT); CREATE TABLE department (id INT,name VARCHAR(50));
SELECT employee.name, position.title, employee.salary, department.name AS department_name FROM employee INNER JOIN position ON employee.position_id = position.id INNER JOIN department ON position.department_id = department.id;
Count the number of renewable energy projects in the 'renewable_energy' schema.
CREATE TABLE renewable_energy (id INT,project_name VARCHAR(50),location VARCHAR(50),investment FLOAT); INSERT INTO renewable_energy (id,project_name,location,investment) VALUES (1,'Solar Farm','Arizona',12000000),(2,'Wind Turbines','Texas',8000000);
SELECT COUNT(*) FROM renewable_energy;
What was the number of sales of refillable makeup products in Germany in H2 2021?
CREATE TABLE makeup_products (product_refillable BOOLEAN,sale_date DATE,quantity INT,manufacturing_country VARCHAR(20)); INSERT INTO makeup_products (product_refillable,sale_date,quantity,manufacturing_country) VALUES (TRUE,'2021-07-01',75,'Germany'),(FALSE,'2021-07-02',100,'Spain');
SELECT SUM(quantity) FROM makeup_products WHERE product_refillable = TRUE AND manufacturing_country = 'Germany' AND sale_date BETWEEN '2021-07-01' AND '2021-12-31';
How many labor rights advocacy unions are there in the northern region?
CREATE TABLE regions (id INT,name VARCHAR(50),union_id INT); INSERT INTO regions (id,name,union_id) VALUES (1,'Northern',1),(2,'Southern',2),(3,'Eastern',3);
SELECT COUNT(*) FROM unions u INNER JOIN regions r ON u.id = r.union_id WHERE u.focus_area = 'labor rights' AND r.name = 'Northern';
Calculate the average price of all menu items in the Vegan category
CREATE TABLE Menu (id INT PRIMARY KEY,name VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2));
SELECT AVG(price) FROM Menu WHERE category = 'Vegan';
What are the top 3 selling items for each cuisine type?
CREATE TABLE orders(order_id INT,order_date DATE,menu_item_id INT,quantity INT); CREATE TABLE menu_items(menu_item_id INT,name TEXT,cuisine TEXT,price DECIMAL);
SELECT menu_items.cuisine, menu_items.name, SUM(orders.quantity) as total_sold FROM menu_items JOIN orders ON menu_items.menu_item_id = orders.menu_item_id GROUP BY menu_items.cuisine, menu_items.menu_item_id ORDER BY total_sold DESC LIMIT 3;
List the names of all cities that have never had a mayor from a historically underrepresented community?
CREATE TABLE city (id INT,name VARCHAR(255)); INSERT INTO city (id,name) VALUES (1,'New York'),(2,'Los Angeles'),(3,'Chicago'),(4,'Houston'),(5,'Phoenix'); CREATE TABLE mayor (id INT,city_id INT,name VARCHAR(255),community VARCHAR(255)); INSERT INTO mayor (id,city_id,name,community) VALUES (1,1,'John Smith','White'),(2,1,'James Johnson','African American'),(3,2,'Maria Rodriguez','Hispanic'),(4,3,'William Lee','Asian'),(5,4,'Robert Brown','White'),(6,5,'David Garcia','Hispanic');
SELECT c.name FROM city c WHERE c.id NOT IN (SELECT m.city_id FROM mayor m WHERE m.community != 'White')
Show number of labor disputes by union name
CREATE TABLE labor_disputes (id INT,union_name VARCHAR(50),dispute_date DATE,dispute_reason VARCHAR(50)); INSERT INTO labor_disputes (id,union_name,dispute_date,dispute_reason) VALUES (1,'United Steelworkers','2019-12-01','Wages'),(2,'Teamsters','2020-06-15','Benefits'),(3,'Service Employees International Union','2018-03-03','Working conditions');
SELECT union_name, COUNT(*) as total_disputes FROM labor_disputes GROUP BY union_name;
What is the average fuel consumption of bulk carriers in the past year?
CREATE TABLE vessel (id INT,type VARCHAR(50),name VARCHAR(50));CREATE TABLE fuel_consumption (vessel_id INT,consumption DECIMAL(10,2),consumption_date DATE);
SELECT AVG(fc.consumption) as avg_consumption FROM vessel v INNER JOIN fuel_consumption fc ON v.id = fc.vessel_id WHERE v.type = 'bulk carrier' AND fc.consumption_date >= DATE(NOW(), INTERVAL -1 YEAR);
What is the total revenue (in USD) generated from each fashion trend category?
CREATE TABLE revenue(category VARCHAR(50),amount FLOAT); INSERT INTO revenue(category,amount) VALUES('TrendA',1250.5),('TrendB',1500.7),('TrendC',1800.3);
SELECT category, SUM(amount) FROM revenue GROUP BY category;
How many males in Texas have been diagnosed with Hepatitis B?
CREATE TABLE Patients (ID INT,Gender VARCHAR(10),Disease VARCHAR(20),State VARCHAR(20)); INSERT INTO Patients (ID,Gender,Disease,State) VALUES (1,'Female','Tuberculosis','California'); INSERT INTO Patients (ID,Gender,Disease,State) VALUES (2,'Male','Hepatitis B','Texas');
SELECT COUNT(*) FROM Patients WHERE Gender = 'Male' AND Disease = 'Hepatitis B' AND State = 'Texas';
Which countries have emissions greater than 5 million in any year?
CREATE TABLE emissions (id INT PRIMARY KEY,country VARCHAR(50),year INT,emissions FLOAT); INSERT INTO emissions (id,country,year,emissions) VALUES (1,'US',2015,5500000.0); INSERT INTO emissions (id,country,year,emissions) VALUES (2,'China',2016,10000000.0);
SELECT country FROM emissions WHERE emissions > 5000000 GROUP BY country HAVING COUNT(*) > 0;
How many units of 'CBD Gummies' product were sold in 'Heavenly Hash' dispensary in January 2022?
CREATE TABLE products (product_id INT,name VARCHAR(255),category VARCHAR(255)); INSERT INTO products (product_id,name,category) VALUES (7,'CBD Gummies','Edibles'); CREATE TABLE dispensaries (dispensary_id INT,name VARCHAR(255)); INSERT INTO dispensaries (dispensary_id,name) VALUES (7,'Heavenly Hash'); CREATE TABLE sales (sale_id INT,product_id INT,dispensary_id INT,quantity INT,sale_date DATE); INSERT INTO sales (sale_id,product_id,dispensary_id,quantity,sale_date) VALUES (500,7,7,100,'2022-01-15');
SELECT SUM(quantity) FROM sales WHERE product_id = (SELECT product_id FROM products WHERE name = 'CBD Gummies') AND dispensary_id = (SELECT dispensary_id FROM dispensaries WHERE name = 'Heavenly Hash') AND sale_date BETWEEN '2022-01-01' AND '2022-01-31';
What is the total budget allocation for transportation for each province, in descending order?
CREATE TABLE provinces (province_name VARCHAR(50),budget_allocation INT); INSERT INTO provinces VALUES ('Ontario',12000000); INSERT INTO provinces VALUES ('Quebec',10000000); INSERT INTO provinces VALUES ('British Columbia',9000000);
SELECT province_name, SUM(budget_allocation) OVER (PARTITION BY province_name) as total_budget_allocation FROM provinces ORDER BY total_budget_allocation DESC;
How many public hospitals are there in each location type?
CREATE TABLE hospitals (name VARCHAR(50),type VARCHAR(50),beds INT,location VARCHAR(50)); INSERT INTO hospitals (name,type,beds,location) VALUES ('Hospital A','Public',300,'City'); INSERT INTO hospitals (name,type,beds,location) VALUES ('Hospital B','Private',200,'Suburban'); INSERT INTO hospitals (name,type,beds,location) VALUES ('Hospital C','Public',400,'Rural');
SELECT location, COUNT(*) as NumPublicHospitals FROM hospitals WHERE type = 'Public' GROUP BY location;
How many unique customers have purchased size-diverse clothing in each region?
CREATE TABLE Customers (CustomerID INT,CustomerName VARCHAR(50),Size VARCHAR(10),Region VARCHAR(50)); INSERT INTO Customers (CustomerID,CustomerName,Size,Region) VALUES (1,'CustomerA','XS','Northeast'),(2,'CustomerB','M','Northeast'),(3,'CustomerC','XL','Midwest'),(4,'CustomerD','S','South'),(5,'CustomerE','XXL','West');
SELECT Region, COUNT(DISTINCT CustomerID) as UniqueCustomers FROM Customers WHERE Size IN ('XS', 'S', 'M', 'L', 'XL', 'XXL') GROUP BY Region;
What is the total fare collected for each vehicle on April 20, 2022?
CREATE TABLE vehicles (vehicle_id INT,vehicle_registration TEXT);CREATE TABLE fares (fare_id INT,vehicle_id INT,fare_amount DECIMAL,fare_collection_date DATE); INSERT INTO vehicles (vehicle_id,vehicle_registration) VALUES (1001,'ABC-123'),(1002,'DEF-456'),(2001,'GHI-789'); INSERT INTO fares (fare_id,vehicle_id,fare_amount,fare_collection_date) VALUES (1,1001,5.00,'2022-04-20'),(2,1001,5.00,'2022-04-20'),(3,1002,3.50,'2022-04-20'),(4,1002,3.50,'2022-04-20'),(5,2001,7.00,'2022-04-20');
SELECT v.vehicle_registration, SUM(f.fare_amount) as total_fare FROM vehicles v JOIN fares f ON v.vehicle_id = f.vehicle_id WHERE f.fare_collection_date = '2022-04-20' GROUP BY v.vehicle_registration;
Which countries participated in 'ClinicalTrial789'?
CREATE TABLE clinical_trials (trial_id TEXT,country TEXT); INSERT INTO clinical_trials (trial_id,country) VALUES ('ClinicalTrial123','USA'),('ClinicalTrial123','Canada'),('ClinicalTrial456','Mexico'),('ClinicalTrial789','India'),('ClinicalTrial789','Nepal');
SELECT DISTINCT country FROM clinical_trials WHERE trial_id = 'ClinicalTrial789';
Identify the top 3 defense contractors with the highest veteran employment ratio and their respective ratios.
CREATE TABLE defense_contractors(contractor_id INT,contractor_name VARCHAR(50),num_veterans INT,total_employees INT); INSERT INTO defense_contractors(contractor_id,contractor_name,num_veterans,total_employees) VALUES (1,'Lockheed Martin',35000,100000),(2,'Boeing',28000,120000),(3,'Raytheon',22000,80000);
SELECT contractor_id, contractor_name, num_veterans * 1.0 / total_employees as veteran_ratio FROM defense_contractors ORDER BY veteran_ratio DESC LIMIT 3;
Identify the number of local jobs created by sustainable tourism in Canada and Australia.
CREATE TABLE SustainableTourism (TourismID int,Location varchar(50),JobsCreated int); INSERT INTO SustainableTourism (TourismID,Location,JobsCreated) VALUES (1,'Canada',2000); INSERT INTO SustainableTourism (TourismID,Location,JobsCreated) VALUES (2,'Australia',3000);
SELECT SUM(JobsCreated) FROM SustainableTourism WHERE Location IN ('Canada', 'Australia')
Display the concerts with a revenue greater than the average revenue of concerts in 'New York'.
CREATE TABLE Concerts (ConcertID INT,Artist VARCHAR(50),City VARCHAR(50),Revenue DECIMAL(10,2)); INSERT INTO Concerts (ConcertID,Artist,City,Revenue) VALUES (1,'Taylor Swift','Los Angeles',500000.00),(2,'BTS','New York',750000.00),(3,'Adele','London',600000.00),(4,'Taylor Swift','New York',350000.00);
SELECT * FROM Concerts WHERE City = 'New York' GROUP BY City; SELECT * FROM Concerts WHERE Revenue > (SELECT AVG(Revenue) FROM (SELECT Revenue FROM Concerts WHERE City = 'New York' GROUP BY City));
What is the total CO2 emissions for the 'Spring_2022' collection?
CREATE TABLE emissions (collection VARCHAR(10),co2_emissions FLOAT,units INT); INSERT INTO emissions (collection,co2_emissions,units) VALUES ('Spring_2022',10.5,1200),('Spring_2022',11.3,1300),('Spring_2022',12.1,1400);
SELECT SUM(co2_emissions) FROM emissions WHERE collection = 'Spring_2022';
Determine the change in eco-rating for each source country between 2021 and 2022.
CREATE TABLE source_countries_2021 (id INT,country VARCHAR(50),num_ecotourists INT,total_eco_rating INT,avg_eco_rating FLOAT); INSERT INTO source_countries_2021 (id,country,num_ecotourists,total_eco_rating,avg_eco_rating) VALUES (1,'United States',1800,13000,7.22),(2,'Australia',1200,9000,7.5),(3,'Canada',900,7500,8.33),(4,'United Kingdom',1500,13500,9); CREATE TABLE source_countries_2022 (id INT,country VARCHAR(50),num_ecotourists INT,total_eco_rating INT,avg_eco_rating FLOAT); INSERT INTO source_countries_2022 (id,country,num_ecotourists,total_eco_rating,avg_eco_rating) VALUES (1,'United States',2000,15000,7.5),(2,'Australia',1500,12000,8),(3,'Canada',1200,10000,8.33),(4,'United Kingdom',1800,18000,10); CREATE TABLE eco_ratings_history (id INT,source_country VARCHAR(50),eco_rating INT,year INT); INSERT INTO eco_ratings_history (id,source_country,eco_rating,year) VALUES (1,'United States',15,2021),(2,'United States',16,2022),(3,'Australia',13,2021),(4,'Australia',14,2022),(5,'Canada',10,2021),(6,'Canada',12,2022),(7,'United Kingdom',16,2021),(8,'United Kingdom',18,2022);
SELECT s2022.country, (s2022.avg_eco_rating - s2021.avg_eco_rating) AS eco_rating_change FROM source_countries_2022 s2022 JOIN source_countries_2021 s2021 ON s2022.country = s2021.country;
What is the average donation amount from donors in Japan in 2022?
CREATE TABLE donors (id INT,name TEXT,country TEXT,donation_amount DECIMAL,donation_year INT); INSERT INTO donors (id,name,country,donation_amount,donation_year) VALUES (1,'Hiroshi Tanaka','Japan',150.00,2022),(2,'Miyuki Sato','Japan',250.00,2021);
SELECT AVG(donation_amount) FROM donors WHERE country = 'Japan' AND donation_year = 2022;
What is the average data usage for each customer in the 'Residential' plan?
CREATE TABLE Customers (CustomerID INT,Plan VARCHAR(20)); INSERT INTO Customers (CustomerID,Plan) VALUES (1,'Residential'),(2,'Business'); CREATE TABLE DataUsage (CustomerID INT,Usage INT); INSERT INTO DataUsage (CustomerID,Usage) VALUES (1,5000),(2,8000);
SELECT c.Plan, AVG(du.Usage) as AvgDataUsage FROM Customers c JOIN DataUsage du ON c.CustomerID = du.CustomerID WHERE c.Plan = 'Residential' GROUP BY c.Plan;
What is the total quantity of sustainable fabrics used by each designer?
CREATE TABLE Designers (DesignerID INT,DesignerName VARCHAR(50),IsSustainableFabric BOOLEAN); INSERT INTO Designers (DesignerID,DesignerName,IsSustainableFabric) VALUES (1,'DesignerA',TRUE),(2,'DesignerB',FALSE); CREATE TABLE FabricUsage (DesignerID INT,Fabric VARCHAR(50),Quantity INT); INSERT INTO FabricUsage (DesignerID,Fabric,Quantity) VALUES (1,'Organic Cotton',500),(1,'Recycled Polyester',300),(2,'Conventional Cotton',700),(2,'Viscose',400);
SELECT d.DesignerName, SUM(fu.Quantity) as TotalSustainableQuantity FROM Designers d JOIN FabricUsage fu ON d.DesignerID = fu.DesignerID WHERE d.IsSustainableFabric = TRUE GROUP BY d.DesignerName;
Delete donors who have not donated more than $100 in total.
CREATE TABLE Donors (DonorID INT,DonorName TEXT,TotalDonation DECIMAL(10,2)); INSERT INTO Donors (DonorID,DonorName,TotalDonation) VALUES (1,'James Doe',50.00),(2,'Jane Smith',350.00),(3,'Mike Johnson',120.00),(4,'Sara Connor',75.00);
DELETE FROM Donors WHERE TotalDonation < 100;
Delete clients from Pakistan with a financial wellbeing score of NULL.
CREATE TABLE client (client_id INT,name TEXT,country TEXT,financial_wellbeing_score INT); INSERT INTO client (client_id,name,country,financial_wellbeing_score) VALUES (1,'John Doe','USA',70); INSERT INTO client (client_id,name,country,financial_wellbeing_score) VALUES (2,'Jane Smith','USA',75); INSERT INTO client (client_id,name,country,financial_wellbeing_score) VALUES (3,'Mohammad Ahmad','Pakistan',NULL); CREATE VIEW clients_with_null_scores AS SELECT * FROM client WHERE financial_wellbeing_score IS NULL;
DELETE FROM client WHERE client_id IN (SELECT client_id FROM clients_with_null_scores WHERE country = 'Pakistan');
What are the demographics of users who clicked on 'Instagram' or 'Snapchat' ads in the last week?
CREATE TABLE Instagram_Ads(id INT,user_id INT,ad_id INT,age INT,gender TEXT); CREATE TABLE Snapchat_Ads(id INT,user_id INT,ad_id INT,age INT,gender TEXT);
SELECT 'Instagram' AS platform, age, gender, COUNT(*) AS clicks FROM Instagram_Ads WHERE post_time >= NOW() - INTERVAL '1 week' GROUP BY age, gender UNION ALL SELECT 'Snapchat' AS platform, age, gender, COUNT(*) AS clicks FROM Snapchat_Ads WHERE post_time >= NOW() - INTERVAL '1 week' GROUP BY age, gender;
What is the average credit score of clients who have completed the Islamic Financial Education program?
CREATE TABLE islamic_financial_education (client_id INT,program_name VARCHAR(30),credit_score INT,program_status VARCHAR(20)); INSERT INTO islamic_financial_education (client_id,program_name,credit_score,program_status) VALUES (201,'Islamic Financial Education',700,'Completed'),(202,'Financial Wellbeing',650,'Enrolled'),(203,'Islamic Financial Education',720,'Completed'),(204,'Financial Capability',680,'Dropped Out');
SELECT AVG(credit_score) FROM islamic_financial_education WHERE program_name = 'Islamic Financial Education' AND program_status = 'Completed';
What is the average satisfaction score for creative AI applications in the USA?
CREATE TABLE creative_ai (id INT,country VARCHAR(50),application VARCHAR(50),satisfaction FLOAT); INSERT INTO creative_ai (id,country,application,satisfaction) VALUES (1,'USA','Text Generation',4.3),(2,'Canada','Image Recognition',4.5);
SELECT AVG(satisfaction) FROM creative_ai WHERE country = 'USA';
What is the average water usage per household in the city of Austin, Texas, for the month of June?
CREATE TABLE water_usage (id INT,household_id INT,city TEXT,state TEXT,usage REAL,timestamp DATETIME); INSERT INTO water_usage (id,household_id,city,state,usage,timestamp) VALUES (1,1,'Austin','Texas',1500,'2022-06-01 00:00:00'),(2,2,'Austin','Texas',1200,'2022-06-15 12:00:00'),(3,3,'Austin','Texas',1800,'2022-06-30 23:59:59');
SELECT AVG(usage) FROM water_usage WHERE city = 'Austin' AND state = 'Texas' AND MONTH(timestamp) = 6;
Which sectors have the highest greenhouse gas emissions in Africa in the last 10 years?
CREATE TABLE emissions (region VARCHAR(255),sector VARCHAR(255),year INT,ghg_emissions FLOAT); INSERT INTO emissions (region,sector,year,ghg_emissions) VALUES ('Africa','Energy',2012,600),('Africa','Industry',2012,500),('Africa','Energy',2013,650),('Africa','Industry',2013,550);
SELECT sector, SUM(ghg_emissions) AS total_emissions FROM emissions WHERE region = 'Africa' GROUP BY sector ORDER BY total_emissions DESC;