instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the maximum and minimum number of inclusive housing policies for each city in the database?
CREATE TABLE cities (id INT,name VARCHAR(255),policies INT); INSERT INTO cities (id,name,policies) VALUES (1,'Toronto',10),(2,'Toronto',12),(3,'Montreal',8),(4,'Montreal',9);
SELECT name, MAX(policies) AS max_policies, MIN(policies) AS min_policies FROM cities GROUP BY name;
Calculate the percentage of renewable energy projects in each state of the United States
CREATE TABLE projects (project_id INT,project_name VARCHAR(255),project_type VARCHAR(255),state VARCHAR(255),installed_capacity FLOAT);
SELECT state, (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM projects WHERE state IN (SELECT state FROM (SELECT DISTINCT state FROM projects WHERE state = 'United States') as temp))) as percentage FROM projects WHERE project_type IN ('Solar', 'Wind', 'Geothermal', 'Hydroelectric') GROUP BY state;
How many space missions were successfully launched by each country?
CREATE TABLE space_missions (id INT,mission_name VARCHAR(255),country VARCHAR(255),launch_status VARCHAR(10)); INSERT INTO space_missions (id,mission_name,country,launch_status) VALUES (1,'Apollo 11','USA','Success'),(2,'Mars Orbiter Mission','India','Success'),(3,'Chandrayaan-1','India','Success'),(4,'Grail','USA','Success'),(5,'Mars Express','Europe','Success'),(6,'Venus Express','Europe','Failure'),(7,'Hayabusa','Japan','Success'),(8,'Akatsuki','Japan','Failure');
SELECT country, COUNT(*) as successful_launches FROM space_missions WHERE launch_status = 'Success' GROUP BY country;
What is the total number of satellites launched by the USA and Russia?
CREATE TABLE satellites (id INT,country VARCHAR(255),name VARCHAR(255),launch_date DATE);
SELECT SUM(satellites.id) FROM satellites WHERE satellites.country IN ('USA', 'Russia');
Calculate the minimum distance from the sun of objects in the Oort Cloud
CREATE TABLE objects (id INT,name VARCHAR(50),distance DECIMAL(10,2),category VARCHAR(50));
SELECT MIN(distance) FROM objects WHERE category = 'Oort Cloud';
Find the spacecraft with the longest duration in space, along with its manufacturing date and country.
CREATE TABLE Spacecraft (ID INT,Name VARCHAR(50),ManufacturingDate DATE,Country VARCHAR(50),DurationInSpace INT); INSERT INTO Spacecraft VALUES (1,'Spacecraft A','2010-01-01','USA',2500),(2,'Spacecraft B','2012-05-15','China',3000),(3,'Spacecraft C','2005-09-27','Russia',1800);
SELECT Name, ManufacturingDate, Country, DurationInSpace FROM (SELECT Name, ManufacturingDate, Country, DurationInSpace, ROW_NUMBER() OVER (ORDER BY DurationInSpace DESC) as rn FROM Spacecraft) sub WHERE rn = 1;
How many games were played in each city?
CREATE TABLE cities (city_id INT,city VARCHAR(50));CREATE TABLE teams (team_id INT,team_name VARCHAR(50),city VARCHAR(50));CREATE TABLE games (game_id INT,team_id INT,city VARCHAR(50)); INSERT INTO cities (city_id,city) VALUES (1,'Atlanta'),(2,'Boston'); INSERT INTO teams (team_id,team_name,city) VALUES (1,'Atlanta Hawks','Atlanta'),(2,'Boston Celtics','Boston'); INSERT INTO games (game_id,team_id,city) VALUES (1,1,'Atlanta'),(2,1,'Atlanta'),(3,2,'Boston'),(4,2,'Boston'),(5,1,'Atlanta');
SELECT c.city, COUNT(g.game_id) FROM cities c JOIN games g ON c.city = g.city GROUP BY c.city;
What is the percentage of fans who identify as male, female, or other for each team's fan base?
CREATE TABLE fan_demographics (fan_id INT,team_id INT,gender VARCHAR(10)); CREATE TABLE teams (team_id INT,team_name VARCHAR(255),sport_id INT); INSERT INTO fan_demographics VALUES (1,101,'Male'),(2,101,'Female'),(3,102,'Male'),(4,102,'Other'),(5,103,'Female'),(6,103,'Male'); INSERT INTO teams VALUES (101,'TeamA',1),(102,'TeamB',2),(103,'TeamC',1);
SELECT t.team_name, f.gender, AVG(100.0 * COUNT(f.fan_id) OVER (PARTITION BY t.team_id) / COUNT(f.fan_id) OVER (PARTITION BY NULL)) as percent_of_fans FROM fan_demographics f JOIN teams t ON f.team_id = t.team_id GROUP BY t.team_name, f.gender;
What is the total number of tickets sold for all football games?
CREATE TABLE tickets (ticket_id INT,game_id INT,region VARCHAR(50),quantity INT); INSERT INTO tickets (ticket_id,game_id,region,quantity) VALUES (1,1,'Midwest',500); INSERT INTO tickets (ticket_id,game_id,region,quantity) VALUES (2,2,'Northeast',700); CREATE TABLE games (game_id INT,sport VARCHAR(50)); INSERT INTO games (game_id,sport) VALUES (1,'Football'); INSERT INTO games (game_id,sport) VALUES (2,'Basketball');
SELECT SUM(quantity) FROM tickets INNER JOIN games ON tickets.game_id = games.game_id WHERE sport = 'Football';
What is the total revenue for the soccer team from ticket sales in London and Paris?
CREATE TABLE tickets (ticket_id INT,game_id INT,quantity INT,price DECIMAL(5,2)); INSERT INTO tickets VALUES (1,1,50,25.99); INSERT INTO tickets VALUES (2,2,30,19.99); CREATE TABLE games (game_id INT,team VARCHAR(20),location VARCHAR(20),price DECIMAL(5,2)); INSERT INTO games VALUES (1,'Arsenal','London',50.00); INSERT INTO games VALUES (2,'PSG','Paris',40.00);
SELECT SUM(tickets.quantity * games.price) FROM tickets INNER JOIN games ON tickets.game_id = games.game_id WHERE games.location IN ('London', 'Paris');
Identify the number of security incidents that occurred in 'Europe' in the last month.
CREATE TABLE incidents (incident_id INT PRIMARY KEY,incident_date DATE,incident_location VARCHAR(50)); INSERT INTO incidents (incident_id,incident_date,incident_location) VALUES (1,'2022-01-01','HQ'),(2,'2022-02-15','Branch01'),(3,'2022-03-30','Asia'),(4,'2022-04-15','Europe'),(5,'2022-04-20','Europe');
SELECT COUNT(*) FROM incidents WHERE incident_location = 'Europe' AND incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
Identify the top 5 threat intelligence sources with the highest number of reported incidents in the last year, according to our Incident Tracking database.
CREATE TABLE IncidentTracking (id INT,source VARCHAR(50),incident_count INT,timestamp DATETIME); INSERT INTO IncidentTracking (id,source,incident_count,timestamp) VALUES (1,'TechFirmA',200,'2021-01-01 10:00:00'),(2,'TechFirmB',150,'2021-01-01 10:00:00');
SELECT source, SUM(incident_count) as total_incidents FROM IncidentTracking WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY source ORDER BY total_incidents DESC LIMIT 5;
What are the collective bargaining agreements expiring soon for unions with more than 3000 members in the technology sector?
CREATE TABLE CBAs (UnionName TEXT,ExpirationDate DATE,Sector TEXT); INSERT INTO CBAs (UnionName,ExpirationDate,Sector) VALUES ('UnionTechA','2023-05-01','Technology'),('UnionTechB','2023-12-31','Technology'),('UnionTechC','2024-01-01','Technology');
SELECT UnionName, ExpirationDate FROM CBAs WHERE Sector = 'Technology' AND ExpirationDate <= DATE('2023-12-31') AND MemberCount > 3000;
How many vessels arrived in Brazil in July 2022 with a speed between 15 and 20 knots?
CREATE TABLE vessel_performance (id INT,name TEXT,speed DECIMAL(5,2),arrived_date DATE,country TEXT); INSERT INTO vessel_performance (id,name,speed,arrived_date,country) VALUES (1,'Vessel M',16.7,'2022-07-05','Brazil'),(2,'Vessel N',18.1,'2022-07-12','Brazil'),(3,'Vessel O',14.3,'2022-07-25','Brazil');
SELECT COUNT(*) FROM vessel_performance WHERE arrived_date BETWEEN '2022-07-01' AND '2022-07-31' AND country = 'Brazil' AND speed BETWEEN 15 AND 20;
What was the maximum cargo weight for vessels arriving at the Port of Rotterdam in March 2022?
CREATE TABLE ports (id INT,name TEXT,country TEXT); INSERT INTO ports (id,name,country) VALUES (1,'Rotterdam','Netherlands'); CREATE TABLE vessels (id INT,name TEXT,type TEXT,cargo_weight INT,port_id INT); INSERT INTO vessels (id,name,type,cargo_weight,port_id) VALUES (1,'CSCL Globe','Container',15000,1),(2,'OOCL Hong Kong','Container',19000,1),(3,'CMA CGM Marco Polo','Container',16000,1);
SELECT MAX(cargo_weight) FROM vessels WHERE port_id IN (SELECT id FROM ports WHERE name = 'Rotterdam') AND EXTRACT(MONTH FROM arrival_date) = 3;
Find the top 3 regions with the highest water conservation efforts in 2021, excluding the 'urban' sector.
CREATE TABLE conservation_efforts (region VARCHAR(255),year INT,sector VARCHAR(255),efforts FLOAT); INSERT INTO conservation_efforts (region,year,sector,efforts) VALUES ('North',2021,'rural',0.25),('North',2021,'suburban',0.22),('South',2021,'rural',0.28),('South',2021,'suburban',0.24),('East',2021,'rural',0.21),('East',2021,'suburban',0.26),('West',2021,'rural',0.27),('West',2021,'suburban',0.23),('North',2021,'urban',0.15),('South',2021,'urban',0.18),('East',2021,'urban',0.17),('West',2021,'urban',0.16);
SELECT region, SUM(efforts) AS total_efforts FROM conservation_efforts WHERE year = 2021 AND sector != 'urban' GROUP BY region ORDER BY total_efforts DESC LIMIT 3;
List all water sources located in California, USA
CREATE TABLE water_sources (id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(255),type VARCHAR(255),location VARCHAR(255));
SELECT * FROM water_sources WHERE location LIKE '%California, USA%';
What is the average bias score for each attribute in the 'algorithmic_fairness' table, grouped by algorithm?
CREATE TABLE algorithmic_fairness (algorithm VARCHAR(255),attribute VARCHAR(255),bias_score FLOAT); INSERT INTO algorithmic_fairness (algorithm,attribute,bias_score) VALUES ('TensorFlow','Gender',0.15),('TensorFlow','Race',0.12),('PyTorch','Gender',0.08),('Scikit-learn','Race',0.05),('Scikit-learn','Age',0.02);
SELECT algorithm, attribute, AVG(bias_score) as avg_bias FROM algorithmic_fairness GROUP BY algorithm, attribute;
List the names and budgets of all community development initiatives in the 'community_development' table, sorted by budget in descending order.
CREATE TABLE community_development (id INT,initiative_name VARCHAR(255),budget INT);
SELECT initiative_name, budget FROM community_development ORDER BY budget DESC;
What are the names and costs of agricultural innovation projects in the 'ruraldev' schema that cost more than 200000 and were implemented in Latin America?
CREATE TABLE ruraldev.innovation_projects (id INT,project_name VARCHAR(50),location VARCHAR(50),cost FLOAT); INSERT INTO ruraldev.innovation_projects (id,project_name,location,cost) VALUES (1,'Precision Farming','North America',150000),(2,'Drip Irrigation','Latin America',250000),(3,'Vertical Farming','Europe',300000),(4,'Livestock Genetics','Latin America',220000);
SELECT project_name, cost FROM ruraldev.innovation_projects WHERE location = 'Latin America' AND cost > 200000;
Delete all records for missions with a mission_status of "Aborted" from the space_missions table
CREATE TABLE space_missions (id INT PRIMARY KEY,mission_name VARCHAR(100),launch_date DATE,mission_status VARCHAR(50));
DELETE FROM space_missions WHERE mission_status = 'Aborted';
What are the manufacturing costs for each aircraft model?
CREATE TABLE AircraftModels (id INT,name VARCHAR(50),manufacturing_cost FLOAT); CREATE TABLE ManufacturingData (id INT,model_id INT,cost_center VARCHAR(50),cost FLOAT); CREATE VIEW CostPerModel AS SELECT model_id,SUM(cost) as total_cost FROM ManufacturingData GROUP BY model_id;
SELECT AircraftModels.name, ManufacturingData.cost FROM AircraftModels JOIN CostPerModel ON AircraftModels.id = CostPerModel.model_id JOIN ManufacturingData ON AircraftModels.id = ManufacturingData.model_id WHERE ManufacturingData.cost_center = 'manufacturing';
Add a new 'conservation' record into the 'conservation_efforts' table
CREATE TABLE conservation_efforts (id INT,name VARCHAR(50),description TEXT,target_species VARCHAR(50),budget FLOAT);
INSERT INTO conservation_efforts (id, name, description, target_species, budget) VALUES (1, 'Tiger Protection', 'A project to protect the endangered Bengal Tiger population in India.', 'Bengal Tiger', 1000000.0);
What was the total quantity of lobsters exported from Australia to Japan in 2022?
CREATE TABLE seafood_exports (id INT,export_date DATE,export_country TEXT,import_country TEXT,quantity INT); INSERT INTO seafood_exports (id,export_date,export_country,import_country,quantity) VALUES (1,'2022-01-01','Australia','Japan',300); INSERT INTO seafood_exports (id,export_date,export_country,import_country,quantity) VALUES (2,'2022-02-15','Australia','Japan',400);
SELECT SUM(quantity) FROM seafood_exports WHERE export_country = 'Australia' AND import_country = 'Japan' AND EXTRACT(YEAR FROM export_date) = 2022 AND species = 'Lobster';
Delete records in the cannabis_producers table where the license_type is 'Infuser'
CREATE TABLE cannabis_producers (id INT PRIMARY KEY,name VARCHAR(255),state VARCHAR(2),license_type VARCHAR(255),license_number INT);
WITH cte1 AS (DELETE FROM cannabis_producers WHERE license_type = 'Infuser') SELECT * FROM cte1;
Update the location of a healthcare provider with the name Dr. Johnson.
CREATE TABLE HealthcareProviders (Id INT,Name TEXT,Location TEXT,Specialty TEXT); INSERT INTO HealthcareProviders (Id,Name,Location,Specialty) VALUES (1,'Dr. Smith','City X','Family Medicine'); INSERT INTO HealthcareProviders (Id,Name,Location,Specialty) VALUES (2,'Dr. Johnson','City X','Cardiology');
UPDATE HealthcareProviders SET Location = 'City Y' WHERE Name = 'Dr. Johnson';
List all the farms in the European region that have a yield per acre for wheat that is at least 15% higher than the average yield per acre for wheat in the entire database.
CREATE TABLE Farm (id INT,name TEXT,crop TEXT,yield_per_acre FLOAT,region TEXT); INSERT INTO Farm (id,name,crop,yield_per_acre,region) VALUES (1,'Jansen Farm','Wheat',180,'European'),(2,'Schmidt Farm','Rye',160,'European'),(3,'Garcia Farm','Wheat',210,'European'); CREATE TABLE Average (crop TEXT,avg_yield FLOAT); INSERT INTO Average (crop,avg_yield) VALUES ('Wheat',170);
SELECT * FROM Farm WHERE region = 'European' AND crop = 'Wheat' AND yield_per_acre >= (SELECT 1.15 * avg_yield FROM Average WHERE crop = 'Wheat');
List all the unique 'Crop Varieties' for each 'Farm' in 'Asia' in 2022?
CREATE TABLE farms (id INT,name TEXT,location TEXT,last_inspection_date DATE); INSERT INTO farms (id,name,location,last_inspection_date) VALUES (1,'Farm A','Asia','2022-01-01'); INSERT INTO farms (id,name,location,last_inspection_date) VALUES (2,'Farm B','Asia','2022-01-02'); CREATE TABLE crops (id INT,name TEXT,variety TEXT,farm_id INT,last_harvest_date DATE); INSERT INTO crops (id,name,variety,farm_id,last_harvest_date) VALUES (1,'Rice','Japonica',1,'2022-03-01'); INSERT INTO crops (id,name,variety,farm_id,last_harvest_date) VALUES (2,'Rice','Indica',2,'2022-03-02');
SELECT DISTINCT c.variety, f.name as farm_name FROM crops c INNER JOIN farms f ON c.farm_id = f.id WHERE f.location = 'Asia' AND c.last_harvest_date BETWEEN '2022-01-01' AND '2022-12-31';
Show the number of urban agriculture initiatives in each region and the average budget.
CREATE TABLE urban_agriculture_initiatives (initiative_name VARCHAR(255),region VARCHAR(255),budget FLOAT);
SELECT region, COUNT(initiative_name) as num_initiatives, AVG(budget) as avg_budget FROM urban_agriculture_initiatives GROUP BY region;
What is the maximum total production, in metric tons, of any crop type in the 'urban_crops' table?
CREATE TABLE urban_crops (id INT,crop_name VARCHAR(50),yield_mt_ha INT,area_ha INT); INSERT INTO urban_crops (id,crop_name,yield_mt_ha,area_ha) VALUES (1,'Rice',5,800),(2,'Soybeans',3.5,900),(3,'Corn',4,700);
SELECT MAX(production_mt) as max_production_mt FROM (SELECT crop_name, SUM(yield_mt_ha * area_ha * 0.01) as production_mt FROM urban_crops GROUP BY crop_name) as subquery;
Which farmers have more than 10 years of experience in the agriculture database?
CREATE TABLE Farmers (id INT,name VARCHAR,location VARCHAR,years_of_experience INT); INSERT INTO Farmers (id,name,location,years_of_experience) VALUES (1,'Jamila Brown','Nairobi',12),(2,'Eduardo Rodriguez','Mexico City',20),(3,'Tran Nguyen','Ho Chi Minh City',10),(4,'Elif Kaya','Ankara',8),(5,'Liam Johnson','Sydney',15);
SELECT name FROM Farmers WHERE years_of_experience > 10;
What is the maximum budget allocated for disability support programs in the 'East Coast' region?
CREATE TABLE DisabilitySupportPrograms (region VARCHAR(20),budget DECIMAL(5,2)); INSERT INTO DisabilitySupportPrograms (region,budget) VALUES ('East Coast',150000.00),('West Coast',200000.00),('Midwest',120000.00),('South',180000.00);
SELECT MAX(budget) FROM DisabilitySupportPrograms WHERE region = 'East Coast';
What is the total number of students and staff with accommodations in the "disability_services" schema, excluding the "accessibility_parking" type?
CREATE SCHEMA disability_services; CREATE TABLE staff (id INT,name VARCHAR(50),accommodation VARCHAR(50)); CREATE TABLE students (id INT,name VARCHAR(50),accommodation VARCHAR(50));
SELECT COUNT(*) FROM disability_services.staff WHERE accommodation != 'accessibility_parking' UNION SELECT COUNT(*) FROM disability_services.students WHERE accommodation != 'accessibility_parking';
What are the climate change impacts on marine species in the Southern Ocean?
CREATE TABLE marine_species_southern_ocean (species_name VARCHAR(255),habitat VARCHAR(255)); INSERT INTO marine_species_southern_ocean (species_name,habitat) VALUES ('Ross Seal','Southern Ocean'),('Crabeater Seal','Southern Ocean'); CREATE TABLE climate_change_impacts_southern_ocean (species_name VARCHAR(255),impacts TEXT); INSERT INTO climate_change_impacts_southern_ocean (species_name,impacts) VALUES ('Ross Seal','Sea ice reduction'),('Crabeater Seal','Changes in prey distribution');
SELECT m.species_name, c.impacts FROM marine_species_southern_ocean m INNER JOIN climate_change_impacts_southern_ocean c ON m.species_name = c.species_name WHERE m.habitat = 'Southern Ocean';
What is the minimum and maximum ocean acidification pH level for each marine region?
CREATE TABLE marine_region (id INT,region_name VARCHAR(50),min_ocean_ph FLOAT,max_ocean_ph FLOAT); INSERT INTO marine_region (id,region_name,min_ocean_ph,max_ocean_ph) VALUES (1,'Atlantic Ocean',7.5,8.1),(2,'Pacific Ocean',7.6,8.2);
SELECT region_name, MIN(min_ocean_ph) AS min_ocean_ph, MAX(max_ocean_ph) AS max_ocean_ph FROM marine_region GROUP BY region_name;
What is the total price of all products?
CREATE TABLE products (id INT,company VARCHAR(255),price DECIMAL(5,2)); INSERT INTO products (id,company,price) VALUES (1,'ABC',50.99),(2,'DEF',35.49),(3,'GHI',65.99),(4,'JKL',25.99);
SELECT SUM(price) FROM products;
Delete all community policing records with a community_policing_id greater than 5 from the 'community_policing' table
CREATE TABLE community_policing (community_policing_id INT,is_active BOOLEAN);
DELETE FROM community_policing WHERE community_policing_id > 5;
Find the crime types with the highest and lowest clearance rates overall.
CREATE TABLE crimes (crime_id INT,type VARCHAR(255),clearance_rate FLOAT);
SELECT c.type, AVG(c.clearance_rate) FROM crimes c GROUP BY c.type ORDER BY AVG(c.clearance_rate) DESC, c.type LIMIT 1; SELECT c.type, AVG(c.clearance_rate) FROM crimes c GROUP BY c.type ORDER BY AVG(c.clearance_rate) ASC, c.type LIMIT 1;
What is the average attendance for theater events in Africa, and how many countries on the continent have hosted such events?
CREATE TABLE events (id INT,name VARCHAR(50),year INT,location VARCHAR(50),type VARCHAR(20)); INSERT INTO events (id,name,year,location,type) VALUES (1,'Event1',2015,'Paris','Art'),(2,'Event2',2016,'London','Music'),(3,'Event3',2017,'Beijing','Theater'),(4,'Event4',2018,'Tokyo','Art'),(5,'Event5',2019,'Nairobi','Theater');
SELECT AVG(attendance) as avg_attendance, COUNT(DISTINCT country) as country_count FROM (SELECT COUNT(*) as attendance, SUBSTRING_INDEX(location, ' ', 1) as country FROM events WHERE type = 'Theater' GROUP BY location) as subquery;
What is the total number of artworks donated by individuals and corporations?
CREATE TABLE Donors (donor_id INT,donor_type VARCHAR(10),num_artworks INT); INSERT INTO Donors (donor_id,donor_type,num_artworks) VALUES (1,'Individual',30),(2,'Corporation',50);
SELECT SUM(num_artworks) FROM Donors WHERE donor_type IN ('Individual', 'Corporation');
Summarize defense diplomacy events by type and year
CREATE TABLE defense_diplomacy (id INT,event_type VARCHAR(50),year INT); INSERT INTO defense_diplomacy (id,event_type,year) VALUES (1,'Military Exercise',2018),(2,'Military Exercise',2019),(3,'Military Sale',2018),(4,'Defense Agreement',2019);
SELECT year, event_type, COUNT(*) as num_events FROM defense_diplomacy GROUP BY year, event_type;
Find the total assets of customers who have invested in stock 'ABC'
CREATE TABLE customers (id INT,name VARCHAR(50),asset_value FLOAT); INSERT INTO customers (id,name,asset_value) VALUES (1,'John Doe',50000.00),(2,'Jane Smith',75000.00); CREATE TABLE investments (customer_id INT,stock_symbol VARCHAR(10),quantity INT); INSERT INTO investments (customer_id,stock_symbol) VALUES (1,'ABC'),(1,'XYZ'),(2,'ABC');
SELECT SUM(asset_value) FROM customers c JOIN investments i ON c.id = i.customer_id WHERE i.stock_symbol = 'ABC';
What is the difference in total assets between customers who have invested in mutual funds and those who have not?
CREATE TABLE customers (customer_id INT,name VARCHAR(50),age INT,gender VARCHAR(10),total_assets DECIMAL(10,2)); INSERT INTO customers (customer_id,name,age,gender,total_assets) VALUES (1,'John Doe',35,'Male',50000.00),(2,'Jane Smith',45,'Female',75000.00),(3,'Bob Johnson',50,'Male',60000.00); CREATE TABLE investments (customer_id INT,investment_type VARCHAR(20),value DECIMAL(10,2)); INSERT INTO investments (customer_id,investment_type,value) VALUES (1,'Stocks',30000.00),(1,'Bonds',20000.00),(2,'Stocks',50000.00),(2,'Mutual Funds',25000.00),(3,'Stocks',40000.00),(3,'Bonds',20000.00);
SELECT SUM(c.total_assets) - subquery.total_assets FROM customers c RIGHT JOIN (SELECT SUM(total_assets) as total_assets FROM customers c INNER JOIN investments i ON c.customer_id = i.customer_id WHERE i.investment_type = 'Mutual Funds') subquery ON 1=1;
What is the total investment per client for each investment type?
CREATE TABLE clients (client_id INT,name TEXT,investment_type TEXT,investment FLOAT); INSERT INTO clients (client_id,name,investment_type,investment) VALUES (1,'John Doe','Stocks',3000.00),(1,'John Doe','Bonds',2000.00),(2,'Jane Smith','Stocks',5000.00);
SELECT client_id, name, investment_type, SUM(investment) OVER (PARTITION BY client_id, investment_type ORDER BY client_id) as total_investment FROM clients;
When did the first fraud alert occur?
CREATE TABLE fraud_alerts (id INT,account_number VARCHAR(20),alert_type VARCHAR(20),alert_date DATE); INSERT INTO fraud_alerts (id,account_number,alert_type,alert_date) VALUES (1,'1234567890','Suspicious Activity','2022-01-01'); INSERT INTO fraud_alerts (id,account_number,alert_type,alert_date) VALUES (2,'0987654321','Identity Theft','2022-01-02');
SELECT MIN(alert_date) FROM fraud_alerts;
List the number of hospitals in each state that have a rural healthcare facility.
CREATE TABLE hospitals (hospital_id INT,name VARCHAR(50),state VARCHAR(20),num_rural_facilities INT);
SELECT state, COUNT(*) FROM hospitals WHERE num_rural_facilities > 0 GROUP BY state;
What is the difference in the number of mental health facilities between rural and urban areas?
CREATE TABLE mental_health_facilities (id INT,name VARCHAR(50),area VARCHAR(10)); INSERT INTO mental_health_facilities (id,name,area) VALUES (1,'Facility A','Rural'),(2,'Facility B','Urban'),(3,'Facility C','Rural'),(4,'Facility D','Urban');
SELECT SUM(CASE WHEN area = 'Rural' THEN 1 ELSE 0 END) - SUM(CASE WHEN area = 'Urban' THEN 1 ELSE 0 END) AS difference FROM mental_health_facilities;
Which military technologies have been updated in the past year, and what were the previous specifications?
CREATE TABLE military_tech (id INT,tech VARCHAR(50),specs VARCHAR(50),update_date DATE); INSERT INTO military_tech (id,tech,specs,update_date) VALUES (1,'Drones','Speed: 200 mph,Range: 500 miles','2021-01-01'),(2,'Drones','Speed: 250 mph,Range: 600 miles','2022-01-01'),(3,'Artificial Intelligence','Algorithmic processing capability: 90%,Memory: 1 TB','2021-01-01'),(4,'Artificial Intelligence','Algorithmic processing capability: 95%,Memory: 2 TB','2022-01-01');
SELECT a.tech, a.specs as previous_specs, b.specs as updated_specs FROM military_tech a INNER JOIN military_tech b ON a.tech = b.tech WHERE a.update_date = (SELECT MAX(update_date) FROM military_tech c WHERE c.tech = a.tech AND c.update_date < b.update_date);
Find the minimum production rate of wells in the 'Mediterranean Sea' and the 'Black 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 (19,'Well S','Mediterranean Sea',3000),(20,'Well T','Mediterranean Sea',4000),(21,'Well U','Black Sea',5000),(22,'Well V','Black Sea',6000);
SELECT MIN(production_rate) FROM wells WHERE region IN ('Mediterranean Sea', 'Black Sea');
What is the highest number of hat-tricks scored by a player in a single Bundesliga season?
CREATE TABLE german_teams (team_id INT,team_name VARCHAR(50)); INSERT INTO german_teams (team_id,team_name) VALUES (1,'Bayern Munich'),(2,'Borussia Dortmund'),(3,'RB Leipzig'); CREATE TABLE german_matches (match_id INT,home_team_id INT,away_team_id INT,home_team_player_hat_tricks INT,away_team_player_hat_tricks INT); INSERT INTO german_matches (match_id,home_team_id,away_team_id,home_team_player_hat_tricks,away_team_player_hat_tricks) VALUES (1,1,2,1,0),(2,2,3,0,1),(3,3,1,1,0);
SELECT MAX(home_team_player_hat_tricks + away_team_player_hat_tricks) AS max_hat_tricks FROM german_matches;
List the number of refugee families, children, and their total age for each location.
CREATE TABLE refugee_families (id INT,location_id INT,family_size INT); CREATE TABLE refugee_children (id INT,family_id INT,age INT); CREATE TABLE locations (id INT,name VARCHAR(255));
SELECT l.name as location_name, COUNT(DISTINCT rf.id) as family_count, SUM(rc.age) as total_children_age FROM refugee_families rf INNER JOIN refugee_children rc ON rf.id = rc.family_id INNER JOIN locations l ON rf.location_id = l.id GROUP BY l.id;
What is the maximum number of bikes rented in 'park1' on weekends?
CREATE TABLE bike_rentals (location VARCHAR(20),day_of_week VARCHAR(10),bikes_rented INT); INSERT INTO bike_rentals (location,day_of_week,bikes_rented) VALUES ('park1','Saturday',15),('park1','Sunday',20),('park2','Friday',10);
SELECT MAX(bikes_rented) FROM bike_rentals WHERE location = 'park1' AND day_of_week IN ('Saturday', 'Sunday');
What is the standard deviation of ad spend for campaigns targeting 'Africa', in the current quarter?
CREATE TABLE campaigns (id INT,name TEXT,target_region TEXT,start_date DATETIME,end_date DATETIME,ad_spend DECIMAL(10,2));
SELECT STD(ad_spend) FROM campaigns WHERE target_region = 'Africa' AND start_date <= NOW() AND end_date >= DATE_SUB(DATE_FORMAT(NOW(), '%Y-%m-01'), INTERVAL 3 MONTH);
Delete the record for a socially responsible loan.
CREATE TABLE loans (id INT,loan_type VARCHAR(255),balance DECIMAL(10,2)); INSERT INTO loans (id,loan_type,balance) VALUES (1,'Conventional',800.00),(2,'Socially Responsible',1000.00);
DELETE FROM loans WHERE loan_type = 'Socially Responsible';
What is the name and total donation for the bottom 2 donors, ordered by total donation in ascending order?
CREATE TABLE donors (id INT,name VARCHAR(50),total_donation FLOAT); INSERT INTO donors (id,name,total_donation) VALUES (1,'John Doe',500.00),(2,'Jane Smith',350.00),(3,'Mike Johnson',200.00);
SELECT name, total_donation FROM (SELECT name, total_donation, ROW_NUMBER() OVER (ORDER BY total_donation ASC) as rank FROM donors) as subquery WHERE rank <= 2;
Calculate the total calories for each cuisine
CREATE TABLE cuisine (cuisine_id INT,name VARCHAR(20)); INSERT INTO cuisine (cuisine_id,name) VALUES (1,'italian'),(2,'chinese'),(3,'indian'); CREATE TABLE dishes (dish_id INT,name VARCHAR(50),cuisine_id INT,calories INT); INSERT INTO dishes (dish_id,name,cuisine_id,calories) VALUES (1,'pizza margherita',1,500),(2,'lasagna',1,600),(3,'fried rice',2,700),(4,'chicken curry',3,800),(5,'vegetable biryani',3,900);
SELECT cuisine.name, SUM(dishes.calories) as total_calories FROM cuisine JOIN dishes ON cuisine.cuisine_id = dishes.cuisine_id GROUP BY cuisine.name;
What is the average weight of return shipments from the 'TX' warehouse?
CREATE TABLE warehouse (id INT,name VARCHAR(20)); CREATE TABLE shipment (id INT,warehouse_id INT,weight FLOAT,is_return BOOLEAN); INSERT INTO warehouse VALUES (1,'LA'),(2,'NY'),(3,'TX'); INSERT INTO shipment VALUES (1,1,50.3,FALSE),(2,2,60.2,TRUE),(3,3,45.1,TRUE),(4,1,70.4,TRUE);
SELECT AVG(shipment.weight) FROM shipment INNER JOIN warehouse ON shipment.warehouse_id = warehouse.id WHERE warehouse.name = 'TX' AND shipment.is_return = TRUE;
What is the average funding per startup, partitioned by country and year?
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255),year INT,funding DECIMAL(10,2)); INSERT INTO biotech.startups (id,name,country,year,funding) VALUES (1,'StartupA','USA',2018,5000000.00),(2,'StartupB','Canada',2020,3000000.00),(3,'StartupC','USA',2019,7000000.00),(4,'StartupD','Germany',2021,4000000.00);
SELECT country, AVG(funding) AS avg_funding FROM biotech.startups WINDOW W AS (PARTITION BY country, year ORDER BY funding ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) GROUP BY country, W.year ORDER BY avg_funding DESC;
Identify the number of open data initiatives in the European Union in 2020
CREATE TABLE open_data (id INT PRIMARY KEY,country VARCHAR(20),year INT,num_initiatives INT); INSERT INTO open_data (id,country,year,num_initiatives) VALUES (1,'France',2020,25); INSERT INTO open_data (id,country,year,num_initiatives) VALUES (2,'Germany',2020,35);
SELECT SUM(num_initiatives) FROM open_data WHERE country IN ('France', 'Germany', 'Italy', 'Spain', 'Poland') AND year = 2020;
What is the total number of green buildings and their total floor area, categorized by energy efficiency rating and city?
CREATE TABLE Cities (CityID int,CityName varchar(50)); CREATE TABLE EnergyEfficiencyRatings (RatingID int,RatingName varchar(50)); CREATE TABLE GreenBuildings (BuildingID int,CityID int,RatingID int,FloorArea int);
SELECT Cities.CityName, EnergyEfficiencyRatings.RatingName, COUNT(GreenBuildings.BuildingID) as TotalBuildings, SUM(GreenBuildings.FloorArea) as TotalFloorArea FROM Cities INNER JOIN GreenBuildings ON Cities.CityID = GreenBuildings.CityID INNER JOIN EnergyEfficiencyRatings ON GreenBuildings.RatingID = EnergyEfficiencyRatings.RatingID GROUP BY Cities.CityName, EnergyEfficiencyRatings.RatingName;
How many hotels have a sustainability score above 80?
CREATE TABLE economic_impact (hotel_id INT,local_employment INT); INSERT INTO economic_impact (hotel_id,local_employment) VALUES (1,25),(2,30);
SELECT COUNT(*) FROM sustainable_tourism st WHERE st.sustainability_score > 80;
Which districts in Barcelona have more than 5 local artisans?
CREATE TABLE local_artisans (artisan_id INT,name TEXT,district TEXT); INSERT INTO local_artisans (artisan_id,name,district) VALUES (1,'Marta','Gothic Quarter'),(2,'Pedro','El Raval'),(3,'Ana','Gothic Quarter'),(4,'Juan','El Raval'),(5,'Lucia','Gothic Quarter'),(6,'Pablo','El Born');
SELECT district, COUNT(*) FROM local_artisans GROUP BY district HAVING COUNT(*) > 5;
What are the total number of hotels and unique countries in the hotel_data table?
CREATE TABLE hotel_data (hotel_id INT,hotel_name TEXT,country TEXT,stars INT); INSERT INTO hotel_data (hotel_id,hotel_name,country,stars) VALUES (1,'Park Hotel','Switzerland',5),(2,'Four Seasons','Canada',5),(3,'The Plaza','USA',4);
SELECT COUNT(DISTINCT hotel_id) as total_hotels, COUNT(DISTINCT country) as unique_countries FROM hotel_data;
What is the average population of species in the Pacific region?
CREATE TABLE Species (id INT,name VARCHAR(50),population INT,region VARCHAR(50),last_seen DATETIME); INSERT INTO Species (id,name,population,region,last_seen) VALUES (5,'Polar Bear',4000,'Arctic','2020-02-01'),(6,'Arctic Fox',1500,'Pacific','2019-06-10');
SELECT region, AVG(population) as avg_population FROM Species WHERE region = 'Pacific' GROUP BY region;
Who are the instructors that have taught traditional art courses in South America?
CREATE TABLE Instructors (id INT,name VARCHAR(30),region VARCHAR(20)); CREATE TABLE Courses (instructor_id INT,location VARCHAR(20),course_type VARCHAR(20));
SELECT I.name FROM Instructors I JOIN Courses C ON I.id = C.instructor_id WHERE I.region = 'South America' AND C.course_type = 'traditional art';
How many patients had a reduction in symptoms after taking medication X in 2021?
CREATE TABLE patient_outcomes (patient_id INT,medication VARCHAR(20),year INT,symptom_reduction INT); INSERT INTO patient_outcomes VALUES (1,'Medication X',2021,1),(2,'Medication X',2021,0),(3,'Medication X',2021,1);
SELECT COUNT(*) FROM patient_outcomes WHERE medication = 'Medication X' AND year = 2021 AND symptom_reduction = 1;
How many tourists visited North America from each continent in 2019?
CREATE TABLE tourists (id INT,continent VARCHAR(50),country VARCHAR(50),visitors INT,year INT); INSERT INTO tourists (id,continent,country,visitors,year) VALUES (1,'North America','Canada',2000,2019),(2,'North America','USA',3000,2019),(3,'South America','Brazil',500,2019),(4,'Europe','France',1000,2019);
SELECT t1.continent, SUM(t2.visitors) FROM tourists t1 INNER JOIN tourists t2 ON t1.year = t2.year WHERE t1.continent != t2.continent AND t2.continent = 'North America' AND t1.year = 2019 GROUP BY t1.continent;
Calculate the number of days since the last inspection for power plants, specifically those with more than 60 days since the last inspection.
CREATE TABLE PollutionSources (SourceID INT,SourceName NVARCHAR(50),Type NVARCHAR(50),LastInspection DATETIME); INSERT INTO PollutionSources (SourceID,SourceName,Type,LastInspection) VALUES (1,'Oil Rig Alpha','Oil Rig','2021-05-12 14:00:00'); INSERT INTO PollutionSources (SourceID,SourceName,Type,LastInspection) VALUES (2,'Coal Power Plant Beta','Power Plant','2021-03-04 08:30:00');
SELECT SourceID, SourceName, DATEDIFF(day, LastInspection, GETDATE()) as DaysSinceInspection FROM PollutionSources WHERE Type = 'Power Plant' AND DaysSinceInspection > 60
What are the names and locations of marine protected areas (MPAs) in the Arctic Ocean and their year of establishment?
CREATE TABLE ArcticMPA (mpa_name VARCHAR(50),location VARCHAR(50),year_established INT,PRIMARY KEY(mpa_name)); INSERT INTO ArcticMPA (mpa_name,location,year_established) VALUES ('Arctic MPA 1','Arctic Ocean',2010),('Arctic MPA 2','Arctic Ocean',2015);
SELECT ArcticMPA.mpa_name, ArcticMPA.location, ArcticMPA.year_established FROM ArcticMPA WHERE ArcticMPA.region = 'Arctic Ocean';
List the dishes that have never been sold
CREATE TABLE dishes (dish_id INT,dish_name VARCHAR(255),price DECIMAL(5,2)); INSERT INTO dishes (dish_id,dish_name,price) VALUES (1,'Margherita Pizza',12.99),(2,'Chicken Alfredo',15.99),(3,'Caesar Salad',9.99); CREATE TABLE sales (sale_id INT,sale_date DATE,dish_id INT,quantity INT); INSERT INTO sales (sale_id,sale_date,dish_id,quantity) VALUES (1,'2022-01-01',1,2),(2,'2022-01-01',2,1),(3,'2022-01-02',3,3);
SELECT d.dish_name FROM dishes d LEFT JOIN sales s ON d.dish_id = s.dish_id WHERE s.dish_id IS NULL;
Delete military equipment sales records with a value less than 1000000 from the year 2019.
CREATE TABLE Military_Equipment_Sales(id INT,country VARCHAR(255),year INT,value FLOAT); INSERT INTO Military_Equipment_Sales(id,country,year,value) VALUES (1,'India',2020,50000000),(2,'India',2019,4500000),(3,'US',2020,80000000),(4,'India',2018,40000000),(5,'US',2019,75000000),(6,'China',2020,60000000),(7,'China',2019,55000000),(8,'US',2018,70000000);
DELETE FROM Military_Equipment_Sales WHERE year = 2019 AND value < 1000000;
What is the total value of military equipment sales to all countries?
CREATE TABLE military_sales (id INT,country VARCHAR,value FLOAT); INSERT INTO military_sales (id,country,value) VALUES (1,'Canada',5000000),(2,'Mexico',3000000),(3,'Canada',7000000);
SELECT SUM(value) FROM military_sales;
What is the total amount of resources depleted for each mining site?
CREATE TABLE MiningSites (SiteID INT,SiteName VARCHAR(50),Location VARCHAR(50),EnvironmentalImpactScore INT,ResourcesDepleted FLOAT);
SELECT SiteName, SUM(ResourcesDepleted) FROM MiningSites GROUP BY SiteName;
Delete a broadband plan from the broadband_plans table
CREATE TABLE broadband_plans (plan_id INT,plan_name VARCHAR(50),download_speed INT,upload_speed INT,price DECIMAL(5,2),contract_length INT,created_at TIMESTAMP);
DELETE FROM broadband_plans WHERE plan_id = 3001;
Find the average donation amount per month, per donor, in descending order of the average donation amount?
CREATE TABLE Donations (DonationID int,DonorID int,DonationAmount decimal(10,2),DonationDate date); INSERT INTO Donations (DonationID,DonorID,DonationAmount,DonationDate) VALUES (1,1,500.00,'2022-01-01'),(2,1,800.00,'2022-02-01'),(3,2,300.00,'2022-01-01'),(4,3,700.00,'2022-01-01');
SELECT DonorID, AVG(DonationAmount) OVER (PARTITION BY EXTRACT(MONTH FROM DonationDate), EXTRACT(YEAR FROM DonationDate) ORDER BY EXTRACT(MONTH FROM DonationDate), EXTRACT(YEAR FROM DonationDate)) AS AvgDonationPerMonth FROM Donations GROUP BY DonorID ORDER BY AvgDonationPerMonth DESC;
What is the average score of players from the USA?
CREATE TABLE Players (PlayerID int,PlayerName varchar(50),Score int,Country varchar(50)); INSERT INTO Players (PlayerID,PlayerName,Score,Country) VALUES (1,'John Doe',90,'USA'),(2,'Jane Smith',80,'Canada');
SELECT AVG(Score) FROM Players WHERE Country = 'USA';
What is the average score of players who joined after 2020-01-01, grouped by game_id?
CREATE TABLE games (game_id INT,name VARCHAR(100),release_date DATE); INSERT INTO games (game_id,name,release_date) VALUES (1,'Game1','2019-06-01'),(2,'Game2','2020-03-15'),(3,'Game3','2018-12-20'); CREATE TABLE player_scores (player_id INT,game_id INT,score INT,join_date DATE); INSERT INTO player_scores (player_id,game_id,score,join_date) VALUES (1,1,85,'2019-07-01'),(2,1,90,'2020-02-01'),(3,2,75,'2020-03-16'),(4,2,80,'2021-01-05'),(5,3,95,'2018-12-22'),(6,3,88,'2019-01-01');
SELECT s.game_id, AVG(s.score) AS avg_score FROM player_scores s JOIN games g ON s.game_id = g.game_id WHERE s.join_date > '2020-01-01' GROUP BY s.game_id;
What is the most popular game by age group?
CREATE TABLE player (player_id INT,player_name VARCHAR(50),age INT,game_title VARCHAR(50)); INSERT INTO player (player_id,player_name,age,game_title) VALUES (1,'John Doe',25,'League of Legends'); INSERT INTO player (player_id,player_name,age,game_title) VALUES (2,'Jane Smith',30,'Mario Kart'); INSERT INTO player (player_id,player_name,age,game_title) VALUES (3,'Bob Johnson',35,'League of Legends');
SELECT age, game_title, COUNT(*) as play_count FROM player GROUP BY age, game_title ORDER BY play_count DESC;
Show the number of public schools in each state and the percentage of schools with a student population over 500
CREATE TABLE schools (school_id INT PRIMARY KEY,school_name TEXT,school_type TEXT,state_id INT,num_students INT);CREATE TABLE states (state_id INT PRIMARY KEY,state_name TEXT);
SELECT s.state_name, COUNT(s.school_name), AVG(CASE WHEN s.num_students > 500 THEN 1 ELSE 0 END) * 100 as percentage FROM schools s INNER JOIN states st ON s.state_id = st.state_id GROUP BY s.state_name;
How many units of lanthanum were extracted in India in 2018?
CREATE TABLE india_lanthanum (id INT,year INT,units INT); INSERT INTO india_lanthanum (id,year,units) VALUES (1,2016,1000),(2,2017,1200),(3,2018,1400);
SELECT COUNT(*) FROM india_lanthanum WHERE year = 2018;
Calculate the total CO2 emissions (in metric tons) per capita for each country in the population_data and carbon_emissions tables.
CREATE TABLE population_data (country VARCHAR(50),year INT,population INT); CREATE TABLE carbon_emissions (country VARCHAR(50),year INT,co2_emissions FLOAT);
SELECT p.country, AVG(co2_emissions/population*1000000) as co2_emissions_per_capita FROM population_data p JOIN carbon_emissions c ON p.country = c.country GROUP BY p.country;
Find total carbon offsets achieved by projects in 'GreenProjects' table, with a budget over $100,000,000?
CREATE TABLE GreenProjects (project_id INT,name VARCHAR(100),budget INT,carbon_offsets_achieved INT);
SELECT SUM(carbon_offsets_achieved) FROM GreenProjects WHERE budget > 100000000;
What is the average energy efficiency of hydro projects in Africa?
CREATE TABLE project (id INT,name TEXT,location TEXT,project_type TEXT,energy_efficiency FLOAT); INSERT INTO project (id,name,location,project_type,energy_efficiency) VALUES (1,'Hydro Dam','Africa','Hydro',0.55);
SELECT AVG(energy_efficiency) FROM project WHERE location = 'Africa' AND project_type = 'Hydro';
Delete 'Pizzeria Yum' from the 'restaurants' table
CREATE TABLE restaurants (name TEXT,revenue FLOAT); INSERT INTO restaurants (name,revenue) VALUES ('Pizzeria Spumoni',15000.0),('Pizzeria Yum',18000.0);
DELETE FROM restaurants WHERE name = 'Pizzeria Yum';
What is the total revenue of restaurants serving Italian cuisine?
CREATE TABLE Restaurants (id INT,name VARCHAR(50),type VARCHAR(20)); CREATE TABLE Menu (id INT,restaurant_id INT,dish VARCHAR(50),category VARCHAR(20),price DECIMAL(5,2)); INSERT INTO Restaurants (id,name,type) VALUES (1,'PastaPalace','Italian'); INSERT INTO Menu (id,restaurant_id,dish,category,price) VALUES (1,1,'Lasagna','Italian',12.99);
SELECT SUM(price) FROM Menu JOIN Restaurants ON Menu.restaurant_id = Restaurants.id WHERE Restaurants.type = 'Italian';
Calculate the total sales by product category
CREATE TABLE sales (sale_id INT,product_id INT,product_category VARCHAR(255),sales FLOAT); INSERT INTO sales (sale_id,product_id,product_category,sales) VALUES (1,1,'Electronics',100),(2,2,'Clothing',200),(3,3,'Electronics',150);
SELECT product_category, SUM(sales) FROM sales GROUP BY product_category;
How many fans are from each continent in the fan_demographics table?
CREATE TABLE fan_demographics (fan_id INT,fan_name VARCHAR(255),country VARCHAR(255),continent VARCHAR(255)); INSERT INTO fan_demographics (fan_id,fan_name,country,continent) VALUES (1,'FanA','USA','North America'),(2,'FanB','Canada','North America'),(3,'FanC','Brazil','South America'),(4,'FanD','India','Asia');
SELECT continent, COUNT(fan_id) as num_fans FROM fan_demographics GROUP BY continent;
How many security incidents were recorded in the 'security_incidents' table for each severity level?
CREATE TABLE security_incidents (id INT PRIMARY KEY,incident_name TEXT,severity TEXT,date_reported DATE);
SELECT severity, COUNT(*) FROM security_incidents GROUP BY severity;
What is the total number of security incidents and their average resolution time, broken down by month and year?
CREATE TABLE incidents (id INT,incident_date DATE,resolution_time INT); INSERT INTO incidents (id,incident_date,resolution_time) VALUES (1,'2021-04-01',5); INSERT INTO incidents (id,incident_date,resolution_time) VALUES (2,'2021-07-15',7); INSERT INTO incidents (id,incident_date,resolution_time) VALUES (3,'2021-10-02',3);
SELECT YEAR(incident_date) as year, MONTH(incident_date) as month, COUNT(*) as num_incidents, AVG(resolution_time) as avg_resolution_time FROM incidents GROUP BY year, month;
How many autonomous buses were operational in Mexico City as of January 1, 2022?
CREATE TABLE autonomous_buses(bus_id INT,operational_status VARCHAR(50),status_date DATE,city VARCHAR(50));
SELECT COUNT(*) FROM autonomous_buses WHERE operational_status = 'operational' AND status_date <= '2022-01-01' AND city = 'Mexico City';
What is the minimum ride duration for ride-hailing services in Singapore?
CREATE TABLE ride_hailing (ride_id INT,ride_duration INT); INSERT INTO ride_hailing (ride_id,ride_duration) VALUES (1,10),(2,15),(3,20),(4,25);
SELECT MIN(ride_duration) as min_duration FROM ride_hailing;
List the names of unions in the 'hospitality' sector that have more than 500 members and their respective collective bargaining agreements.
CREATE TABLE hospitality_unions (id INT,name TEXT,sector TEXT,collective_bargaining_agreement TEXT,member_count INT);
SELECT name, collective_bargaining_agreement FROM hospitality_unions WHERE sector = 'hospitality' AND member_count > 500;
How many electric vehicles have been sold in California in the past year?
CREATE TABLE Sales (id INT,vehicle_id INT,quantity INT,date DATE); CREATE TABLE Vehicles (id INT,make VARCHAR(50),model VARCHAR(50),type VARCHAR(50)); INSERT INTO Sales (id,vehicle_id,quantity,date) VALUES (1,1,100,'2021-01-01'); INSERT INTO Vehicles (id,make,model,type) VALUES (1,'Tesla','Model 3','Electric');
SELECT SUM(quantity) FROM Sales INNER JOIN Vehicles ON Sales.vehicle_id = Vehicles.id WHERE type = 'Electric' AND date >= DATEADD(year, -1, GETDATE());
List all auto shows in the USA with electric vehicle participation.
CREATE TABLE AutoShows (Id INT,Name VARCHAR(50),Location VARCHAR(50),Date DATE); CREATE TABLE ElectricVehicles (Id INT,Name VARCHAR(50),AutoShowId INT); INSERT INTO AutoShows (Id,Name,Location,Date) VALUES (1,'New York Auto Show','New York','2022-04-15'),(2,'Los Angeles Auto Show','California','2022-11-19'); INSERT INTO ElectricVehicles (Id,Name,AutoShowId) VALUES (1,'Tesla Model S',1),(2,'Nissan Leaf',1),(3,'Audi e-Tron',2);
SELECT AutoShows.Name FROM AutoShows INNER JOIN ElectricVehicles ON AutoShows.Id = ElectricVehicles.AutoShowId WHERE Location = 'USA';
What is the average safety rating for electric vehicles released in 2020?
CREATE TABLE Vehicles (Id INT,Name VARCHAR(100),Type VARCHAR(50),SafetyRating FLOAT,ReleaseYear INT); INSERT INTO Vehicles (Id,Name,Type,SafetyRating,ReleaseYear) VALUES (1,'Model S','Electric',5.2,2020); INSERT INTO Vehicles (Id,Name,Type,SafetyRating,ReleaseYear) VALUES (2,'Leaf','Electric',4.8,2020);
SELECT AVG(SafetyRating) FROM Vehicles WHERE Type = 'Electric' AND ReleaseYear = 2020;
Show the number of trips taken by vessels in a given time period
VESSEL(vessel_id,last_maintenance_date); TRIP(voyage_id,trip_date,vessel_id)
SELECT v.vessel_id, COUNT(t.voyage_id) AS num_of_trips FROM VESSEL v JOIN TRIP t ON v.vessel_id = t.vessel_id WHERE t.trip_date BETWEEN v.last_maintenance_date AND DATEADD(day, 30, v.last_maintenance_date) GROUP BY v.vessel_id;
List the top 5 recycling centers by total waste recycled in the state of New York, sorted by recycling rate in descending order.
CREATE TABLE recycling_centers (id INT,center_name TEXT,state TEXT,total_waste_recycled INT,total_waste INT); INSERT INTO recycling_centers (id,center_name,state,total_waste_recycled,total_waste) VALUES (1,'Recycling Center A','New York',20000,30000),(2,'Recycling Center B','New York',15000,25000);
SELECT center_name, (total_waste_recycled / total_waste) * 100 AS recycling_rate FROM recycling_centers WHERE state = 'New York' GROUP BY center_name ORDER BY recycling_rate DESC LIMIT 5;
What is the total CO2 emission from waste incineration per city since Jan 1st, 2021?
CREATE TABLE Cities (id INT,city_name VARCHAR(255)); INSERT INTO Cities (id,city_name) VALUES (1,'CityA'),(2,'CityB'); CREATE TABLE IncinerationData (city_id INT,co2_emission INT,date DATE); INSERT INTO IncinerationData (city_id,co2_emission,date) VALUES (1,50,'2021-01-01'),(1,60,'2021-01-02'),(2,40,'2021-01-01'),(2,45,'2021-01-02');
SELECT Cities.city_name, SUM(IncinerationData.co2_emission) FROM Cities INNER JOIN IncinerationData ON Cities.id = IncinerationData.city_id WHERE date >= '2021-01-01' AND waste_type = 'incineration';
What is the total volume of water saved by water conservation initiatives in Rio de Janeiro, Brazil in 2019?
CREATE TABLE WaterConservationInitiatives_Rio (id INT,year INT,savings INT); INSERT INTO WaterConservationInitiatives_Rio (id,year,savings) VALUES (1,2019,1200000),(2,2018,1150000),(3,2017,1100000);
SELECT SUM(savings) FROM WaterConservationInitiatives_Rio WHERE year = 2019;
What is the total revenue generated from male members in the Midwest who used the cycling classes in the past 3 months?
CREATE TABLE Members (MemberID INT,Gender VARCHAR(10),Region VARCHAR(20),MembershipDate DATE); INSERT INTO Members (MemberID,Gender,Region,MembershipDate) VALUES (5,'Male','Midwest','2021-02-01'); CREATE TABLE Classes (ClassID INT,ClassType VARCHAR(20),Duration INT,MemberID INT); INSERT INTO Classes (ClassID,ClassType,Duration,MemberID) VALUES (50,'Cycling',60,5); CREATE TABLE Transactions (TransactionID INT,MemberID INT,Service VARCHAR(20),Amount DECIMAL(5,2)); INSERT INTO Transactions (TransactionID,MemberID,Service,Amount) VALUES (500,5,'Cycling',100.00);
SELECT SUM(Transactions.Amount) FROM Members INNER JOIN Classes ON Members.MemberID = Classes.MemberID INNER JOIN Transactions ON Members.MemberID = Transactions.MemberID WHERE Members.Gender = 'Male' AND Members.Region = 'Midwest' AND Classes.ClassType = 'Cycling' AND Transactions.TransactionDate BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND CURRENT_DATE;