instruction stringlengths 0 1.06k | input stringlengths 11 5.3k | response stringlengths 2 4.44k |
|---|---|---|
List the number of vessels and their average capacity by type in the 'shipping' schema. | CREATE TABLE shipping.vessels (id INT,name VARCHAR(50),type VARCHAR(50),capacity INT); INSERT INTO shipping.vessels (id,name,type,capacity) VALUES (1,'VesselA','Refrigerated',5000),(2,'VesselB','Dry Bulk',8000),(3,'VesselC','Refrigerated',6000),(4,'VesselD','Dry Bulk',9000); | SELECT type, AVG(capacity) FROM shipping.vessels GROUP BY type; |
Identify members who attended workout sessions in both January and February 2022. | CREATE TABLE Members (MemberID INT,FirstName VARCHAR(50),LastName VARCHAR(50)); INSERT INTO Members (MemberID,FirstName,LastName) VALUES (1,'John','Doe'); INSERT INTO Members (MemberID,FirstName,LastName) VALUES (2,'Jane','Doe'); CREATE TABLE Workouts (WorkoutID INT,MemberID INT,WorkoutDate DATE); INSERT INTO Workouts (WorkoutID,MemberID,WorkoutDate) VALUES (1,1,'2022-01-12'); INSERT INTO Workouts (WorkoutID,MemberID,WorkoutDate) VALUES (2,1,'2022-02-13'); INSERT INTO Workouts (WorkoutID,MemberID,WorkoutDate) VALUES (3,2,'2022-01-15'); | SELECT DISTINCT m.MemberID, m.FirstName, m.LastName FROM Members m INNER JOIN Workouts w1 ON m.MemberID = w1.MemberID INNER JOIN Workouts w2 ON m.MemberID = w2.MemberID WHERE w1.WorkoutDate >= '2022-01-01' AND w1.WorkoutDate < '2022-02-01' AND w2.WorkoutDate >= '2022-02-01' AND w2.WorkoutDate < '2022-03-01'; |
Determine the most expensive crop type and the farmer who grows it. | CREATE TABLE Farmers (id INT,name VARCHAR(50),age INT,location VARCHAR(50)); INSERT INTO Farmers (id,name,age,location) VALUES (1,'John Doe',35,'USA'); INSERT INTO Farmers (id,name,age,location) VALUES (2,'Jane Smith',40,'Canada'); CREATE TABLE Crops (id INT,farmer_id INT,crop_name VARCHAR(50),yield INT,sale_price DECIMAL(5,2)); INSERT INTO Crops (id,farmer_id,crop_name,yield,sale_price) VALUES (1,1,'Corn',120,2.35); INSERT INTO Crops (id,farmer_id,crop_name,yield,sale_price) VALUES (2,2,'Soybeans',80,3.50); | SELECT c.crop_name, MAX(c.sale_price) as max_price FROM Crops c JOIN Farmers f ON c.farmer_id = f.id GROUP BY c.crop_name HAVING MAX(c.sale_price) = (SELECT MAX(c2.sale_price) FROM Crops c2); |
What percentage of tourists visiting Sydney speak English? | CREATE TABLE language_stats (id INT,city VARCHAR(20),country VARCHAR(10),language VARCHAR(10),num_tourists INT); INSERT INTO language_stats (id,city,country,language,num_tourists) VALUES (1,'Sydney','Australia','English',50000),(2,'Sydney','China','Mandarin',20000),(3,'Sydney','USA','English',30000); | SELECT (SUM(CASE WHEN language = 'English' THEN num_tourists ELSE 0 END) * 100.0 / SUM(num_tourists)) AS percentage FROM language_stats WHERE city = 'Sydney'; |
List the military innovation patents filed by South Korea? | CREATE TABLE military_patents (country VARCHAR(50),patent_number INTEGER); INSERT INTO military_patents (country,patent_number) VALUES ('USA',12345),('USA',67890),('South Korea',78901),('UK',34567),('Canada',90123); | SELECT country, patent_number FROM military_patents WHERE country = 'South Korea'; |
What are the names and research interests of faculty members who have received grants from the 'National Science Foundation'? | CREATE TABLE Faculty (FacultyID int,Name varchar(50),ResearchInterest varchar(50)); INSERT INTO Faculty (FacultyID,Name,ResearchInterest) VALUES (1,'John Smith','Machine Learning'); INSERT INTO Faculty (FacultyID,Name,ResearchInterest) VALUES (2,'Jane Doe','Data Science'); CREATE TABLE Grants (GrantID int,Grantor varchar(50),FacultyID int); INSERT INTO Grants (GrantID,Grantor,FacultyID) VALUES (1,'National Science Foundation',1); INSERT INTO Grants (GrantID,Grantor,FacultyID) VALUES (2,'Microsoft Research',2); | SELECT Faculty.Name, Faculty.ResearchInterest FROM Faculty INNER JOIN Grants ON Faculty.FacultyID = Grants.FacultyID WHERE Grants.Grantor = 'National Science Foundation'; |
What is the total freight cost for the top 2 countries that imported the most goods from Africa in Q3 2022? | CREATE TABLE freight_costs (country VARCHAR(255),import_value DECIMAL(10,2),quarter INT,year INT); INSERT INTO freight_costs (country,import_value,quarter,year) VALUES ('China',15000.00,3,2022),('USA',12000.00,3,2022),('India',9000.00,3,2022); | SELECT f.country, SUM(f.import_value) as total_cost FROM freight_costs f WHERE f.quarter = 3 AND f.year = 2022 GROUP BY f.country ORDER BY total_cost DESC LIMIT 2; |
Insert a new record into the regulatory_compliance table with the following data: vessel_id 1301, compliance_status 'Compliant' | CREATE TABLE regulatory_compliance (id INT,vessel_id INT,compliance_status VARCHAR(20)); | INSERT INTO regulatory_compliance (vessel_id, compliance_status) VALUES (1301, 'Compliant'); |
List all mining operations that have depleted more than 500 units of resources in Q2 2021. | CREATE TABLE ResourcesDepleted (ResourceDepletedID INT,Operation VARCHAR(50),Quarter INT,Year INT,Quantity DECIMAL(10,2)); INSERT INTO ResourcesDepleted (ResourceDepletedID,Operation,Quarter,Year,Quantity) VALUES (1,'Coal',2,2021,550); INSERT INTO ResourcesDepleted (ResourceDepletedID,Operation,Quarter,Year,Quantity) VALUES (2,'Iron',2,2021,450); | SELECT Operation FROM ResourcesDepleted WHERE Quarter = 2 AND Year = 2021 AND Quantity > 500; |
What is the average temperature and humidity for each crop type in the current month, grouped by geographical regions? | CREATE TABLE crop (id INTEGER,type TEXT,temperature FLOAT,humidity FLOAT,date DATE,region_id INTEGER);CREATE TABLE region (id INTEGER,name TEXT); | SELECT r.name as region, c.type as crop, AVG(c.temperature) as avg_temp, AVG(c.humidity) as avg_hum FROM crop c INNER JOIN region r ON c.region_id = r.id WHERE c.date >= DATEADD(month, 0, DATEADD(day, DATEDIFF(day, 0, CURRENT_DATE), 0)) AND c.date < DATEADD(month, 1, DATEADD(day, DATEDIFF(day, 0, CURRENT_DATE), 0)) GROUP BY r.name, c.type; |
Identify researchers who have received funding for both Fair AI and Explainable AI projects. | CREATE TABLE ai_research_funding (id INT,researcher VARCHAR(255),project VARCHAR(255),amount FLOAT); INSERT INTO ai_research_funding (id,researcher,project,amount) VALUES (1,'Dana','Fair AI',50000),(2,'Eli','Explainable AI',75000),(3,'Fiona','Fair AI',60000),(4,'Dana','Explainable AI',80000); | SELECT researcher FROM ai_research_funding WHERE project IN ('Fair AI', 'Explainable AI') GROUP BY researcher HAVING COUNT(DISTINCT project) = 2; |
What is the maximum safety score for models developed in the US? | CREATE TABLE models (model_id INT,name VARCHAR(255),country VARCHAR(255),safety_score FLOAT); INSERT INTO models (model_id,name,country,safety_score) VALUES (1,'ModelA','USA',0.92),(2,'ModelB','Canada',0.88),(3,'ModelC','USA',0.95); | SELECT MAX(safety_score) FROM models WHERE country = 'USA'; |
Determine the annual trend of academic papers published per department from 2018 to 2021. | CREATE TABLE academic_papers_by_dept (paper_id INT,student_id INT,department TEXT,published_year INT); INSERT INTO academic_papers_by_dept (paper_id,student_id,department,published_year) VALUES (1,1,'Mathematics',2018),(2,2,'Computer Science',2019),(3,3,'Physics',2020),(4,4,'Mathematics',2019); | SELECT published_year, department, AVG(CASE WHEN published_year IS NOT NULL THEN 1.0 ELSE 0.0 END) as avg_papers_per_dept FROM academic_papers_by_dept GROUP BY published_year, department ORDER BY published_year; |
Find the average price of sustainable materials sourced from each country. | CREATE TABLE sustainable_materials (id INT,country VARCHAR(50),price DECIMAL(5,2)); INSERT INTO sustainable_materials (id,country,price) VALUES (1,'United States',15.99),(2,'Brazil',12.50); | SELECT country, AVG(price) FROM sustainable_materials GROUP BY country; |
What is the maximum number of fish in each sustainable fish farm in the Pacific ocean? | CREATE TABLE fish_farms (id INT,name TEXT,country TEXT,ocean TEXT,sustainable BOOLEAN,num_fish INT); INSERT INTO fish_farms (id,name,country,ocean,sustainable,num_fish) VALUES (1,'Farm A','Country A','Pacific',true,500),(2,'Farm B','Country B','Pacific',false,700),(3,'Farm C','Country A','Pacific',true,800); | SELECT sustainable, MAX(num_fish) FROM fish_farms WHERE ocean = 'Pacific' GROUP BY sustainable; |
How many marine mammals are found in the Pacific Ocean? | CREATE TABLE marine_mammals (name VARCHAR(255),location VARCHAR(255),population INT); INSERT INTO marine_mammals (name,location,population) VALUES ('Blue Whale','Pacific Ocean',2000),('Dolphin','Atlantic Ocean',1500),('Seal','Arctic Ocean',1000); | SELECT SUM(population) FROM marine_mammals WHERE location = 'Pacific Ocean'; |
What is the maximum funding for marine conservation in a single year? | CREATE TABLE marine_conservation_funding (year INT,funding INT); INSERT INTO marine_conservation_funding (year,funding) VALUES (2020,5000000),(2021,5500000),(2022,6000000); | SELECT MAX(funding) FROM marine_conservation_funding; |
What is the minimum price of promethium produced in Australia? | CREATE TABLE promethium_production (country VARCHAR(255),price DECIMAL(10,2)); INSERT INTO promethium_production (country,price) VALUES ('Australia',120.00); | SELECT MIN(price) FROM promethium_production WHERE country = 'Australia'; |
What is the maximum capacity of Wind Farms in Germany? | CREATE TABLE Wind_Farms (project_id INT,location VARCHAR(50),capacity FLOAT); INSERT INTO Wind_Farms (project_id,location,capacity) VALUES (1,'Germany',120.5),(2,'France',95.3),(3,'Germany',152.8),(4,'Spain',119.9); | SELECT MAX(capacity) FROM Wind_Farms WHERE location = 'Germany'; |
Determine the change in waste generation per quarter for Japan in 2020, compared to the previous quarter. | CREATE TABLE waste_generation (id INT,country VARCHAR(50),waste_amount FLOAT,quarter INT,year INT); INSERT INTO waste_generation (id,country,waste_amount,quarter,year) VALUES (1,'Japan',120000,1,2020),(2,'Japan',125000,2,2020),(3,'Japan',130000,3,2020),(4,'Japan',135000,4,2020); | SELECT LAG(waste_amount) OVER (PARTITION BY country ORDER BY year, quarter) + LAG(waste_amount) OVER (PARTITION BY country ORDER BY year, quarter) - waste_amount as diff FROM waste_generation WHERE country = 'Japan' AND year = 2020; |
Calculate the average amount of research grants awarded to graduate students in the "engineering" department | CREATE TABLE research_grants (id INT,student_id INT,department VARCHAR(255),amount FLOAT); INSERT INTO research_grants (id,student_id,department,amount) VALUES (1,1001,'engineering',50000.00),(2,1002,'biology',75000.00),(3,1003,'engineering',60000.00); CREATE TABLE graduate_students (id INT,name VARCHAR(255),department VARCHAR(255)); INSERT INTO graduate_students (id,name,department) VALUES (1001,'Alice','engineering'),(1002,'Bob','biology'),(1003,'Charlie','engineering'); | SELECT AVG(rg.amount) FROM research_grants rg INNER JOIN graduate_students gs ON rg.student_id = gs.id WHERE gs.department = 'engineering'; |
What is the total number of permits issued in each state for residential projects? | CREATE TABLE Permits (PermitID INT,ProjectID INT,PermitType CHAR(1),PermitDate DATE,State CHAR(2)); | SELECT State, COUNT(*) FROM Permits WHERE PermitType='R' GROUP BY State; |
Delete the record of the passenger who boarded the train with the route 202 on March 16, 2021 at 12:30 PM. | CREATE TABLE TRAIN_RIDERS (id INT,name VARCHAR(50),boarding_time TIMESTAMP); CREATE TABLE TRAIN_ROUTES (route_number INT,start_time TIMESTAMP,end_time TIMESTAMP); INSERT INTO TRAIN_ROUTES VALUES (202,'2021-03-16 12:00:00','2021-03-16 13:00:00'); INSERT INTO TRAIN_RIDERS VALUES (2,'John Doe','2021-03-16 12:30:00'); | DELETE FROM TRAIN_RIDERS WHERE id = 2; |
List all the unique workout types that were performed by female members? | CREATE TABLE Workouts (WorkoutID INT,WorkoutType VARCHAR(50),MemberID INT); INSERT INTO Workouts (WorkoutID,WorkoutType,MemberID) VALUES (1,'Running',1); INSERT INTO Workouts (WorkoutID,WorkoutType,MemberID) VALUES (2,'Yoga',2); CREATE TABLE Members (MemberID INT,Name VARCHAR(50),Gender VARCHAR(50)); INSERT INTO Members (MemberID,Name,Gender) VALUES (1,'John Doe','Male'); INSERT INTO Members (MemberID,Name,Gender) VALUES (2,'Jane Smith','Female'); | SELECT DISTINCT WorkoutType FROM Workouts INNER JOIN Members ON Workouts.MemberID = Members.MemberID WHERE Members.Gender = 'Female'; |
Determine the total sales revenue for strains with 'Diesel' in their name in Colorado dispensaries during Q2 2022. | CREATE TABLE strains (id INT,name TEXT,type TEXT); INSERT INTO strains (id,name,type) VALUES (7,'Sour Diesel','Sativa'),(8,'Diesel','Indica'),(9,'NYC Diesel','Hybrid'); CREATE TABLE sales (id INT,strain_id INT,retail_price DECIMAL,sale_date DATE,state TEXT); INSERT INTO sales (id,strain_id,retail_price,sale_date,state) VALUES (26,7,32.00,'2022-04-15','Colorado'),(27,8,34.00,'2022-05-01','Colorado'),(28,9,36.00,'2022-06-15','Colorado'); | SELECT SUM(retail_price) FROM sales INNER JOIN strains ON sales.strain_id = strains.id WHERE state = 'Colorado' AND sale_date >= '2022-04-01' AND sale_date < '2022-07-01' AND strains.name LIKE '%Diesel%'; |
What is the maximum length for rail tunnels in Italy? | CREATE TABLE Tunnel (id INT,name TEXT,location TEXT,length FLOAT,type TEXT); INSERT INTO Tunnel (id,name,location,length,type) VALUES (1,'Gotthard Base Tunnel','Switzerland',57000,'Rail'),(2,'Brenner Base Tunnel','Italy',64000,'Rail'); | SELECT MAX(length) FROM Tunnel WHERE location = 'Italy' AND type = 'Rail'; |
What is the earliest and latest start date for defense projects in region W? | CREATE TABLE DefenseProjects (project_id INT,region VARCHAR(50),start_date DATE); INSERT INTO DefenseProjects (project_id,region,start_date) VALUES (1,'W','2020-01-01'); INSERT INTO DefenseProjects (project_id,region,start_date) VALUES (2,'W','2021-01-01'); | SELECT region, MIN(start_date) as earliest_start_date, MAX(start_date) as latest_start_date FROM DefenseProjects WHERE region = 'W' GROUP BY region; |
Create a view that displays the total number of defense contracts awarded to each company in the 'defense_contracts' table | CREATE TABLE defense_contracts (contract_id INT PRIMARY KEY,company VARCHAR(255),value DECIMAL(10,2),date DATE); | CREATE VIEW contract_summary AS SELECT company, COUNT(*) as total_contracts FROM defense_contracts GROUP BY company; |
What is the average daily water consumption per person in New York City over the last month? | CREATE TABLE nyc_water_consumption (id INT,date DATE,person_id INT,water_consumption FLOAT); INSERT INTO nyc_water_consumption (id,date,person_id,water_consumption) VALUES (1,'2023-02-01',1,20.0),(2,'2023-02-02',2,25.0); | SELECT AVG(water_consumption / person_size) FROM nyc_water_consumption WHERE date >= DATEADD(month, -1, CURRENT_DATE); |
What is the average salary of employees who joined through a diversity initiative in the IT department, broken down by gender? | CREATE TABLE Employees (EmployeeID int,Name varchar(50),Gender varchar(10),Department varchar(50),Salary decimal(10,2),JoinDiversityInitiative int); INSERT INTO Employees (EmployeeID,Name,Gender,Department,Salary,JoinDiversityInitiative) VALUES (1,'John Doe','Male','IT',75000.00,1); INSERT INTO Employees (EmployeeID,Name,Gender,Department,Salary,JoinDiversityInitiative) VALUES (2,'Jane Smith','Female','IT',80000.00,1); | SELECT Gender, AVG(Salary) FROM Employees WHERE Department = 'IT' AND JoinDiversityInitiative = 1 GROUP BY Gender; |
Insert new fashion trends for the fall season, associating them with the correct category. | CREATE TABLE FashionTrends (TrendID INT,TrendName VARCHAR(50),Category VARCHAR(50)); | INSERT INTO FashionTrends (TrendID, TrendName, Category) VALUES (1, 'Oversized Blazers', 'Outerwear'), (2, 'Wide Leg Pants', 'Bottoms'), (3, 'Cropped Cardigans', 'Tops'); |
What is the total landfill capacity, in 2022, in urban areas in South America? | CREATE TABLE landfill_capacity_south_america (country TEXT,capacity INTEGER,year INTEGER,area TEXT); | SELECT SUM(capacity) FROM landfill_capacity_south_america WHERE area = 'South America' AND year = 2022; |
What is the total number of farmers who have received training in sustainable farming practices, per country, in the past year? | CREATE TABLE farmers (id INT,name VARCHAR(50),country VARCHAR(50),training_sustainable BOOLEAN); | SELECT country, COUNT(*) as total_trained FROM farmers WHERE training_sustainable = TRUE AND date(training_date) >= date('now','-1 year') GROUP BY country; |
Who are the top 3 directors with the highest total production budget? | CREATE TABLE movies (id INT,title VARCHAR(255),release_year INT,production_budget DECIMAL(10,2),director VARCHAR(255)); | SELECT director, SUM(production_budget) as total_budget FROM movies GROUP BY director ORDER BY total_budget DESC LIMIT 3; |
What are the top 10 most common vulnerabilities across all systems? | CREATE TABLE systems (system_id INT,system_name VARCHAR(255)); CREATE TABLE vulnerabilities (vulnerability_id INT,system_id INT,vulnerability_type VARCHAR(255)); | SELECT v.vulnerability_type, COUNT(*) as count FROM vulnerabilities v JOIN systems s ON v.system_id = s.system_id GROUP BY v.vulnerability_type ORDER BY count DESC LIMIT 10; |
What is the maximum cultural heritage preservation score for any country in 2023? | CREATE TABLE country_data (country VARCHAR(255),year INT,score INT); INSERT INTO country_data (country,year,score) VALUES ('India',2023,98),('China',2023,96),('Japan',2023,99); | SELECT MAX(score) FROM country_data WHERE year = 2023; |
What is the total number of community health workers who have received implicit bias training, broken down by their ethnicity? | CREATE TABLE CommunityHealthWorkers (WorkerID INT,Ethnicity VARCHAR(255),ImplicitBiasTraining DATE); INSERT INTO CommunityHealthWorkers (WorkerID,Ethnicity,ImplicitBiasTraining) VALUES (1,'Hispanic','2022-01-10'); INSERT INTO CommunityHealthWorkers (WorkerID,Ethnicity,ImplicitBiasTraining) VALUES (2,'African American','2021-12-15'); INSERT INTO CommunityHealthWorkers (WorkerID,Ethnicity,ImplicitBiasTraining) VALUES (3,'Asian','2022-02-03'); INSERT INTO CommunityHealthWorkers (WorkerID,Ethnicity,ImplicitBiasTraining) VALUES (4,'Native American','2021-08-02'); | SELECT Ethnicity, COUNT(*) as Total FROM CommunityHealthWorkers WHERE ImplicitBiasTraining IS NOT NULL GROUP BY Ethnicity; |
What is the cost of 'chicken' at 'Home Cooking'? | CREATE TABLE menus (restaurant VARCHAR(255),item VARCHAR(255),cost FLOAT); INSERT INTO menus (restaurant,item,cost) VALUES ('Home Cooking','chicken',10.0); | SELECT cost FROM menus WHERE restaurant = 'Home Cooking' AND item = 'chicken'; |
What is the average depth of all oceans? | CREATE TABLE ocean_depths (ocean_name TEXT,avg_depth REAL); INSERT INTO ocean_depths (ocean_name,avg_depth) VALUES ('Pacific Ocean',4028.0),('Indian Ocean',3963.0),('Atlantic Ocean',3926.0); | SELECT AVG(avg_depth) FROM ocean_depths; |
What is the minimum quantity for each product category (low stock and in stock) for products made in Mexico? | CREATE TABLE inventory (product_id INT,product_origin VARCHAR(50),category VARCHAR(50),quantity INT); INSERT INTO inventory (product_id,product_origin,category,quantity) VALUES (1,'Mexico','Low Stock',20),(2,'Peru','In Stock',50),(3,'Mexico','In Stock',75); | SELECT product_origin, category, MIN(quantity) as min_quantity FROM inventory WHERE product_origin = 'Mexico' GROUP BY product_origin, category; |
Find the total revenue for each menu category in the month of January 2022 | CREATE TABLE menu_items (menu_category VARCHAR(255),revenue DECIMAL(10,2)); INSERT INTO menu_items (menu_category,revenue) VALUES ('Appetizers',1500.00),('Entrees',3500.00),('Desserts',2000.00); CREATE TABLE time_dim (date DATE); INSERT INTO time_dim (date) VALUES ('2022-01-01'),('2022-01-02'),('2022-01-03'); | SELECT menu_category, SUM(revenue) as total_revenue FROM menu_items MI JOIN time_dim TD ON DATE('2022-01-01') = TD.date GROUP BY menu_category; |
What is the average salary of employees in the 'engineering' department? | CREATE TABLE salaries (id INT,employee_id INT,salary INT); INSERT INTO salaries (id,employee_id,salary) VALUES (1,1,50000),(2,2,55000),(3,3,60000); | SELECT AVG(salary) FROM salaries JOIN employees ON salaries.employee_id = employees.id WHERE employees.department = 'engineering'; |
What is the average revenue per month for the Rock genre? | CREATE TABLE Monthly (MonthID INT,SongID INT,Month VARCHAR(50),Revenue INT); | SELECT Monthly.Month, AVG(Monthly.Revenue) as AvgRevenuePerMonth FROM Monthly INNER JOIN Song ON Monthly.SongID = Song.SongID WHERE Song.GenreID = (SELECT GenreID FROM Genre WHERE Name='Rock') GROUP BY Monthly.Month; |
List all geothermal power plants in the "GeothermalProjects" schema, along with their total installed capacity in MW. | CREATE TABLE GeothermalCapacity (project_id INT,name VARCHAR(100),location VARCHAR(100),capacity INT); INSERT INTO GeothermalCapacity (project_id,name,location,capacity) VALUES (1,'Geothermal Plant 1','Iceland',120),(2,'Geothermal Plant 2','Italy',180); | SELECT project_id, name, location, capacity FROM GeothermalProjects.GeothermalCapacity; |
How many 5-star hotels in the 'Asia' region have adopted AI-powered services? | CREATE TABLE asiahotels (id INT,name VARCHAR(255),star_rating INT,has_ai BOOLEAN); INSERT INTO asiahotels (id,name,star_rating,has_ai) VALUES (1,'AI Smart Hotel',5,1); INSERT INTO asiahotels (id,name,star_rating,has_ai) VALUES (2,'Traditional Hotel',5,0); | SELECT COUNT(*) FROM asiahotels WHERE star_rating = 5 AND has_ai = 1; |
What is the total water usage by agricultural sector in California and Texas? | CREATE TABLE california_water_usage (state VARCHAR(20),sector VARCHAR(20),usage INT); INSERT INTO california_water_usage (state,sector,usage) VALUES ('California','Agricultural',12000); CREATE TABLE texas_water_usage (state VARCHAR(20),sector VARCHAR(20),usage INT); INSERT INTO texas_water_usage (state,sector,usage) VALUES ('Texas','Agricultural',15000); | SELECT usage FROM california_water_usage WHERE sector = 'Agricultural' UNION SELECT usage FROM texas_water_usage WHERE sector = 'Agricultural' |
What is the maximum and minimum funding received by biotech startups in each Canadian province? | CREATE SCHEMA if not exists funding_canada;CREATE TABLE if not exists funding_canada.startups (id INT,name VARCHAR(100),province VARCHAR(50),funding DECIMAL(10,2));INSERT INTO funding_canada.startups (id,name,province,funding) VALUES (1,'StartupA','Ontario',3000000.00),(2,'StartupB','Quebec',1000000.00),(3,'StartupC','Ontario',500000.00),(4,'StartupD','British Columbia',2000000.00); | SELECT province, MAX(funding) as max_funding, MIN(funding) as min_funding FROM funding_canada.startups GROUP BY province; |
Find the number of labor rights violations in each region. | CREATE TABLE violations (violation_id INT,region_id INT,violation_count INT); CREATE TABLE regions (region_id INT,region_name TEXT); INSERT INTO violations (violation_id,region_id,violation_count) VALUES (1,1,10),(2,1,20),(3,2,30),(4,3,40); INSERT INTO regions (region_id,region_name) VALUES (1,'Region A'),(2,'Region B'),(3,'Region C'); | SELECT regions.region_name, SUM(violations.violation_count) FROM regions INNER JOIN violations ON regions.region_id = violations.region_id GROUP BY regions.region_name; |
Calculate the percentage of ingredients sourced from organic farms in cosmetic products. | CREATE TABLE ingredients (ingredient_id INT,organic BOOLEAN,product_id INT); | SELECT organic, COUNT(*) as num_ingredients, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM ingredients) as percentage FROM ingredients GROUP BY organic; |
Show the names of all destinations that were marketed in 2020 and had more than 15000 tourists visiting in that year. | CREATE TABLE marketing_campaigns (destination VARCHAR(20),year INT); CREATE TABLE tourism_stats (destination VARCHAR(20),year INT,tourists INT); INSERT INTO marketing_campaigns (destination,year) VALUES ('Japan',2020),('France',2020),('Germany',2021),('Italy',2020); INSERT INTO tourism_stats (destination,year,tourists) VALUES ('Japan',2020,20000),('Japan',2021,25000),('France',2020,16000),('France',2021,18000),('Germany',2021,12000),('Italy',2020,15000),('Italy',2021,17000); | SELECT destination FROM marketing_campaigns WHERE year = 2020 INTERSECT SELECT destination FROM tourism_stats WHERE tourists > 15000 AND year = 2020; |
How many volunteer hours were recorded for environmental programs in California? | CREATE TABLE VolunteerEvents (EventID INT,EventName TEXT,Location TEXT,EventType TEXT); INSERT INTO VolunteerEvents (EventID,EventName,Location,EventType) VALUES (1,'Beach Cleanup','California','Environment'),(2,'Tree Planting','New York','Environment'); | SELECT SUM(VolunteerHours) FROM VolunteerEvents JOIN VolunteerHours ON VolunteerEvents.EventID = VolunteerHours.EventID WHERE VolunteerEvents.Location = 'California' AND VolunteerEvents.EventType = 'Environment'; |
Alter the 'claims' table to add a constraint that the 'claim_amount' should be non-negative | CREATE TABLE if not exists claims (claim_id INT PRIMARY KEY,policyholder_id INT,claim_amount DECIMAL(10,2),claim_date DATE); | ALTER TABLE claims ADD CONSTRAINT non_negative_claim CHECK (claim_amount >= 0); |
Update the 'soil_moisture' value to 50% in the 'Plot1' on 2022-07-15. | CREATE TABLE Plot1 (date DATE,soil_moisture FLOAT); | UPDATE Plot1 SET soil_moisture = 50 WHERE date = '2022-07-15'; |
What is the average calorie intake per user in Canada, partitioned by day? | CREATE TABLE meals (user_id INT,meal_date DATE,calories INT); INSERT INTO meals (user_id,meal_date,calories) VALUES (1,'2022-01-01',600),(1,'2022-01-02',800),(3,'2022-01-01',400); CREATE TABLE users (user_id INT,country VARCHAR(255)); INSERT INTO users (user_id,country) VALUES (1,'Canada'),(2,'USA'),(3,'Canada'); | SELECT meal_date, AVG(calories) as avg_calories FROM (SELECT user_id, meal_date, calories FROM meals JOIN users ON meals.user_id = users.user_id WHERE users.country = 'Canada') t GROUP BY meal_date; |
Retrieve vessel performance data with the maximum speed and minimum distance traveled by vessels 'D' and 'E' from the 'vessel_performance' table | CREATE TABLE vessel_performance (vessel_id TEXT,speed FLOAT,distance FLOAT,timestamp TIMESTAMP); | SELECT vessel_id, MAX(speed) as max_speed, MIN(distance) as min_distance FROM vessel_performance WHERE vessel_id IN ('D', 'E') GROUP BY vessel_id; |
Delete all traditional art forms related to textile craftsmanship. | CREATE TABLE art_forms (id INT PRIMARY KEY,name VARCHAR(50),type VARCHAR(30)); INSERT INTO art_forms (id,name,type) VALUES (1,'Throat Singing','Music'),(2,'Batik','Textile'),(3,'Ikebana','Visual Arts'); | DELETE FROM art_forms WHERE type = 'Textile'; |
Who has sold the most merchandise among TeamD's players? | CREATE TABLE merchandise (id INT,player VARCHAR(50),team VARCHAR(50),sales DECIMAL(5,2)); INSERT INTO merchandise (id,player,team,sales) VALUES (1,'James Johnson','TeamD',500.00),(2,'Jessica Smith','TeamD',700.00),(3,'Michael Brown','TeamD',600.00),(4,'Nicole White','TeamE',800.00),(5,'Oliver Green','TeamE',900.00); | SELECT player FROM merchandise WHERE team = 'TeamD' ORDER BY sales DESC LIMIT 1; |
Who are the project managers for the 'technology for social good' sector? | CREATE TABLE employees (employee_id INT,name VARCHAR(50),position VARCHAR(50)); INSERT INTO employees (employee_id,name,position) VALUES (1,'Greg','Project Manager'); INSERT INTO employees (employee_id,name,position) VALUES (2,'Hannah','Data Scientist'); INSERT INTO employees (employee_id,name,position) VALUES (3,'Ivan','Project Manager'); INSERT INTO employees (employee_id,name,position) VALUES (4,'Judy','Developer'); | SELECT name FROM employees INNER JOIN projects ON employees.employee_id = projects.project_manager WHERE sector = 'technology for social good'; |
What is the total number of policies and the percentage of those policies that have a claim amount greater than 5000? | CREATE TABLE policyholders (id INT,policy_id INT); INSERT INTO policyholders (id,policy_id) VALUES (1,1),(2,2),(3,3); CREATE TABLE claims (id INT,policy_id INT,claim_amount INT); INSERT INTO claims (id,policy_id,claim_amount) VALUES (1,1,5000),(2,2,3000),(3,3,10000); | SELECT COUNT(DISTINCT policyholders.id) AS total_policies, COUNT(DISTINCT claims.policy_id) FILTER (WHERE claim_amount > 5000) * 100.0 / COUNT(DISTINCT policyholders.id) AS high_claim_percentage FROM policyholders LEFT JOIN claims ON policyholders.policy_id = claims.policy_id; |
What is the number of bridges and their average length (in meters) in 'New York' from the 'bridges' and 'bridge_lengths' tables? | CREATE TABLE bridges (id INT,name VARCHAR(255),location VARCHAR(255)); CREATE TABLE bridge_lengths (bridge_id INT,length DECIMAL(10,2)); | SELECT b.location, COUNT(b.id) as number_of_bridges, AVG(bl.length) as average_length FROM bridges b INNER JOIN bridge_lengths bl ON b.id = bl.bridge_id WHERE b.location = 'New York' GROUP BY b.location; |
What is the number of unique donors for each program? | CREATE TABLE Donors (DonorID INT,ProgramID INT,DonorName TEXT); CREATE TABLE Programs (ProgramID INT,ProgramName TEXT); | SELECT Programs.ProgramName, COUNT(DISTINCT Donors.DonorID) AS NumberOfDonors FROM Donors INNER JOIN Programs ON Donors.ProgramID = Programs.ProgramID GROUP BY Programs.ProgramName; |
How many volunteers participated in each program in Q3 2021, sorted by the number of volunteers in descending order? | CREATE TABLE Programs (id INT,program_name VARCHAR(50),total_volunteers INT); CREATE TABLE VolunteerEvents (id INT,program_id INT,event_date DATE,total_volunteers INT); | SELECT Programs.program_name, SUM(VolunteerEvents.total_volunteers) AS total_volunteers_q3 FROM Programs INNER JOIN VolunteerEvents ON Programs.id = VolunteerEvents.program_id WHERE VolunteerEvents.event_date BETWEEN '2021-07-01' AND '2021-09-30' GROUP BY Programs.program_name ORDER BY total_volunteers_q3 DESC; |
Which dish had the highest sales revenue in branch 1, 2, and 3? | CREATE TABLE Branches (branch_id INT,branch_name VARCHAR(255));CREATE TABLE Menu (dish_name VARCHAR(255),branch_id INT,price DECIMAL(5,2));CREATE TABLE Sales (sale_date DATE,dish_name VARCHAR(255),quantity INT); | SELECT dish_name, SUM(quantity * price) as total_revenue FROM Sales JOIN Menu ON Sales.dish_name = Menu.dish_name WHERE branch_id IN (1, 2, 3) GROUP BY dish_name ORDER BY total_revenue DESC LIMIT 1; |
What is the status of satellites launched by India? | CREATE TABLE satellites (satellite_id INT,name VARCHAR(255),country VARCHAR(255),launch_date DATE,status VARCHAR(255)); INSERT INTO satellites (satellite_id,name,country,launch_date,status) VALUES (1,'GSAT-1','India','2001-06-18','Active'); | SELECT name, status FROM satellites WHERE country = 'India'; |
Show marine species that are present in all regions | CREATE TABLE species_in_regions (species_id INT,region_id INT); INSERT INTO species_in_regions (species_id,region_id) VALUES (1,1),(2,2),(3,1),(4,2),(5,3),(6,1),(7,2),(8,3),(9,1),(10,2),(11,3); | SELECT species_id FROM species_in_regions GROUP BY species_id HAVING COUNT(DISTINCT region_id) = (SELECT COUNT(DISTINCT region_id) FROM regions); |
How many public community centers are there in the Southeast region? | CREATE TABLE CommunityCenter (Name VARCHAR(255),Region VARCHAR(255),Type VARCHAR(255)); INSERT INTO CommunityCenter (Name,Region,Type) VALUES ('Southeast Community Center','Southeast','Public'),('Northeast Community Center','Northeast','Public'),('Southwest Community Center','Southwest','Public'),('Northwest Community Center','Northwest','Public'); | SELECT COUNT(*) FROM CommunityCenter WHERE Region = 'Southeast' AND Type = 'Public'; |
What is the average age of patients with HIV in urban areas? | CREATE TABLE hiv_patients(id INT,age INT,city TEXT,state TEXT); CREATE VIEW urban_areas AS SELECT * FROM areas WHERE population > 100000; | SELECT AVG(age) FROM hiv_patients JOIN urban_areas USING(city); |
Calculate the total number of mental health treatment facilities in Africa. | CREATE TABLE facilities (facility_id INT,facility_name VARCHAR(50),country VARCHAR(50),region VARCHAR(50)); INSERT INTO facilities (facility_id,facility_name,country,region) VALUES (1,'Accra Mental Health Clinic','Ghana','Africa'),(2,'Nairobi Mental Health Institute','Kenya','Africa'); | SELECT COUNT(facility_id) FROM facilities WHERE facilities.region = 'Africa'; |
How many cultural events were held in 'Tokyo' in 2021? | CREATE TABLE events(id INT,city VARCHAR(255),year INT,num_events INT); INSERT INTO events (id,city,year,num_events) VALUES (1,'Tokyo',2021,15),(2,'Tokyo',2022,20),(3,'Paris',2021,25); | SELECT SUM(num_events) FROM events WHERE city = 'Tokyo' AND year = 2021; |
What is the average age of audience members who attended events in New York or Chicago in 2021, and update their records with the calculated average age? | CREATE TABLE Audience (audience_id INT,event_city VARCHAR(50),audience_age INT); INSERT INTO Audience (audience_id,event_city,audience_age) VALUES (1,'New York',35),(2,'Chicago',40),(3,'New York',32),(4,'Chicago',45),(5,'New York',38),(6,'Chicago',35); | SELECT AVG(audience_age) FROM Audience WHERE event_city IN ('New York', 'Chicago') AND event_year = 2021; |
Who are the teachers that have not attended any professional development programs? | CREATE TABLE teachers (teacher_id INT,teacher_name TEXT); INSERT INTO teachers (teacher_id,teacher_name) VALUES (1,'Mrs. Doe'),(2,'Mr. Smith'),(3,'Ms. Johnson'); CREATE TABLE professional_development (program_id INT,program_name TEXT,teacher_id INT); INSERT INTO professional_development (program_id,program_name,teacher_id) VALUES (1,'Python for Educators',1),(2,'Data Science for Teachers',2),(3,'Inclusive Teaching',4),(4,'Open Pedagogy',5); | SELECT t.teacher_name FROM teachers t LEFT JOIN professional_development pd ON t.teacher_id = pd.teacher_id WHERE pd.teacher_id IS NULL; |
How many public schools were built in the state of California between 2015 and 2020? | CREATE TABLE schools (state VARCHAR(255),year INT,school_count INT); INSERT INTO schools (state,year,school_count) VALUES ('California',2015,150),('California',2016,200),('California',2017,250),('California',2018,300),('California',2019,350),('California',2020,400); | SELECT SUM(school_count) AS total_schools_built FROM schools WHERE state = 'California' AND year BETWEEN 2015 AND 2020; |
What is the percentage of restaurants that passed their food safety inspections in each region? | CREATE TABLE FoodInspections (restaurant_id INT,region VARCHAR(50),passed BOOLEAN); INSERT INTO FoodInspections (restaurant_id,region,passed) VALUES (1,'North',TRUE),(1,'North',FALSE),(2,'North',TRUE),(2,'South',TRUE),(2,'South',FALSE); | SELECT region, AVG(IF(passed, 1, 0)) as pass_percentage FROM foodinspections GROUP BY region; |
List all marine species in the 'marine_species' table, ordered by conservation status | CREATE TABLE marine_species (id INT PRIMARY KEY,species_name VARCHAR(255),conservation_status VARCHAR(255)); INSERT INTO marine_species (id,species_name,conservation_status) VALUES (1001,'Oceanic Whitetip Shark','Vulnerable'),(1002,'Green Sea Turtle','Threatened'),(1003,'Leatherback Sea Turtle','Vulnerable'),(1004,'Hawksbill Sea Turtle','Endangered'); | SELECT species_name FROM marine_species ORDER BY conservation_status ASC; |
What is the maximum property tax for affordable housing units in the state of California? | CREATE TABLE affordable_housing (id INT,property_tax FLOAT,state VARCHAR(20)); INSERT INTO affordable_housing (id,property_tax,state) VALUES (1,5000,'California'),(2,7000,'New York'),(3,3000,'Texas'); | SELECT MAX(property_tax) FROM affordable_housing WHERE state = 'California'; |
What are the total sales for each genre in the United States? | CREATE TABLE sales (genre VARCHAR(255),country VARCHAR(255),sales FLOAT); CREATE TABLE genres (genre VARCHAR(255)); INSERT INTO genres (genre) VALUES ('Pop'),('Rock'),('Jazz'),('Classical'); | SELECT s.genre, SUM(s.sales) as total_sales FROM sales s JOIN genres g ON s.genre = g.genre WHERE s.country = 'United States' GROUP BY s.genre; |
List all oil fields in Canada and their production figures. | CREATE TABLE OilFields (FieldID INT,FieldName VARCHAR(50),Country VARCHAR(50),Production INT,Reserves INT); INSERT INTO OilFields (FieldID,FieldName,Country,Production,Reserves) VALUES (1,'Galaxy','USA',20000,500000); INSERT INTO OilFields (FieldID,FieldName,Country,Production,Reserves) VALUES (2,'Apollo','Canada',15000,400000); | SELECT FieldName, Production FROM OilFields WHERE Country = 'Canada'; |
What is the count of packages in 'received' status at each warehouse in 'Asia'? | CREATE TABLE Warehouse (id INT,name VARCHAR(20),city VARCHAR(20),country VARCHAR(20)); INSERT INTO Warehouse (id,name,city,country) VALUES (1,'Seoul Warehouse','Seoul','South Korea'),(2,'Mumbai Warehouse','Mumbai','India'),(3,'Tokyo Warehouse','Tokyo','Japan'); CREATE TABLE Packages (id INT,warehouse_id INT,status VARCHAR(20)); INSERT INTO Packages (id,warehouse_id,status) VALUES (1,1,'received'),(2,1,'processing'),(3,2,'received'),(4,2,'received'),(5,3,'processing'); | SELECT warehouse_id, COUNT(*) FROM Packages WHERE status = 'received' GROUP BY warehouse_id HAVING country = 'Asia'; |
How many public meetings were held in 'Meetings' table by month? | CREATE TABLE Meetings (meeting_id INT,meeting_date DATE); | SELECT MONTH(meeting_date), COUNT(meeting_id) FROM Meetings GROUP BY MONTH(meeting_date); |
Which artist had the highest revenue generated from sales at the "Contemporary Art Gallery" in 2021? | CREATE TABLE ArtistSales2 (GalleryName TEXT,ArtistName TEXT,NumPieces INTEGER,PricePerPiece FLOAT); INSERT INTO ArtistSales2 (GalleryName,ArtistName,NumPieces,PricePerPiece) VALUES ('Contemporary Art Gallery','Warhol',12,75.5),('Contemporary Art Gallery','Matisse',15,60.0),('Contemporary Art Gallery','Kahlo',18,80.0); | SELECT ArtistName, SUM(NumPieces * PricePerPiece) AS Revenue FROM ArtistSales2 WHERE GalleryName = 'Contemporary Art Gallery' AND YEAR(SaleDate) = 2021 GROUP BY ArtistName ORDER BY Revenue DESC LIMIT 1; |
What is the average depth of marine protected areas in the Atlantic? | CREATE TABLE marine_protected_areas (name TEXT,location TEXT,avg_depth FLOAT); INSERT INTO marine_protected_areas (name,location,avg_depth) VALUES ('Bermuda Park','Atlantic',50.0),('Azores','Atlantic',20.0); | SELECT AVG(avg_depth) FROM marine_protected_areas WHERE location = 'Atlantic'; |
How many players use VR technology in esports events? | CREATE TABLE EsportsEvents (EventID INT,Players INT,UsesVR BOOLEAN); INSERT INTO EsportsEvents (EventID,Players,UsesVR) VALUES (1,10,TRUE); | SELECT SUM(Players) FROM EsportsEvents WHERE UsesVR = TRUE; |
How many countries in Oceania have been promoting sustainable tourism since 2018? | CREATE TABLE Sustainable_Practices (id INT PRIMARY KEY,country_id INT,certification_date DATE,FOREIGN KEY (country_id) REFERENCES Countries(id)); INSERT INTO Sustainable_Practices (id,country_id,certification_date) VALUES (1,1,'2018-07-01'); INSERT INTO Sustainable_Practices (id,country_id,certification_date) VALUES (2,12,'2019-03-01'); | SELECT COUNT(DISTINCT c.id) as country_count FROM Countries c INNER JOIN Sustainable_Practices sp ON c.id = sp.country_id WHERE c.continent = 'Oceania' AND sp.certification_date >= '2018-01-01'; |
What is the average speed of electric vehicles in the 'test_drives' table, grouped by 'vehicle_make'? | CREATE TABLE test_drives (drive_id INT,vehicle_make VARCHAR(20),avg_speed FLOAT); INSERT INTO test_drives (drive_id,vehicle_make,avg_speed) VALUES (1,'Tesla',65.3),(2,'Tesla',68.1),(3,'Rivian',62.9),(4,'Rivian',64.5); | SELECT vehicle_make, AVG(avg_speed) avg_speed FROM test_drives GROUP BY vehicle_make; |
What is the maximum R&D expenditure for drugs approved in 'Year1'? | CREATE TABLE r_d_expenditure (drug_name TEXT,expenditure INTEGER,approval_year TEXT); INSERT INTO r_d_expenditure (drug_name,expenditure,approval_year) VALUES ('Drug1',2500,'Year1'),('Drug2',3000,'Year2'),('Drug3',3500,'Year1'),('Drug4',4000,'Year3'); | SELECT MAX(expenditure) FROM r_d_expenditure WHERE approval_year = 'Year1'; |
Update the travel advisory for Brazil in 2022 to 'exercise caution'. | CREATE TABLE travel_advisories (country VARCHAR(20),year INT,advisory VARCHAR(50)); INSERT INTO travel_advisories (country,year,advisory) VALUES ('Japan',2022,'avoid non-essential travel'),('Brazil',2022,'avoid all travel'); | UPDATE travel_advisories SET advisory = 'exercise caution' WHERE country = 'Brazil' AND year = 2022; |
How many players have participated in eSports events for game 'B'? | CREATE TABLE GameB_Participants (player_id INT,game_id INT); CREATE TABLE GameB_eSportsEvents (event_id INT,game_id INT); INSERT INTO GameB_Participants (player_id,game_id) VALUES (1,1),(2,1),(3,2),(4,1),(5,2); INSERT INTO GameB_eSportsEvents (event_id,game_id) VALUES (101,1),(102,2),(103,1); | SELECT COUNT(DISTINCT GameB_Participants.player_id) as num_players FROM GameB_Participants JOIN GameB_eSportsEvents ON GameB_Participants.game_id = GameB_eSportsEvents.game_id; |
Create a table named 'health_equity_metrics' | CREATE TABLE health_equity_metrics (id INT PRIMARY KEY,metric VARCHAR(255),value FLOAT); | CREATE TABLE health_equity_metrics (id INT PRIMARY KEY, metric VARCHAR(255), value FLOAT); |
What is the maximum age of members in unions with a 'hospitality' industry classification? | CREATE TABLE unions (id INT,name VARCHAR(255),industry VARCHAR(255),member_age INT); INSERT INTO unions (id,name,industry,member_age) VALUES (1,'Union D','hospitality',30),(2,'Union E','hospitality',35),(3,'Union F','hospitality',40); | SELECT MAX(member_age) FROM unions WHERE industry = 'hospitality'; |
Calculate the average landfill capacity for districts in each region. | CREATE TABLE LandfillCapacity (id INT,district VARCHAR(20),capacity INT,region VARCHAR(10)); INSERT INTO LandfillCapacity (id,district,capacity,region) VALUES (1,'DistrictA',250000,'RegionA'),(2,'DistrictB',500000,'RegionB'),(3,'DistrictC',300000,'RegionA'); | SELECT region, AVG(capacity) FROM LandfillCapacity GROUP BY region; |
What is the difference in price between the most and least expensive products in the 'haircare' table? | CREATE TABLE haircare (product_id INT,product_name VARCHAR(50),price DECIMAL(5,2)); | SELECT product_name, price, MAX(price) OVER() - MIN(price) OVER() as price_difference FROM haircare; |
Identify the wildlife habitats that have a decrease in area between 2018 and 2019, and order them by the largest decrease first. | CREATE TABLE wildlife_habitats (habitat_id INT,habitat_name VARCHAR(50),year INT,area INT); INSERT INTO wildlife_habitats (habitat_id,habitat_name,year,area) VALUES (1,'Forest',2018,1000),(2,'Wetland',2018,2000),(3,'Grassland',2018,3000),(4,'Forest',2019,900),(5,'Wetland',2019,1800),(6,'Grassland',2019,2800); | SELECT habitat_name, (LAG(area, 1) OVER (PARTITION BY habitat_name ORDER BY year)) - area AS area_decrease FROM wildlife_habitats WHERE year = 2019 GROUP BY habitat_name, area ORDER BY area_decrease DESC; |
Show the number of cases won, lost, and settled by attorneys in the corporate law department. | CREATE TABLE Cases (CaseID INT,AttorneyID INT,Outcome VARCHAR(10)); INSERT INTO Cases (CaseID,AttorneyID,Outcome) VALUES (1,1,'Won'),(2,1,'Lost'),(3,2,'Settled'); | SELECT c.AttorneyID, SUM(CASE WHEN c.Outcome = 'Won' THEN 1 ELSE 0 END) AS Wins, SUM(CASE WHEN c.Outcome = 'Lost' THEN 1 ELSE 0 END) AS Losses, SUM(CASE WHEN c.Outcome = 'Settled' THEN 1 ELSE 0 END) AS Settled FROM Cases c WHERE c.AttorneyID IN (SELECT a.AttorneyID FROM Attorneys a WHERE a.PracticeArea = 'Corporate Law') GROUP BY c.AttorneyID; |
What is the average pollution index for each mine in Country A? | CREATE TABLE environmental_impact (id INT,mine_id INT,pollution_index FLOAT,impact_date DATE); INSERT INTO environmental_impact (id,mine_id,pollution_index,impact_date) VALUES (3,3,28.1,'2020-01-01'); INSERT INTO environmental_impact (id,mine_id,pollution_index,impact_date) VALUES (4,4,32.5,'2020-02-01'); | SELECT e.mine_id, AVG(e.pollution_index) as avg_pollution FROM environmental_impact e WHERE e.location = 'Country A' GROUP BY e.mine_id; |
How many broadband subscribers are there in Ohio who have had a service outage in the last year? | CREATE TABLE broadband_subscribers (id INT,name VARCHAR(50),outage BOOLEAN,state VARCHAR(50)); INSERT INTO broadband_subscribers (id,name,outage,state) VALUES (7,'Charlie White',true,'OH'); INSERT INTO broadband_subscribers (id,name,outage,state) VALUES (8,'David Black',false,'OH'); | SELECT COUNT(*) FROM broadband_subscribers WHERE outage = true AND state = 'OH' AND YEAR(registration_date) = YEAR(CURRENT_DATE) - 1; |
How many garments were produced in each country in the last month? | CREATE TABLE production (id INT,factory VARCHAR(255),country VARCHAR(255),quantity INT,production_date DATE); INSERT INTO production (id,factory,country,quantity,production_date) VALUES (1,'Fabric Inc','India',700,'2021-05-01'),(2,'Stitch Time','India',800,'2021-06-15'),(3,'Sew Good','India',600,'2021-04-01'),(4,'Fabric Inc','USA',900,'2021-05-01'); | SELECT country, COUNT(quantity) FROM production WHERE production_date >= DATEADD(month, -1, CURRENT_DATE) GROUP BY country; |
Delete all records from the soil moisture table for the past week. | CREATE TABLE soil_moisture (id INT,field_id INT,value INT,timestamp TIMESTAMP); | DELETE FROM soil_moisture WHERE timestamp >= NOW() - INTERVAL '1 week'; |
Which team has the highest average ticket price? | CREATE TABLE tickets (id INT,game_id INT,team VARCHAR(255),price DECIMAL(10,2)); | SELECT team, AVG(price) AS avg_price FROM tickets GROUP BY team ORDER BY avg_price DESC LIMIT 1; |
What is the total amount of food waste generated in the last month, categorized by ingredient type? | CREATE TABLE food_waste (id INT,waste_date DATE,ingredient_name TEXT,quantity INT); | SELECT ingredient_name, SUM(quantity) FROM food_waste WHERE waste_date >= DATE(NOW()) - INTERVAL 1 MONTH GROUP BY ingredient_name; |
What is the total revenue generated from 'Organic' and 'Fair Trade' sourced menu items? | CREATE TABLE menu_items (id INT,name VARCHAR(255),category VARCHAR(255),organic_sourced BOOLEAN,fair_trade_sourced BOOLEAN,revenue INT); INSERT INTO menu_items (id,name,category,organic_sourced,fair_trade_sourced,revenue) VALUES (1,'Quinoa Salad','Salads',TRUE,TRUE,500),(2,'Grilled Chicken Sandwich','Sandwiches',FALSE,FALSE,700),(3,'Black Bean Burger','Burgers',TRUE,FALSE,600); | SELECT SUM(revenue) as total_revenue FROM menu_items WHERE organic_sourced = TRUE AND fair_trade_sourced = TRUE; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.