instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total number of participants in community development initiatives in rural Africa?
CREATE TABLE Community_Development_Initiatives (id INT,initiative_name TEXT,participants INT,location TEXT); INSERT INTO Community_Development_Initiatives (id,initiative_name,participants,location) VALUES (1,'Clean Water Access',150,'Rural Africa'),(2,'Education Center',200,'Urban Africa');
SELECT SUM(participants) FROM Community_Development_Initiatives WHERE location = 'Rural Africa';
Which habitats have seen a decrease in preservation efforts from 2017 to 2018?
CREATE TABLE PreservationTrends(Year INT,Habitat VARCHAR(20),Efforts INT); INSERT INTO PreservationTrends VALUES (2017,'Forest',120),(2018,'Forest',150),(2017,'Wetland',80),(2018,'Wetland',90);
SELECT Habitat, (Efforts2018 - Efforts2017) AS DecreaseInEfforts FROM (SELECT Habitat, MAX(CASE WHEN Year = 2017 THEN Efforts END) AS Efforts2017, MAX(CASE WHEN Year = 2018 THEN Efforts END) AS Efforts2018 FROM PreservationTrends GROUP BY Habitat) AS Subquery;
List the species and their average weight in the Mediterranean region?
CREATE TABLE Species (region VARCHAR(255),species_name VARCHAR(255),avg_weight DECIMAL(5,2)); INSERT INTO Species (region,species_name,avg_weight) VALUES ('Mediterranean','Tuna',25.5),('Mediterranean','Salmon',12.2);
SELECT species_name, avg_weight FROM Species WHERE region = 'Mediterranean';
What is the biomass of seafood species at risk in the Mediterranean Sea?
CREATE TABLE seafoodspecies (species VARCHAR(30),biomass FLOAT,location VARCHAR(20)); INSERT INTO seafoodspecies (species,biomass,location) VALUES ('Tuna',15000,'Mediterranean Sea'),('Sardines',20000,'Mediterranean Sea');
SELECT biomass FROM seafoodspecies WHERE species IN ('Tuna', 'Sardines') AND location = 'Mediterranean Sea';
What is the total production (production) of seafood (product) with organic certification (is_organic) for each country (country) in the 'seafood_production_v3' table, where the total production exceeds 20000 tons?
CREATE TABLE seafood_production_v3 (id INT,country VARCHAR(255),product VARCHAR(255),production FLOAT,is_organic BOOLEAN); INSERT INTO seafood_production_v3 (id,country,product,production,is_organic) VALUES (1,'Norway','Salmon',25000.0,TRUE),(2,'Norway','Cod',15000.0,FALSE),(3,'Chile','Tuna',18000.0,TRUE),(4,'Chile','Hake',12000.0,FALSE),(5,'Canada','Lobster',22000.0,TRUE);
SELECT country, SUM(production) FROM seafood_production_v3 WHERE is_organic = TRUE GROUP BY country HAVING SUM(production) > 20000;
How many funding sources have contributed to theatre-related productions?
CREATE TABLE TheatreEvents (id INT,title VARCHAR(50),type VARCHAR(50)); INSERT INTO TheatreEvents (id,title,type) VALUES (1,'Theatre Play','Play'); INSERT INTO TheatreEvents (id,title,type) VALUES (2,'Musical','Musical'); CREATE TABLE TheatreFunding (id INT,event_id INT,source VARCHAR(50),amount FLOAT); INSERT INTO TheatreFunding (id,event_id,source,amount) VALUES (1,1,'City Grant',12000); INSERT INTO TheatreFunding (id,event_id,source,amount) VALUES (2,1,'Private Donor',8000); INSERT INTO TheatreFunding (id,event_id,source,amount) VALUES (3,2,'Government Grant',10000);
SELECT COUNT(DISTINCT source) FROM TheatreFunding WHERE type = 'Play';
Number of awards won by female directors?
CREATE TABLE Awards (id INT,director_name VARCHAR(100),director_gender VARCHAR(10),award VARCHAR(50));
SELECT COUNT(*) FROM Awards WHERE director_gender = 'female';
What is the "license_number" for the contractor with "contractor_id" 1001 in the "Contractors" table?
CREATE TABLE Contractors (contractor_id INT,name VARCHAR(255),location VARCHAR(255),license_number VARCHAR(50));
SELECT license_number FROM Contractors WHERE contractor_id = 1001;
Determine the difference in average retail price between Indica and Sativa strains in California.
CREATE TABLE DispensarySales(id INT,dispensary VARCHAR(255),state VARCHAR(255),strain_type VARCHAR(255),retail_price DECIMAL(10,2));
SELECT AVG(CASE WHEN strain_type = 'Indica' THEN retail_price ELSE NULL END) - AVG(CASE WHEN strain_type = 'Sativa' THEN retail_price ELSE NULL END) as price_difference FROM DispensarySales WHERE state = 'California';
What was the total revenue by week for a specific dispensary in Colorado in 2021?
CREATE TABLE Dispensaries (id INT,name TEXT,state TEXT); INSERT INTO Dispensaries (id,name,state) VALUES (1,'Dispensary A','Colorado'); CREATE TABLE Sales (dispid INT,date DATE,revenue DECIMAL(10,2)); INSERT INTO Sales (dispid,date,revenue) VALUES (1,'2021-01-01',2000); INSERT INTO Sales (dispid,date,revenue) VALUES (1,'2021-01-08',2500);
SELECT d.name, WEEK(s.date) as week, SUM(s.revenue) as total_revenue FROM Dispensaries d JOIN Sales s ON d.id = s.dispid WHERE d.state = 'Colorado' AND d.name = 'Dispensary A' AND YEAR(s.date) = 2021 GROUP BY d.name, week;
What is the total pro bono hours for attorneys who work on civil cases, ordered by hours?
CREATE TABLE attorney (attorney_id INT,name VARCHAR(255),location VARCHAR(255)); INSERT INTO attorney (attorney_id,name,location) VALUES (1,'Juan Rodriguez','Miami'),(2,'Maria Garcia','Los Angeles'),(3,'David Kim','Seattle'); CREATE TABLE case_outcomes (outcome_id INT,attorney_id INT,case_type VARCHAR(255),hours DECIMAL(10,2)); INSERT INTO case_outcomes (outcome_id,attorney_id,case_type,hours) VALUES (1,1,'Civil',20.00),(2,1,'Civil',25.00),(3,2,'Criminal',30.00),(4,3,'Family',35.00),(5,3,'Civil',40.00),(6,3,'Civil',45.00);
SELECT case_type, SUM(hours) as total_hours FROM case_outcomes WHERE case_type = 'Civil' GROUP BY case_type ORDER BY total_hours DESC;
Update the 'production_schedule' table and set 'production_status' to 'completed' for all records where 'shift_time' is '06:00-14:00'
CREATE TABLE production_schedule (schedule_id INT,shift_time TIME,production_status VARCHAR(15));
UPDATE production_schedule SET production_status = 'completed' WHERE shift_time = '06:00-14:00';
What is the maximum emission level for each chemical compound in the West region in Q2 2021?
CREATE TABLE plants (plant_id INT,plant_name VARCHAR(50),region VARCHAR(50)); INSERT INTO plants (plant_id,plant_name,region) VALUES (1,'Plant C','West'); INSERT INTO plants (plant_id,plant_name,region) VALUES (2,'Plant D','East'); CREATE TABLE chemical_emissions (plant_id INT,chemical_compound VARCHAR(50),emission_level INT,emission_date DATE); INSERT INTO chemical_emissions (plant_id,chemical_compound,emission_level,emission_date) VALUES (1,'Compound X',200,'2021-04-01'); INSERT INTO chemical_emissions (plant_id,chemical_compound,emission_level,emission_date) VALUES (1,'Compound Y',250,'2021-04-02');
SELECT chemical_compound, MAX(emission_level) AS max_emission_q2_2021 FROM chemical_emissions WHERE region = 'West' AND emission_date BETWEEN '2021-04-01' AND '2021-06-30' GROUP BY chemical_compound;
List all climate communication campaigns in South America and their budgets, sorted by campaign name.
CREATE TABLE climate_communication_sa (campaign_name VARCHAR(50),country VARCHAR(50),budget NUMERIC(12,2)); INSERT INTO climate_communication_sa (campaign_name,country,budget) VALUES ('Green Future','Brazil',15000.00),('Climate Action','Argentina',20000.00),('Eco Life','Colombia',12000.00),('Clean Earth','Peru',18000.00),('Sustainable World','Chile',25000.00);
SELECT campaign_name, country, budget FROM climate_communication_sa WHERE country IN ('South America') ORDER BY campaign_name;
What is the maximum investment in climate finance for a single project in Europe?
CREATE TABLE climate_finance_projects (id INT,country VARCHAR(50),project VARCHAR(50),investment FLOAT); INSERT INTO climate_finance_projects (id,country,project,investment) VALUES (1,'Germany','renewable energy',2000000.00),(2,'France','energy efficiency',1500000.00),(3,'UK','carbon capture',3000000.00);
SELECT MAX(investment) FROM climate_finance_projects WHERE country IN ('Germany', 'France', 'UK', 'Italy', 'Spain');
What was the total R&D expenditure for 'DrugA'?
CREATE TABLE rd_expenditure (drug_name TEXT,amount INTEGER); INSERT INTO rd_expenditure VALUES ('DrugA',5000000);
SELECT SUM(amount) FROM rd_expenditure WHERE drug_name = 'DrugA';
What was the total sales revenue of all drugs in Q4 2020 in Mexico?
CREATE TABLE sales (drug_name TEXT,quarter TEXT,year INTEGER,revenue INTEGER); INSERT INTO sales (drug_name,quarter,year,revenue) VALUES ('DrugA','Q4',2020,100000),('DrugB','Q4',2020,150000);
SELECT SUM(revenue) FROM sales WHERE quarter = 'Q4' AND year = 2020;
What is the number of primary care physicians per capita in each state of the United States?
CREATE TABLE us_states (id INT,name VARCHAR(255)); CREATE TABLE primary_care_physicians (id INT,state_id INT,count INT); CREATE TABLE population (id INT,state_id INT,total_population INT); INSERT INTO us_states (id,name) VALUES (1,'Alabama'),(2,'Alaska'),(3,'Arizona'),(4,'Arkansas'),(5,'California');
SELECT s.name, pc.count / p.total_population AS physicians_per_capita FROM primary_care_physicians pc JOIN us_states s ON pc.state_id = s.id JOIN population p ON pc.state_id = p.state_id;
What is the maximum and minimum funding amount by quarter for companies founded in the US?
CREATE TABLE funding (funding_id INT,company_id INT,amount DECIMAL(10,2),year INT,quarter INT); INSERT INTO funding (funding_id,company_id,amount,year,quarter) VALUES (1,1,150000.00,2019,1),(2,2,200000.00,2018,4),(3,3,250000.00,2019,2); CREATE TABLE companies (company_id INT,founding_year INT,country VARCHAR(255)); INSERT INTO companies (company_id,founding_year,country) VALUES (1,2018,'USA'),(2,2017,'Canada'),(3,2019,'USA');
SELECT companies.country, funding.quarter, MAX(funding.amount) as max_funding, MIN(funding.amount) as min_funding FROM funding JOIN companies ON funding.company_id = companies.company_id WHERE companies.country = 'USA' GROUP BY companies.country, funding.quarter;
Create a table named "indigenous_farms" with columns "id", "name", "community", and "hectares" where "id" is the primary key
CREATE TABLE indigenous_farms (id SERIAL PRIMARY KEY,name TEXT,community TEXT,hectares INT);
CREATE TABLE indigenous_farms (id SERIAL PRIMARY KEY, name TEXT, community TEXT, hectares INT);
Identify the most common disability-related complaints in each of the last 3 months, and the total number of complaints in each of those months?
CREATE TABLE complaints (complaint_id INT,complaint_type VARCHAR(255),date DATE); INSERT INTO complaints (complaint_id,complaint_type,date) VALUES (1,'Physical Barrier','2021-03-15'); INSERT INTO complaints (complaint_id,complaint_type,date) VALUES (2,'Lack of Communication','2021-02-20');
SELECT MONTH(date) as month, complaint_type, COUNT(*) as num_complaints FROM complaints WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 3 MONTH) AND NOW() GROUP BY month, complaint_type;
What is the percentage of students who received accommodations for mobility impairments?
CREATE TABLE Students (student_id INT,department VARCHAR(255)); CREATE TABLE Accommodations (accommodation_id INT,student_id INT,accommodation_type VARCHAR(255)); CREATE TABLE DisabilityTypes (disability_type VARCHAR(255),student_id INT);
SELECT (COUNT(DISTINCT student_id) * 100.0 / (SELECT COUNT(DISTINCT student_id) FROM Students)) as percentage FROM Accommodations WHERE student_id IN ( SELECT student_id FROM DisabilityTypes WHERE disability_type = 'Mobility Impairment');
What is the total budget allocated for physical disability accommodations in South America?
CREATE TABLE Accommodations (Id INT,StudentId INT,Type VARCHAR(50),RequestDate DATE,Region VARCHAR(30),Budget DECIMAL(10,2)); INSERT INTO Accommodations (Id,StudentId,Type,RequestDate,Region,Budget) VALUES (1,1,'Wheelchair Ramp','2022-01-01','South America',2000),(2,2,'Mobility Scooter','2022-02-01','South America',3000),(3,3,'Wheelchair Lift','2022-03-01','South America',4000),(4,4,'Adaptive Seating','2022-04-01','South America',5000);
SELECT SUM(Budget) FROM Accommodations WHERE Type LIKE 'Physical%' AND Region = 'South America';
What is the average depth of all trenches in the Southern Ocean?
CREATE TABLE oceanography (id INT,location VARCHAR(255),depth INT); INSERT INTO oceanography (id,location,depth) VALUES (1,'Southern Ocean Trench',8000);
SELECT AVG(depth) FROM oceanography WHERE location = 'Southern Ocean Trench';
What are the total unit sales of cosmetics products that are free from parabens and sulfates?
CREATE TABLE product_safety (product_name TEXT,is_paraben_free BOOLEAN,is_sulfate_free BOOLEAN); INSERT INTO product_safety (product_name,is_paraben_free,is_sulfate_free) VALUES ('Product 6',true,true),('Product 7',false,false),('Product 8',true,true),('Product 9',false,true),('Product 10',true,true); CREATE TABLE product_sales (product_name TEXT,unit_sales INTEGER); INSERT INTO product_sales (product_name,unit_sales) VALUES ('Product 6',500),('Product 7',300),('Product 8',400),('Product 9',700),('Product 10',200);
SELECT SUM(product_sales.unit_sales) FROM product_sales JOIN product_safety ON product_sales.product_name = product_safety.product_name WHERE product_safety.is_paraben_free = true AND product_safety.is_sulfate_free = true;
What is the total revenue of organic cosmetics sold in the UK in the past month?
CREATE TABLE OrganicSales (product VARCHAR(255),country VARCHAR(255),is_organic BOOLEAN,revenue FLOAT);
SELECT SUM(revenue) FROM OrganicSales WHERE is_organic = TRUE AND country = 'UK' AND date >= DATEADD(month, -1, GETDATE());
What is the total number of artworks in the 'Artworks' table, grouped by art category?
CREATE TABLE Artworks (id INT,art_category VARCHAR(255),artist_name VARCHAR(255),year INT,art_medium VARCHAR(255));
SELECT art_category, COUNT(*) as total FROM Artworks GROUP BY art_category;
What is the total number of threat intelligence incidents by day for the last week?
CREATE TABLE ThreatIntelligence (IncidentID int,IncidentDate date,IncidentSeverity varchar(50)); INSERT INTO ThreatIntelligence (IncidentID,IncidentDate,IncidentSeverity) VALUES (1,'2022-01-15','High'),(2,'2022-03-01','Medium'),(3,'2022-04-10','High'),(4,'2022-07-05','Low'),(5,'2022-11-28','Medium'),(6,'2022-12-01','High'),(7,'2022-12-03','Low');
SELECT IncidentDate, COUNT(*) as NumIncidents FROM ThreatIntelligence WHERE IncidentDate >= DATEADD(day, -7, CURRENT_DATE) GROUP BY IncidentDate;
What is the total number of military equipment in the 'naval' category, by country?
CREATE TABLE military_equipment_2 (country VARCHAR(50),category VARCHAR(50),number INT); INSERT INTO military_equipment_2 (country,category,number) VALUES ('USA','Naval',287),('Russia','Naval',278),('China','Naval',714),('UK','Naval',76),('India','Naval',295);
SELECT country, SUM(number) as total_naval FROM military_equipment_2 WHERE category = 'Naval' GROUP BY country;
Update the destination to 'Cape Town' for all records with cargo_id 103 in table fleet_management
CREATE TABLE fleet_management (id INT PRIMARY KEY,cargo_id INT,status VARCHAR(20),destination VARCHAR(20)); INSERT INTO fleet_management (id,cargo_id,status,destination) VALUES (1,101,'pending','Buenos Aires'),(2,102,'loaded','Sydney'),(3,103,'pending','Buenos Aires');
UPDATE fleet_management SET destination = 'Cape Town' WHERE cargo_id = 103;
What is the average gross tonnage of container vessels in each port?
CREATE TABLE Port (PortID INT,PortName VARCHAR(50),City VARCHAR(50),Country VARCHAR(50)); INSERT INTO Port (PortID,PortName,City,Country) VALUES (1,'Port of Los Angeles','Los Angeles','USA'); INSERT INTO Port (PortID,PortName,City,Country) VALUES (2,'Port of Rotterdam','Rotterdam','Netherlands'); CREATE TABLE Vessel (VesselID INT,VesselName VARCHAR(50),GrossTonnage INT,VesselType VARCHAR(50),PortID INT); INSERT INTO Vessel (VesselID,VesselName,GrossTonnage,VesselType,PortID) VALUES (1,'Ever Ace',235000,'Container',1); INSERT INTO Vessel (VesselID,VesselName,GrossTonnage,VesselType,PortID) VALUES (2,'Algeciras',128000,'Ro-Ro',2);
SELECT PortName, AVG(GrossTonnage) AS AvgGrossTonnage FROM Vessel v JOIN Port p ON v.PortID = p.PortID WHERE VesselType = 'Container' GROUP BY PortName;
Identify the total number of machines in the 'Circular Economy' category that were manufactured before 2010.
CREATE TABLE Machines (MachineID INT,Category VARCHAR(50),ManufacturingYear INT); INSERT INTO Machines (MachineID,Category,ManufacturingYear) VALUES (1,'Circular Economy',2005); INSERT INTO Machines (MachineID,Category,ManufacturingYear) VALUES (2,'Circular Economy',2012);
SELECT COUNT(*) FROM Machines WHERE Category = 'Circular Economy' AND ManufacturingYear < 2010;
Show the total number of artifacts excavated from site 'Timgad'.
CREATE TABLE artifact_timgad (artifact_id INTEGER,site_name TEXT,artifact_type TEXT,age INTEGER); INSERT INTO artifact_timgad (artifact_id,site_name,artifact_type,age) VALUES (1,'Timgad','Pottery',1800),(2,'Timgad','Stone',1900),(3,'Timgad','Ceramic',1700),(4,'Timgad','Bone',1600),(5,'Timgad','Stone',2000);
SELECT COUNT(*) FROM artifact_timgad WHERE site_name = 'Timgad';
Find the total value of social impact bonds issued by each organization.
CREATE TABLE social_impact_bonds (id INT,organization_name VARCHAR(255),issue_year INT,value FLOAT); INSERT INTO social_impact_bonds (id,organization_name,issue_year,value) VALUES (1,'Acme Corp',2018,2000000),(2,'XYZ Foundation',2019,3000000),(3,'Global Giving',2018,1500000),(4,'Acme Corp',2019,2500000),(5,'XYZ Foundation',2018,1000000);
SELECT organization_name, SUM(value) as total_value FROM social_impact_bonds GROUP BY organization_name;
List all social impact investments in the Healthcare sector with ESG scores above 80, ordered by investment date and ESGScore, including only investments made by investors from the United Kingdom.
CREATE TABLE SocialImpactInvestments (InvestmentID INT,InvestmentDate DATE,Sector VARCHAR(20),ESGScore INT,InvestorCountry VARCHAR(20)); INSERT INTO SocialImpactInvestments VALUES (1,'2021-01-01','Healthcare',85,'UK'),(2,'2021-02-01','Healthcare',75,'Germany'),(3,'2021-03-01','Healthcare',82,'UK');
SELECT * FROM SocialImpactInvestments WHERE Sector = 'Healthcare' AND ESGScore > 80 AND InvestorCountry = 'UK' ORDER BY InvestmentDate, ESGScore DESC;
What is the ranking of national security measures for Russia based on the publication date?
CREATE TABLE national_security (id INT,title VARCHAR(255),description TEXT,agency VARCHAR(255),date DATE); INSERT INTO national_security (id,title,description,agency,date) VALUES (1,'National Cyber Strategy','Outlines the approach to protecting the American people and the American way of life in the digital age','White House','2018-09-20'); INSERT INTO national_security (id,title,description,agency,date) VALUES (2,'Cybersecurity and Infrastructure Security Agency Act of 2018','Establishes the Cybersecurity and Infrastructure Security Agency within the Department of Homeland Security','Congress','2018-11-16'); INSERT INTO national_security (id,title,description,agency,date) VALUES (3,'Russian Military Doctrine','Outlines the country’s stance on military security','Russian Government','2014-12-26');
SELECT title, description, agency, date, ROW_NUMBER() OVER (PARTITION BY agency ORDER BY date DESC) as ranking FROM national_security WHERE agency = 'Russian Government';
Update the genre for a specific song
CREATE TABLE songs (id INT PRIMARY KEY,title VARCHAR(100),artist VARCHAR(50),release_date DATE,genre VARCHAR(20));
UPDATE songs SET genre = 'rock' WHERE id = 456 AND title = 'Bohemian Rhapsody';
What are the total views for all open education resources in each language and format, ordered by views?
CREATE TABLE open_education_resources (id INT,title VARCHAR(50),format VARCHAR(10),language VARCHAR(20),views INT); INSERT INTO open_education_resources (id,title,format,language,views) VALUES (1,'Introduction to SQL','Video','English',1000);
SELECT language, format, SUM(views) as total_views FROM open_education_resources GROUP BY language, format ORDER BY total_views DESC;
What is the average salary for employees who identify as female or non-binary, grouped by their department?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(10),Salary DECIMAL(10,2),Department VARCHAR(50)); INSERT INTO Employees (EmployeeID,Gender,Salary,Department) VALUES (1,'Female',85000.00,'IT'),(2,'Male',95000.00,'Marketing'),(3,'Non-binary',70000.00,'HR'),(4,'Female',80000.00,'IT'),(5,'Male',90000.00,'Marketing'),(6,'Non-binary',75000.00,'HR');
SELECT e.Department, AVG(e.Salary) as AvgSalary FROM Employees e WHERE e.Gender IN ('Female', 'Non-binary') GROUP BY e.Department;
What is the difference in average salary between employees who have and have not completed diversity and inclusion training, by job title and region?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(10),JobTitle VARCHAR(50),Region VARCHAR(50),Salary INT,CompletedDiversityTraining BOOLEAN); INSERT INTO Employees (EmployeeID,Gender,JobTitle,Region,Salary,CompletedDiversityTraining) VALUES (1,'Male','Manager','North',70000,TRUE),(2,'Female','Manager','South',65000,FALSE),(3,'Male','Developer','East',60000,TRUE),(4,'Female','Developer','West',62000,FALSE);
SELECT Region, JobTitle, AVG(CASE WHEN CompletedDiversityTraining THEN Salary ELSE NULL END) - AVG(CASE WHEN NOT CompletedDiversityTraining THEN Salary ELSE NULL END) AS Salary_Difference FROM Employees GROUP BY Region, JobTitle;
What is the average number of steals per game for the Lakers?
CREATE TABLE teams (team_id INT,team_name VARCHAR(50)); INSERT INTO teams (team_id,team_name) VALUES (1,'Lakers'); CREATE TABLE games (game_id INT,home_team_id INT,away_team_id INT,home_team_score INT,away_team_score INT,home_team_steals INT,away_team_steals INT); INSERT INTO games (game_id,home_team_id,away_team_id,home_team_score,away_team_score,home_team_steals,away_team_steals) VALUES (1,1,2,100,90,8,7),(2,2,1,80,85,9,6),(3,1,3,110,105,10,8),(4,4,1,70,75,5,7);
SELECT AVG(home_team_steals + away_team_steals) as avg_steals FROM games WHERE home_team_id = (SELECT team_id FROM teams WHERE team_name = 'Lakers') OR away_team_id = (SELECT team_id FROM teams WHERE team_name = 'Lakers');
Which NFL team has the most Super Bowl titles?
CREATE TABLE nfl_teams (team_id INT,name VARCHAR(50),location VARCHAR(50),super_bowl_wins INT); INSERT INTO nfl_teams (team_id,name,location,super_bowl_wins) VALUES (1,'Pittsburgh Steelers','Pittsburgh',6); INSERT INTO nfl_teams (team_id,name,location,super_bowl_wins) VALUES (2,'New England Patriots','Boston',6);
SELECT name FROM nfl_teams WHERE super_bowl_wins = (SELECT MAX(super_bowl_wins) FROM nfl_teams);
What is the total amount of funds allocated for each type of disaster?
CREATE TABLE DisasterFunds (DisasterType VARCHAR(20),FundID INT,AllocatedAmount DECIMAL(10,2)); INSERT INTO DisasterFunds (DisasterType,FundID,AllocatedAmount) VALUES ('Earthquake',1,5000.00),('Flood',2,7500.00),('Hurricane',3,10000.00),('Tornado',4,12500.00),('Volcano',5,15000.00);
SELECT DisasterType, SUM(AllocatedAmount) as TotalFunds FROM DisasterFunds GROUP BY DisasterType;
Who is the contact person for the 'refugee support' sector?
CREATE TABLE contacts (id INT,name TEXT,sector TEXT,email TEXT); INSERT INTO contacts (id,name,sector,email) VALUES (1,'John Doe','refugee support','[email protected]'); INSERT INTO contacts (id,name,sector,email) VALUES (2,'Jane Doe','community development','[email protected]');
SELECT name, email FROM contacts WHERE sector = 'refugee support';
What is the total number of ethical AI projects in the healthcare sector?
CREATE TABLE Ethical_AI (sector VARCHAR(50),projects INT); INSERT INTO Ethical_AI (sector,projects) VALUES ('Healthcare',100),('Finance',150),('Education',120),('Retail',80);
SELECT sector, SUM(projects) FROM Ethical_AI WHERE sector = 'Healthcare';
Who are the top 3 suppliers of recycled polyester?
CREATE TABLE suppliers (id INT,name VARCHAR(255),material VARCHAR(255)); INSERT INTO suppliers (id,name,material) VALUES (1,'Supplier A','Recycled Polyester'),(2,'Supplier B','Organic Cotton'),(3,'Supplier C','Recycled Polyester'),(4,'Supplier D','Hemp'),(5,'Supplier E','Recycled Polyester');
SELECT name FROM suppliers WHERE material = 'Recycled Polyester' GROUP BY name ORDER BY COUNT(*) DESC LIMIT 3;
What is the most popular post category on TikTok in the last week?
CREATE TABLE post_data (post_id INT,category VARCHAR(50),platform VARCHAR(20),date DATE); INSERT INTO post_data (post_id,category,platform,date) VALUES (1,'dance','TikTok','2022-01-01'),(2,'comedy','TikTok','2022-01-02'),(3,'dance','Instagram','2022-01-03');
SELECT category, COUNT(*) AS count FROM post_data WHERE platform = 'TikTok' AND date >= DATEADD(week, -1, GETDATE()) GROUP BY category ORDER BY count DESC LIMIT 1;
Compute the average financial wellbeing score change for customers from the previous quarter.
CREATE TABLE financial_wellbeing(customer_id INT,score DECIMAL(3,1),measure_date DATE); INSERT INTO financial_wellbeing VALUES (1,75,'2022-01-15'),(2,80,'2022-04-01'),(3,70,'2022-03-05'),(4,85,'2022-05-12'),(5,72,'2022-02-01'),(6,78,'2022-01-02');
SELECT AVG(score - LAG(score) OVER (PARTITION BY customer_id ORDER BY measure_date)) AS avg_change FROM financial_wellbeing;
How many clients have taken out socially responsible loans in each country, excluding loans from clients in Saudi Arabia and the UAE?
CREATE TABLE socially_responsible_loans(client_id INT,client_country VARCHAR(25));INSERT INTO socially_responsible_loans(client_id,client_country) VALUES (1,'Bahrain'),(2,'UAE'),(3,'Indonesia'),(4,'Saudi Arabia'),(5,'Malaysia'),(6,'UAE'),(7,'Indonesia'),(8,'Saudi Arabia'),(9,'Malaysia'),(10,'UAE');
SELECT client_country, COUNT(DISTINCT client_id) as num_clients FROM socially_responsible_loans WHERE client_country NOT IN ('Saudi Arabia', 'UAE') GROUP BY client_country;
What is the average financial wellbeing program duration in South America by country?
CREATE TABLE programs (id INT PRIMARY KEY,program_name VARCHAR(255),region_id INT,is_financial_wellbeing BOOLEAN,start_date DATE,end_date DATE); CREATE TABLE regions (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255)); CREATE VIEW program_views AS SELECT programs.id,programs.program_name,programs.region_id,programs.is_financial_wellbeing,programs.start_date,programs.end_date,regions.country FROM programs INNER JOIN regions ON TRUE;
SELECT regions.country, AVG(DATEDIFF('day', program_views.start_date, program_views.end_date)) AS avg_duration FROM program_views INNER JOIN regions ON program_views.region_id = regions.id WHERE program_views.is_financial_wellbeing = TRUE AND regions.country IN ('South America') GROUP BY regions.country;
Delete all records from the 'food_recalls' table that have a 'recall_date' before '2020-01-01'
CREATE TABLE food_recalls (id INT PRIMARY KEY,product VARCHAR(100),recall_date DATE);
DELETE FROM food_recalls WHERE recall_date < '2020-01-01';
How many GMO products were sold in Italy in 2020?
CREATE TABLE sales_gmo (id INT,product VARCHAR(50),is_gmo BOOLEAN,sale_date DATE); INSERT INTO sales_gmo (id,product,is_gmo,sale_date) VALUES (1,'Corn',true,'2020-01-01'),(2,'Soybeans',true,'2020-01-02');
SELECT COUNT(*) FROM sales_gmo WHERE is_gmo = true AND EXTRACT(YEAR FROM sale_date) = 2020 AND country = 'Italy';
How many shipments were made in each country in the last month?
CREATE TABLE Warehouses (WarehouseID INT,WarehouseName VARCHAR(50),Country VARCHAR(50)); CREATE TABLE Shipments (ShipmentID INT,WarehouseID INT,DeliveryTime INT,ShipmentDate DATE);
SELECT W.Country, COUNT(*) AS ShipmentsInCountry, YEAR(S.ShipmentDate) AS ShipmentYear, MONTH(S.ShipmentDate) AS ShipmentMonth FROM Warehouses W JOIN Shipments S ON W.WarehouseID = S.WarehouseID WHERE S.ShipmentDate >= DATEADD(month, -1, GETDATE()) GROUP BY W.Country, YEAR(S.ShipmentDate), MONTH(S.ShipmentDate);
What is the total quantity of each product shipped from the Tokyo warehouse?
CREATE TABLE Warehouses (WarehouseID int,WarehouseName varchar(255),City varchar(255),Country varchar(255)); INSERT INTO Warehouses (WarehouseID,WarehouseName,City,Country) VALUES (3,'Tokyo Warehouse','Tokyo','Japan'); CREATE TABLE Shipments (ShipmentID int,WarehouseID int,ProductName varchar(255),Quantity int,ShippedDate date); INSERT INTO Shipments (ShipmentID,WarehouseID,ProductName,Quantity,ShippedDate) VALUES (3,3,'Oranges',70,'2022-01-03');
SELECT ProductName, SUM(Quantity) AS TotalQuantity FROM Shipments WHERE WarehouseID = 3 GROUP BY ProductName;
What is the number of traffic accidents in Toronto involving cyclists in the last 3 years, and how many resulted in injuries?
CREATE TABLE traffic_accidents (year INT,location VARCHAR(255),accident_type VARCHAR(255),injury BOOLEAN); INSERT INTO traffic_accidents (year,location,accident_type,injury) VALUES (2019,'Toronto','cyclist',TRUE),(2020,'Toronto','cyclist',FALSE),(2021,'Toronto','cyclist',TRUE);
SELECT COUNT(*) AS total_accidents, SUM(injury) AS injury_accidents FROM traffic_accidents WHERE location = 'Toronto' AND accident_type = 'cyclist' AND year BETWEEN 2019 AND 2021;
How many graduate students from underrepresented communities are enrolled in STEM programs?
CREATE TABLE Students(StudentID INT,Name VARCHAR(50),Program VARCHAR(50),Community VARCHAR(50)); INSERT INTO Students(StudentID,Name,Program,Community) VALUES (1,'Alice Johnson','Computer Science','African American'),(2,'Bob Brown','Physics','Hispanic'),(3,'Charlie Davis','Mathematics','Native American');
SELECT COUNT(*) FROM Students WHERE Program LIKE '%STEM%' AND Community IN ('African American', 'Hispanic', 'Native American')
What is the maximum grant amount awarded to any research project in the Chemistry department?
CREATE TABLE grants (id INT,department VARCHAR(10),amount INT); INSERT INTO grants (id,department,amount) VALUES (1,'Physics',50000),(2,'Chemistry',80000);
SELECT MAX(amount) FROM grants WHERE department = 'Chemistry';
What is the number of research publications for each student, sorted by the number of publications in descending order?
CREATE TABLE GraduateStudents (StudentID int,StudentName varchar(255)); CREATE TABLE Publications (PublicationID int,StudentID int,Title varchar(255));
SELECT StudentName, COUNT(*) as NumPublications FROM Publications p JOIN GraduateStudents gs ON p.StudentID = gs.StudentID GROUP BY StudentName ORDER BY NumPublications DESC;
What is the distribution of mental health parity compliance scores for each health equity metric?
CREATE TABLE ParityCompliance (MetricID INT,HealthEquityMetric TEXT,ComplianceScore INT); INSERT INTO ParityCompliance (MetricID,HealthEquityMetric,ComplianceScore) VALUES (1,'Access to Care',80),(2,'Quality of Care',90),(3,'Cost of Care',70);
SELECT HealthEquityMetric, AVG(ComplianceScore) as Avg_Score, STDDEV(ComplianceScore) as StdDev_Score FROM ParityCompliance GROUP BY HealthEquityMetric;
List the top 3 countries with the most heritage sites and the number of sites for each?
CREATE TABLE heritage_sites (site_id INT,site_name TEXT,country TEXT); INSERT INTO heritage_sites (site_id,site_name,country) VALUES (1,'Heritage Site 1','Italy'),(2,'Heritage Site 2','Italy'),(3,'Heritage Site 3','Germany'),(4,'Heritage Site 4','Spain'),(5,'Heritage Site 5','France');
SELECT country, COUNT(*) AS num_sites FROM heritage_sites GROUP BY country ORDER BY num_sites DESC LIMIT 3;
What is the percentage of hotels in the EU that have adopted AI technology?
CREATE TABLE hotel_tech (hotel_id INT,hotel_name VARCHAR(255),ai_adoption BOOLEAN); INSERT INTO hotel_tech (hotel_id,hotel_name,ai_adoption) VALUES (1,'Hotel A',TRUE),(2,'Hotel B',FALSE),(3,'Hotel C',TRUE);
SELECT (COUNT(*) FILTER (WHERE ai_adoption = TRUE) * 100.0 / COUNT(*)) FROM hotel_tech WHERE country IN ('EU', 'Europe');
How many species were observed per month in the Tundra Biology Study?
CREATE TABLE TundraBiologyStudy (id INT,year INT,month INT,species_observed INT); INSERT INTO TundraBiologyStudy (id,year,month,species_observed) VALUES (1,2000,1,25),(2,2000,2,28),(3,2000,3,31);
SELECT month, AVG(species_observed) FROM TundraBiologyStudy GROUP BY year, month HAVING AVG(species_observed) > 25;
What is the average temperature per month in each region in the 'temperature_readings' table?
CREATE TABLE temperature_readings (reading_date DATE,temperature FLOAT,region TEXT);
SELECT DATE_TRUNC('month', reading_date) AS month, region, AVG(temperature) FROM temperature_readings GROUP BY month, region;
How many traditional musicians are registered in Mexico?
CREATE TABLE traditional_musicians (id INT PRIMARY KEY,name TEXT,age INT,registration_date DATE,country TEXT);
SELECT COUNT(*) FROM traditional_musicians WHERE country = 'Mexico';
Who are the top 3 contributors to heritage site preservation efforts in Africa?
CREATE TABLE contributors (id INT,name TEXT,country TEXT,amount_donated FLOAT); INSERT INTO contributors (id,name,country,amount_donated) VALUES (1,'John Smith','USA',5000.00),(2,'Jane Doe','Canada',4000.00),(3,'Amina Mohamed','Kenya',8000.00);
SELECT name FROM contributors ORDER BY amount_donated DESC LIMIT 3;
What is the count of bridges in California with seismic retrofit needs, categorized by bridge type and construction year?
CREATE TABLE Bridges (id INT,state VARCHAR(2),bridge_type VARCHAR(10),construction_year INT,seismic_retrofit_need BOOLEAN); INSERT INTO Bridges (id,state,bridge_type,construction_year,seismic_retrofit_need) VALUES (1,'CA','Beam',1960,TRUE),(2,'CA','Arch',1990,FALSE),(3,'CA','Suspension',2010,TRUE);
SELECT bridge_type, construction_year, COUNT(*) as count FROM Bridges WHERE state = 'CA' AND seismic_retrofit_need = TRUE GROUP BY bridge_type, construction_year;
What is the maximum resilience score for infrastructure projects in Texas?
CREATE TABLE Infrastructure (ProjectID INT,Location VARCHAR(20),ResilienceScore FLOAT); INSERT INTO Infrastructure (ProjectID,Location,ResilienceScore) VALUES (1,'Texas',85);
SELECT MAX(ResilienceScore) FROM Infrastructure WHERE Location = 'Texas';
Find the average carbon footprint of all 'sustainable_tourism' activities.
CREATE TABLE sustainable_tourism (activity_name VARCHAR(50),carbon_footprint INT); INSERT INTO sustainable_tourism (activity_name,carbon_footprint) VALUES ('Hiking',5),('Birdwatching',3),('Camping',7);
SELECT AVG(carbon_footprint) FROM sustainable_tourism;
What is the average hotel rating for eco-friendly hotels in Japan?
CREATE TABLE hotels (hotel_id INT,name TEXT,country TEXT,stars FLOAT,is_eco_friendly BOOLEAN); INSERT INTO hotels (hotel_id,name,country,stars,is_eco_friendly) VALUES (1,'Hotel Verde','Japan',4.5,true),(2,'Green Palace','France',4.2,true);
SELECT AVG(stars) FROM hotels WHERE is_eco_friendly = true AND country = 'Japan';
What is the total number of marine mammals in the Gulf of Mexico, excluding dolphins and whales?
CREATE TABLE marine_mammals (id INT,species TEXT,count INT,region TEXT);
SELECT SUM(count) FROM marine_mammals WHERE species NOT IN ('dolphin', 'whale') AND region = 'Gulf of Mexico';
What is the average number of users per media platform in the last month?
CREATE TABLE Users (user_id INT,platform VARCHAR(50),registration_date DATE); INSERT INTO Users (user_id,platform,registration_date) VALUES (1,'Platform1','2022-01-01'),(2,'Platform2','2022-02-15'),(3,'Platform1','2022-03-01');
SELECT AVG(number_of_users) FROM (SELECT platform, COUNT(*) AS number_of_users FROM Users WHERE registration_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY platform) AS subquery;
List all mining sites and their corresponding labor productivity metrics.
CREATE TABLE mining_sites (id INT,name VARCHAR(20),extraction_volume INT,region VARCHAR(20)); CREATE TABLE labor_productivity (site_id INT,productivity DECIMAL(10,2));
SELECT mining_sites.name, labor_productivity.productivity FROM mining_sites JOIN labor_productivity ON mining_sites.id = labor_productivity.site_id;
What is the maximum monthly data usage for broadband subscribers in all regions?
CREATE TABLE subscribers (subscriber_id INT,data_usage FLOAT,region VARCHAR(20)); INSERT INTO subscribers (subscriber_id,data_usage,region) VALUES (1,25.6,'Northern'),(2,32.8,'Northeast'),(3,18.9,'Northern'),(4,45.6,'Southern'),(5,50.0,'Eastern'); CREATE TABLE maximum_usage (max_usage FLOAT); INSERT INTO maximum_usage (max_usage) VALUES (55.0);
SELECT MAX(data_usage) FROM subscribers;
What is the minimum data usage for mobile subscribers in Europe?
CREATE TABLE mobile_subscribers (subscriber_id INT,name VARCHAR(50),data_usage FLOAT,continent VARCHAR(20)); INSERT INTO mobile_subscribers (subscriber_id,name,data_usage,continent) VALUES (1,'John Doe',30.5,'Europe'); INSERT INTO mobile_subscribers (subscriber_id,name,data_usage,continent) VALUES (2,'Jane Smith',35.8,'Europe');
SELECT MIN(data_usage) FROM mobile_subscribers WHERE continent = 'Europe';
Create table for marine protected areas
CREATE TABLE marine_protected_areas (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),size FLOAT,year_established INT);
CREATE TABLE marine_protected_areas (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), size FLOAT, year_established INT);
What is the conservation status of the 'Giant Pacific Octopus'?
CREATE TABLE species (scientific_name TEXT,common_name TEXT,conservation_status TEXT); INSERT INTO species (scientific_name,common_name,conservation_status) VALUES ('Giant Pacific Octopus','Giant Pacific Octopus','Least Concern');
SELECT conservation_status FROM species WHERE common_name = 'Giant Pacific Octopus';
Which countries have the highest and lowest ocean acidity levels?
CREATE TABLE ocean_acidity (country TEXT,avg_ph REAL); INSERT INTO ocean_acidity (country,avg_ph) VALUES ('United States',7.8),('Canada',7.6),('Mexico',7.9);
SELECT country, avg_ph FROM (SELECT country, avg_ph, ROW_NUMBER() OVER (ORDER BY avg_ph DESC) as rnk FROM ocean_acidity) subq WHERE rnk = 1 OR rnk = (SELECT COUNT(*) FROM ocean_acidity) ORDER BY avg_ph;
List the donation amounts and dates for donations made by the donor with ID = 2, in descending order by date.
CREATE TABLE Donations (DonationID int,DonorID int,DonationDate date,DonationAmount decimal(10,2)); INSERT INTO Donations (DonationID,DonorID,DonationDate,DonationAmount) VALUES (1,1,'2020-01-01',1000.00),(2,1,'2020-02-01',1500.00),(3,2,'2020-01-01',2000.00),(4,2,'2020-02-01',1000.00),(5,3,'2020-01-01',3000.00),(6,3,'2020-02-01',2000.00),(7,3,'2020-03-01',2000.00);
SELECT DonationAmount, DonationDate FROM Donations WHERE DonorID = 2 ORDER BY DonationDate DESC;
Update the amount donated by DonorA to 1750.00
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT,Amount DECIMAL(10,2)); INSERT INTO Donors (DonorID,DonorName,Country,Amount) VALUES (1,'DonorA','USA',1500.00),(2,'DonorB','Canada',2000.00);
UPDATE Donors SET Amount = 1750.00 WHERE DonorName = 'DonorA';
Identify the top 3 countries with the highest number of players who have adopted virtual reality technology.
CREATE TABLE CountryData (Country VARCHAR(50),Population INT,VRAdopters INT); INSERT INTO CountryData (Country,Population,VRAdopters) VALUES ('USA',331002651,50000),('China',1439323776,25000),('Canada',37410003),('India',1380004385,10000);
SELECT Country, VRAdopters FROM (SELECT Country, VRAdopters, ROW_NUMBER() OVER (ORDER BY VRAdopters DESC) AS RN FROM CountryData JOIN (SELECT PlayerID, VRDevice FROM VRAdoption GROUP BY PlayerID, VRDevice) VR ON CountryData.Country = VR.PlayerCountry) T WHERE RN <= 3
Find the number of times each type of equipment was used in the past month, and the total duration of use.
CREATE TABLE equipment_data (id INT,equipment_type VARCHAR(255),usage_duration INT,timestamp DATETIME); INSERT INTO equipment_data (id,equipment_type,usage_duration,timestamp) VALUES (1,'Tractor',120,'2022-01-01 10:00:00');
SELECT equipment_type, COUNT(*) as use_count, SUM(usage_duration) as total_duration FROM equipment_data WHERE timestamp >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 MONTH) GROUP BY equipment_type;
Identify the total nitrogen levels and farm size for farms using a center pivot irrigation system, located in the Europe region.
CREATE TABLE farm (id INT,name VARCHAR(50),size FLOAT,irrigation_system VARCHAR(20),region VARCHAR(50),PRIMARY KEY(id)); INSERT INTO farm (id,name,size,irrigation_system,region) VALUES (1,'Farm X',80.3,'center pivot','Europe'); INSERT INTO farm (id,name,size,irrigation_system,region) VALUES (2,'Farm Y',55.8,'drip','Asia'); INSERT INTO farm (id,name,size,irrigation_system,region) VALUES (3,'Farm Z',65.1,'center pivot','Europe'); CREATE TABLE nitrogen (id INT,farm_id INT,nitrogen FLOAT,PRIMARY KEY(id)); INSERT INTO nitrogen (id,farm_id,nitrogen) VALUES (1,1,33.5); INSERT INTO nitrogen (id,farm_id,nitrogen) VALUES (2,1,34.2); INSERT INTO nitrogen (id,farm_id,nitrogen) VALUES (3,3,30.8);
SELECT f.irrigation_system, f.region, SUM(f.size) AS total_area, AVG(n.nitrogen) AS avg_nitrogen FROM farm f INNER JOIN nitrogen n ON f.id = n.farm_id WHERE f.irrigation_system = 'center pivot' AND f.region = 'Europe' GROUP BY f.irrigation_system, f.region;
List the satellite images in the 'satellite_images' table that were taken before June 2021.
CREATE TABLE satellite_images (id INT,image_name VARCHAR(50),capture_date DATE); INSERT INTO satellite_images (id,image_name,capture_date) VALUES (1,'image1','2021-07-01'),(2,'image2','2021-08-01'),(3,'image3','2021-05-01');
SELECT * FROM satellite_images WHERE capture_date < '2021-06-01';
How many public libraries are there in the state of California?
CREATE TABLE state_facilities (state VARCHAR(20),facility_type VARCHAR(20),count INT); INSERT INTO state_facilities (state,facility_type,count) VALUES ('California','Public Library',123);
SELECT COUNT(*) FROM state_facilities WHERE state = 'California' AND facility_type = 'Public Library';
Identify the number of public events organized by the department of community services in the city of Toronto.
CREATE SCHEMA gov_data;CREATE TABLE gov_data.public_events (city VARCHAR(20),department VARCHAR(20),events INT); INSERT INTO gov_data.public_events (city,department,events) VALUES ('Toronto','Community Services',25),('Toronto','Parks',15),('Toronto','Public Libraries',10);
SELECT department, SUM(events) as total_events FROM gov_data.public_events WHERE city = 'Toronto' AND department = 'Community Services' GROUP BY department;
Identify REE mining companies that have operations in both the USA and Australia?
CREATE TABLE company_operations (company_name VARCHAR(255),location VARCHAR(255)); INSERT INTO company_operations (company_name,location) VALUES ('Company X','USA'),('Company Y','Australia'),('Company Z','Canada'),('Company A','China'),('Company B','Australia'),('Company C','USA'),('Company D','Russia'),('Company E','Brazil');
SELECT company_name FROM company_operations WHERE location IN ('USA', 'Australia') GROUP BY company_name HAVING COUNT(DISTINCT location) = 2;
What is the average production quantity for Gadolinium in 2017, excluding companies that produced less than 100 units of Terbium the same year?
CREATE TABLE Producers (ProducerID INT PRIMARY KEY,Name TEXT,ProductionYear INT,RareEarth TEXT,Quantity INT);
SELECT AVG(Quantity) FROM Producers p1 WHERE RareEarth = 'Gadolinium' AND ProductionYear = 2017 AND Quantity > (SELECT SUM(Quantity) FROM Producers p2 WHERE p2.ProducerID = p1.ProducerID AND RareEarth = 'Terbium' AND ProductionYear = 2017) GROUP BY p1.RareEarth, p1.ProductionYear;
Which country produced the most Yttrium in 2020?
CREATE TABLE production_country (year INT,element VARCHAR(10),country VARCHAR(10),quantity INT); INSERT INTO production_country (year,element,country,quantity) VALUES (2020,'Yttrium','China',8000);
SELECT element, country, SUM(quantity) as total_quantity FROM production_country WHERE year = 2020 GROUP BY element, country ORDER BY total_quantity DESC LIMIT 1
What is the minimum monthly rent for studio units in the 'affordable' area?
CREATE TABLE min_rent (unit_id INT,area VARCHAR(20),studio BOOLEAN,monthly_rent FLOAT); INSERT INTO min_rent (unit_id,area,studio,monthly_rent) VALUES (1,'affordable',TRUE,1000);
SELECT MIN(monthly_rent) FROM min_rent WHERE area = 'affordable' AND studio = TRUE;
Get the name and installed capacity of the Wind Farms in the USA with the highest capacity
CREATE TABLE wind_farms_us (id INT,name VARCHAR(100),country VARCHAR(50),capacity_mw FLOAT); INSERT INTO wind_farms_us (id,name,country,capacity_mw) VALUES (1,'Windfarm 1','USA',100.0),(2,'Windfarm 2','USA',120.0),(3,'Windfarm 3','USA',150.0);
SELECT name, capacity_mw FROM wind_farms_us WHERE capacity_mw = (SELECT MAX(capacity_mw) FROM wind_farms_us);
List all solar projects in Spain and their capacities (in MW)
CREATE TABLE project (id INT,name TEXT,country TEXT,type TEXT,capacity INT); INSERT INTO project (id,name,country,type,capacity) VALUES (31,'Solara','Spain','Solar',500),(32,'Barcelona Solar','Spain','Solar',300);
SELECT * FROM project WHERE country = 'Spain' AND type = 'Solar';
Calculate the year-over-year revenue growth for each restaurant.
CREATE TABLE restaurants (restaurant_id INT,restaurant_name VARCHAR(50),city VARCHAR(50),state VARCHAR(50),revenue FLOAT,year INT); INSERT INTO restaurants (restaurant_id,restaurant_name,city,state,revenue,year) VALUES (1,'Restaurant A','City A','State A',123456.78,2021);
SELECT restaurant_name, (revenue - LAG(revenue) OVER (PARTITION BY restaurant_name ORDER BY year)) / ABS(LAG(revenue) OVER (PARTITION BY restaurant_name ORDER BY year)) as revenue_growth FROM restaurants;
What is the average revenue earned by each restaurant in the 'Mexican' cuisine category?
CREATE TABLE restaurants (restaurant_id INT,name VARCHAR(50),cuisine VARCHAR(50),revenue INT); INSERT INTO restaurants VALUES (1,'Asian Fusion','Asian',5000),(2,'Tuscan Bistro','Italian',7000),(3,'Baja Coast','Mexican',4000),(4,'Sushi House','Asian',8000),(5,'Pizzeria Rustica','Italian',6000),(6,'Taqueria El Paso','Mexican',4500),(7,'Mexican Grill','Mexican',5500);
SELECT name, AVG(revenue) FROM restaurants WHERE cuisine = 'Mexican' GROUP BY name;
What is the total revenue for each menu category in restaurant E for the month of June 2021?
CREATE TABLE Restaurants (RestaurantID int,Name varchar(50));CREATE TABLE Menus (MenuID int,RestaurantID int,MenuCategory varchar(50),TotalRevenue decimal(10,2));
SELECT M.MenuCategory, SUM(M.TotalRevenue) as TotalRevenuePerCategory FROM Menus M INNER JOIN Restaurants R ON M.RestaurantID = R.RestaurantID WHERE R.Name = 'E' AND MONTH(M.OrderDate) = 6 AND YEAR(M.OrderDate) = 2021 GROUP BY M.MenuCategory;
What is the total revenue generated by restaurants in New York with a seating capacity greater than 100?
CREATE TABLE restaurants (id INT,name TEXT,location TEXT,seating_capacity INT); INSERT INTO restaurants (id,name,location,seating_capacity) VALUES (1,'Restaurant A','New York',120),(2,'Restaurant B','New York',80),(3,'Restaurant C','Texas',200),(4,'Restaurant D','California',150); CREATE TABLE orders (id INT,restaurant_id INT,revenue DECIMAL(5,2)); INSERT INTO orders (id,restaurant_id,revenue) VALUES (1,1,500.00),(2,1,700.00),(3,2,600.00),(4,3,1200.00),(5,4,900.00);
SELECT SUM(revenue) FROM restaurants INNER JOIN orders ON restaurants.id = orders.restaurant_id WHERE seating_capacity > 100 AND location = 'New York';
List all satellites in Low Earth Orbit (LEO) and their respective launch dates.
CREATE TABLE Satellites (SatelliteID INT,Name VARCHAR(100),OrbitType VARCHAR(50),LaunchDate DATETIME);
SELECT s.Name, s.LaunchDate FROM Satellites s WHERE s.OrbitType = 'Low Earth Orbit';
Find the total number of spacecraft launched by each company, grouped by company name and ordered by the total number of spacecraft launched.
CREATE TABLE Space_Missions(id INT,mission_name VARCHAR(50),launch_date DATE,spacecraft_manufacturer VARCHAR(50));
SELECT spacecraft_manufacturer, COUNT(*) as Total_Spacecraft_Launched FROM Space_Missions GROUP BY spacecraft_manufacturer ORDER BY Total_Spacecraft_Launched DESC;
How many astrophysics research projects have been conducted by ISRO?
CREATE TABLE Astrophysics_Research (id INT,project_name VARCHAR(50),conducting_agency VARCHAR(50)); INSERT INTO Astrophysics_Research (id,project_name,conducting_agency) VALUES (1,'PALIA','ISRO');
SELECT COUNT(project_name) FROM Astrophysics_Research WHERE conducting_agency = 'ISRO';
How many fans attended home games for each team?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams (team_id,team_name) VALUES (1,'Atlanta Hawks'),(2,'Boston Celtics'); CREATE TABLE game_attendance (game_id INT,team_id INT,home_game BOOLEAN,num_fans INT); INSERT INTO game_attendance (game_id,team_id,home_game,num_fans) VALUES (1,1,true,15000),(2,1,false,8000),(3,2,true,20000);
SELECT t.team_name, SUM(CASE WHEN ga.home_game THEN ga.num_fans ELSE 0 END) as home_game_attendance FROM teams t INNER JOIN game_attendance ga ON t.team_id = ga.team_id GROUP BY t.team_name;
What is the maximum trip distance for each vehicle type?
CREATE TABLE trips (id INT,user_id INT,vehicle_type VARCHAR(20),trip_distance FLOAT,trip_duration INT,departure_time TIMESTAMP,arrival_time TIMESTAMP);INSERT INTO trips (id,user_id,vehicle_type,trip_distance,trip_duration,departure_time,arrival_time) VALUES (9,101,'motorcycle',80.7,45,'2022-01-06 06:00:00','2022-01-06 06:45:00');
SELECT vehicle_type, MAX(trip_distance) as max_distance FROM trips GROUP BY vehicle_type;