instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total waste generation in eco-district A and B?
CREATE TABLE district (id INT,name TEXT,waste_generation FLOAT); INSERT INTO district (id,name,waste_generation) VALUES (1,'A',120),(2,'B',150);
SELECT SUM(waste_generation) FROM district WHERE name IN ('A', 'B');
What is the maximum market price of Samarium in the last 3 years?
CREATE TABLE SamariumProduction (id INT PRIMARY KEY,year INT,market_price DECIMAL(10,2));
SELECT MAX(market_price) FROM SamariumProduction WHERE year BETWEEN (YEAR(CURRENT_DATE) - 3) AND YEAR(CURRENT_DATE);
Delete the records of players who have not participated in any esports event.
CREATE TABLE Players (PlayerID INT,ParticipatedInEsports BOOLEAN); INSERT INTO Players (PlayerID,ParticipatedInEsports) VALUES (1,TRUE),(2,FALSE);
DELETE FROM Players WHERE ParticipatedInEsports = FALSE;
List the athletes who have participated in wellbeing programs on the same day as another athlete?
CREATE TABLE athlete_wellbeing (athlete_id INT,program_date DATE); INSERT INTO athlete_wellbeing (athlete_id,program_date) VALUES (1,'2021-03-01'),(1,'2021-07-15'),(2,'2021-02-20'),(3,'2020-12-31'),(3,'2021-06-05'),(4,'2021-05-01'),(5,'2021-09-10'),(6,'2021-03-01'),(7,'2021-03-01');
SELECT a1.athlete_id, a1.program_date FROM athlete_wellbeing a1 JOIN athlete_wellbeing a2 ON a1.program_date = a2.program_date AND a1.athlete_id != a2.athlete_id;
What is the average annual visitors to cultural heritage sites in Italy?
CREATE TABLE cultural_heritage_sites_italy (site_id INT,site_name TEXT,country TEXT,annual_visitors INT); INSERT INTO cultural_heritage_sites_italy (site_id,site_name,country,annual_visitors) VALUES (1,'Colosseum','Italy',2000000),(2,'Leaning Tower of Pisa','Italy',1500000);
SELECT AVG(annual_visitors) FROM cultural_heritage_sites_italy;
List all marine species that are found in only one ocean basin
CREATE TABLE species (id INT,name VARCHAR(255),habitat VARCHAR(255)); CREATE TABLE ocean_basin (id INT,name VARCHAR(255)); CREATE TABLE species_ocean_basin (species_id INT,ocean_basin_id INT);
SELECT species.name FROM species JOIN species_ocean_basin ON species.id = species_ocean_basin.species_id JOIN ocean_basin ON species_ocean_basin.ocean_basin_id = ocean_basin.id GROUP BY species.name HAVING COUNT(DISTINCT ocean_basin.name) = 1;
Identify the number of unique visitors who attended both theatre performances and poetry readings in the same month.
CREATE TABLE theatre_performances (id INT,visitor_id INT,visit_date DATE); CREATE TABLE poetry_readings (id INT,visitor_id INT,visit_date DATE);
SELECT COUNT(DISTINCT visitor_id) AS unique_visitors FROM theatre_performances INNER JOIN poetry_readings ON theatre_performances.visitor_id = poetry_readings.visitor_id AND MONTH(theatre_performances.visit_date) = MONTH(poetry_readings.visit_date);
What is the average word count of articles published on politics in the last month, grouped by week?
CREATE TABLE articles (id INT,title VARCHAR(255),word_count INT,publish_date DATE,topic VARCHAR(255)); INSERT INTO articles (id,title,word_count,publish_date,topic) VALUES (1,'Article 1',500,'2022-01-01','politics'),(2,'Article 2',700,'2022-01-05','politics');
SELECT AVG(word_count), WEEKOFYEAR(publish_date) AS Week FROM articles WHERE topic = 'politics' AND publish_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH) GROUP BY Week;
What is the average CO2 emission per night for local events in California?
CREATE TABLE Events (id INT,name TEXT,location TEXT,type TEXT,start_date DATE,end_date DATE,co2_emission INT); INSERT INTO Events (id,name,location,type,start_date,end_date,co2_emission) VALUES (1,'Local Festival','California','Local','2022-03-01','2022-03-05',500);
SELECT AVG(co2_emission / DATEDIFF(end_date, start_date)) FROM Events WHERE location = 'California' AND type = 'Local';
Determine the number of unique players who have played each game
CREATE TABLE Players (player_id INT,player_name VARCHAR(100),game_id INT); INSERT INTO Players (player_id,player_name,game_id) VALUES (1,'Player1',1),(2,'Player2',1),(3,'Player3',2),(4,'Player4',3),(5,'Player5',1);
SELECT G.game_name, COUNT(DISTINCT P.player_id) AS unique_players FROM Players P INNER JOIN Games G ON P.game_id = G.game_id GROUP BY G.game_name;
What is the minimum depth of any ocean floor mapping project site in the 'Ocean' schema?
CREATE SCHEMA Ocean; CREATE TABLE Mapping (site_id INT,depth FLOAT); INSERT INTO Mapping (site_id,depth) VALUES (1,5000.2),(2,4000.3),(3,3000.4),(4,2000.5),(5,1000.6);
SELECT MIN(depth) FROM Ocean.Mapping;
Delete all records from the 'safety_records' table where 'record_date' is after '2021-01-01'
CREATE TABLE safety_records (record_id INT PRIMARY KEY,record_date DATE,safety_rating INT);
DELETE FROM safety_records WHERE record_date > '2021-01-01';
What is the total number of guests who experienced heritage tours in Asia?
CREATE TABLE heritage_tours (tour_id INT,tour_name TEXT,region TEXT,guest_count INT); INSERT INTO heritage_tours (tour_id,tour_name,region,guest_count) VALUES (101,'Ancient China','Asia',500),(102,'Asian Royal Palaces','Asia',700),(103,'Indian Heritage','Asia',600);
SELECT SUM(guest_count) as total_guests FROM heritage_tours WHERE region = 'Asia';
What is the total cargo weight for all vessels in the Caribbean, sorted by vessel type?
CREATE TABLE vessel_cargo (id INT PRIMARY KEY,vessel_name VARCHAR(50),type VARCHAR(50),cargo_weight INT,location VARCHAR(50),timestamp DATETIME); INSERT INTO vessel_cargo (id,vessel_name,type,cargo_weight,location,timestamp) VALUES (1,'VesselD','Cargo',10000,'Caribbean','2021-10-01 10:00:00'),(2,'VesselE','Tanker',1500...
SELECT type, SUM(cargo_weight) FROM vessel_cargo WHERE location = 'Caribbean' GROUP BY type ORDER BY SUM(cargo_weight) DESC;
What is the average duration in months of all humanitarian assistance missions in the 'Africa' region?
CREATE TABLE humanitarian_missions (id INT,name TEXT,region TEXT,start_date DATE,end_date DATE); INSERT INTO humanitarian_missions (id,name,region,start_date,end_date) VALUES (1,'Mission 1','Africa','2017-01-01','2017-12-31');
SELECT AVG(DATEDIFF('month', start_date, end_date)) AS avg_duration_months FROM humanitarian_missions WHERE region = 'Africa';
What are the top 5 states with the highest threat intelligence metrics?
CREATE TABLE threat_intelligence (threat_id INT,state TEXT,metric FLOAT); INSERT INTO threat_intelligence (threat_id,state,metric) VALUES (1,'California',0.9),(2,'Texas',0.8),(3,'New York',0.7),(4,'Florida',0.6),(5,'Illinois',0.5);
SELECT state, AVG(metric) as avg_metric FROM threat_intelligence GROUP BY state ORDER BY avg_metric DESC LIMIT 5;
Display the makes and models of vehicles with safety test results in the 'safety_testing' table, grouped by make
CREATE TABLE safety_testing (id INT PRIMARY KEY,make VARCHAR(50),model VARCHAR(50),tests_passed INT);
SELECT make, model FROM safety_testing GROUP BY make;
What is the total premium collected from policyholders in each state?
CREATE TABLE policyholders (id INT,name VARCHAR(255),state VARCHAR(255),policy_type VARCHAR(255),premium FLOAT); INSERT INTO policyholders (id,name,state,policy_type,premium) VALUES (1,'John Doe','New York','Auto',1200),(2,'Jane Smith','California','Home',2000),(3,'Bob Johnson','California','Auto',1500),(4,'Alice Willi...
SELECT state, SUM(premium) FROM policyholders GROUP BY state;
List all the organizations in the 'Environment' category.
CREATE TABLE category (cat_id INT,name VARCHAR(255)); INSERT INTO category (cat_id,name) VALUES (1,'Arts & Culture'),(2,'Environment'),(3,'Health'),(4,'Education'); CREATE TABLE organization (org_id INT,name VARCHAR(255),cat_id INT); INSERT INTO organization (org_id,name,cat_id) VALUES (1,'CodeTutor',1),(2,'GreenPeace'...
SELECT name FROM organization WHERE cat_id = (SELECT cat_id FROM category WHERE name = 'Environment');
Which menu items have a food safety violation in the past year?
CREATE TABLE menu_items (id INT,name VARCHAR(50),restaurant_id INT); CREATE TABLE menu_item_inspections (menu_item_id INT,inspection_date DATE,violation BOOLEAN);
SELECT menu_items.name FROM menu_items JOIN menu_item_inspections ON menu_items.id = menu_item_inspections.menu_item_id WHERE violation = TRUE AND inspection_date >= DATEADD(year, -1, GETDATE());
What is the total number of parks in each city?
CREATE TABLE cities (id INT,name TEXT);CREATE TABLE parks (id INT,park_name TEXT,city_id INT);INSERT INTO cities (id,name) VALUES (1,'CityA'),(2,'CityB'),(3,'CityC');INSERT INTO parks (id,park_name,city_id) VALUES (1,'ParkX',1),(2,'ParkY',2),(3,'ParkZ',3);
SELECT city_id, COUNT(*) FROM parks GROUP BY city_id;
Which education programs are offered in 'region1' and 'region2'?
CREATE VIEW education_programs AS SELECT 'program1' AS program,'region1' AS region UNION SELECT 'program2','region1' UNION SELECT 'program3','region2';
SELECT DISTINCT region FROM education_programs WHERE region IN ('region1', 'region2');
What is the total number of evidence-based policies implemented in the West?
CREATE TABLE evidence_based_policies (policy_id INT,policy_name VARCHAR(255),state VARCHAR(255),region VARCHAR(255)); INSERT INTO evidence_based_policies (policy_id,policy_name,state,region) VALUES (1,'Policy X','California','West'),(2,'Policy Y','Oregon','West');
SELECT COUNT(*) FROM evidence_based_policies WHERE region = 'West';
Find artists with the highest and lowest attendance at their events.
CREATE TABLE artist_events (id INT,artist_name VARCHAR(255),event_name VARCHAR(255),attendance INT); INSERT INTO artist_events (id,artist_name,event_name,attendance) VALUES (1,'Vincent van Gogh','Starry Night Exhibition',1200),(2,'Claude Monet','Water Lilies Exhibition',1500),(3,'Edgar Degas','Ballerina Exhibition',800...
SELECT artist_name, CASE WHEN attendance = MAX(attendance) OVER () THEN 'Highest' ELSE 'Lowest' END AS attendance_type FROM artist_events;
Who are the top 5 artists with the most streams in the last 30 days?
CREATE TABLE StreamingData (stream_id INT,stream_date DATE,song_id INT,artist_name VARCHAR(255),streams INT); INSERT INTO StreamingData (stream_id,stream_date,song_id,artist_name,streams) VALUES (1,'2022-01-01',1,'Bad Bunny',100000),(2,'2022-01-02',2,'BTS',120000),(3,'2022-01-03',3,'Adele',90000),(4,'2022-01-04',4,'Tay...
SELECT artist_name, SUM(streams) as total_streams FROM StreamingData WHERE stream_date >= CURDATE() - INTERVAL 30 DAY GROUP BY artist_name ORDER BY total_streams DESC LIMIT 5;
What is the distribution of products by price range in the ethical fashion market?
CREATE TABLE products (product_id INT,price DECIMAL(10,2));CREATE TABLE price_ranges (price DECIMAL(10,2),range VARCHAR(20));
SELECT pr.range, COUNT(p.product_id) FROM products p JOIN price_ranges pr ON p.price BETWEEN pr.price - 5 AND pr.price + 5 GROUP BY pr.range;
What was the average donation amount by donors from urban areas in Q2 2020?
CREATE TABLE Donors (DonorID int,DonationDate date,DonationAmount numeric,DonorAreaType varchar(50));
SELECT AVG(DonationAmount) FROM (SELECT DonationAmount FROM Donors WHERE DonationDate BETWEEN '2020-04-01' AND '2020-06-30' AND DonorAreaType = 'Urban');
Calculate the average quantity of fish stock for each farmer who farms both Tuna and Mackerel?
CREATE TABLE FishStock (StockID INT,FarmerID INT,Species VARCHAR(50),Quantity INT,HarvestDate DATE); INSERT INTO FishStock (StockID,FarmerID,Species,Quantity,HarvestDate) VALUES (1,1,'Tuna',200,'2021-05-01'); INSERT INTO FishStock (StockID,FarmerID,Species,Quantity,HarvestDate) VALUES (2,1,'Mackerel',150,'2021-06-15');...
SELECT FarmerID, AVG(Quantity) FROM FishStock WHERE Species IN ('Tuna', 'Mackerel') GROUP BY FarmerID HAVING COUNT(DISTINCT Species) = 2;
Update the 'city' to 'Los Angeles' for records with 'bike_id' 200 in the 'PublicBikeSystems' table
CREATE TABLE PublicBikeSystems (bike_id INT,city VARCHAR(20),PRIMARY KEY (bike_id));
UPDATE PublicBikeSystems SET city = 'Los Angeles' WHERE bike_id = 200;
Display the total number of cases and billing amounts for cases that were not resolved by trial.
CREATE TABLE CaseResolutions (CaseID INT,CaseType VARCHAR(20),Resolution VARCHAR(20),BillingAmount DECIMAL(10,2)); INSERT INTO CaseResolutions (CaseID,CaseType,Resolution,BillingAmount) VALUES (1,'Civil','Plaintiff Verdict',7000.00),(2,'Civil','Settlement',3000.00);
SELECT COUNT(*), SUM(BillingAmount) FROM CaseResolutions WHERE Resolution != 'Trial';
List all space missions that had an astronaut from a country in Asia.
CREATE TABLE SpaceMissions (id INT,name VARCHAR(255),launch_date DATE);CREATE TABLE Astronauts (id INT,name VARCHAR(255),country VARCHAR(10),mission_id INT);CREATE VIEW Asia_Astronauts AS SELECT * FROM Astronauts WHERE country IN ('China','India','Japan','South Korea','North Korea','Indonesia','Vietnam','Malaysia','Tha...
SELECT name FROM SpaceMissions sm JOIN Astronauts a ON sm.id = a.mission_id WHERE a.country IN (SELECT country FROM Asia_Astronauts);
Identify the number of maintenance requests for each vehicle type and year in the 'maintenance' table
CREATE SCHEMA IF NOT EXISTS public_transport;CREATE TABLE IF NOT EXISTS public_transport.maintenance (maintenance_id SERIAL PRIMARY KEY,vehicle_type TEXT,request_date DATE);INSERT INTO public_transport.maintenance (vehicle_type,request_date) VALUES ('Bus','2022-02-01'),('Tram','2022-02-02'),('Bus','2022-03-03'),('Tram'...
SELECT EXTRACT(YEAR FROM request_date) AS year, vehicle_type, COUNT(*) FROM public_transport.maintenance GROUP BY EXTRACT(YEAR FROM request_date), vehicle_type;
How many food safety inspections occurred in 'LA' in 2022?
CREATE TABLE inspections (location VARCHAR(255),year INT,inspections_count INT); INSERT INTO inspections (location,year,inspections_count) VALUES ('LA',2022,45);
SELECT inspections_count FROM inspections WHERE location = 'LA' AND year = 2022;
How many climate communication campaigns were conducted in South America for projects focused on afforestation?
CREATE TABLE projects (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255),start_date DATE,end_date DATE,budget DECIMAL(10,2)); CREATE TABLE mitigation_activities (id INT PRIMARY KEY,project_id INT,activity VARCHAR(255),cost DECIMAL(10,2)); CREATE TABLE countries (id INT PRIMARY KEY,country VARCHAR(255),populatio...
SELECT COUNT(communication_campaigns.id) as num_communication_campaigns FROM projects JOIN communication_campaigns ON projects.id = communication_campaigns.project_id JOIN mitigation_activities ON projects.id = mitigation_activities.project_id WHERE projects.country = 'South America' AND mitigation_activities.activity ...
What is the total number of mental health facilities in each state with a cultural competency rating above 7 and a health equity rating below 6?
CREATE TABLE MentalHealthFacilities (Id INT,State VARCHAR(255),CulturalCompetencyRating INT,HealthEquityRating INT); INSERT INTO MentalHealthFacilities (Id,State,CulturalCompetencyRating,HealthEquityRating) VALUES (1,'California',9,6); INSERT INTO MentalHealthFacilities (Id,State,CulturalCompetencyRating,HealthEquityRa...
SELECT State, COUNT(*) FROM MentalHealthFacilities WHERE CulturalCompetencyRating > 7 AND HealthEquityRating < 6 GROUP BY State;
What is the number of units manufactured for each garment type by region in Q1 2021?
CREATE TABLE garment_manufacturing (garment_id INT,garment_type VARCHAR(50),region VARCHAR(50),production_date DATE,units_manufactured INT); CREATE TABLE garments (garment_id INT,garment_name VARCHAR(50));
SELECT garment_type, region, SUM(units_manufactured) FROM garment_manufacturing JOIN garments ON garment_manufacturing.garment_id = garments.garment_id WHERE EXTRACT(QUARTER FROM production_date) = 1 AND EXTRACT(YEAR FROM production_date) = 2021 GROUP BY garment_type, region;
What is the minimum depth of any marine protected area in the Indian Ocean?
CREATE TABLE marine_protected_areas (name TEXT,location TEXT,min_depth INTEGER,max_depth INTEGER); INSERT INTO marine_protected_areas (name,location,min_depth,max_depth) VALUES ('Area A','Indian',50,120),('Area B','Indian',100,250),('Area C','Indian',75,175);
SELECT MIN(min_depth) FROM marine_protected_areas WHERE location = 'Indian';
List the top 5 carbon pricing policies by total carbon price in North America, Europe, and Asia, for the year 2020.
CREATE TABLE carbon_pricing (country text,policy text,price decimal,year integer);
SELECT policy, SUM(price) as total_price FROM carbon_pricing WHERE year = 2020 AND country IN ('North America', 'Europe', 'Asia') GROUP BY policy ORDER BY total_price DESC LIMIT 5;
Show the number of active projects and total budget for 'Disaster Response' sector projects in the 'Middle East' region as of 2021-01-01.
CREATE TABLE Projects (project_id INT,project_name VARCHAR(255),sector VARCHAR(255),region VARCHAR(255),start_date DATE,end_date DATE,budget INT); INSERT INTO Projects (project_id,project_name,sector,region,start_date,end_date,budget) VALUES (1,'ProjectA','Disaster Response','Middle East','2021-01-01','2022-12-31',5000...
SELECT COUNT(project_id) AS active_projects, SUM(budget) AS total_budget FROM Projects WHERE sector = 'Disaster Response' AND region = 'Middle East' AND end_date >= '2021-01-01';
What is the total production (bbl) for wells in the 'Russia' region for the last 3 years?
CREATE TABLE well_production (well_id INT,region VARCHAR(20),year INT,production INT); INSERT INTO well_production (well_id,region,year,production) VALUES (1,'Russia',2020,300000),(2,'Russia',2019,320000),(3,'Houston',2020,150000);
SELECT SUM(production) FROM well_production WHERE region = 'Russia' AND year >= 2018;
What is the win rate for each attorney by region?
CREATE TABLE Wins (CaseID INT,AttorneyID INT,Region VARCHAR(50),CaseOutcome VARCHAR(50)); INSERT INTO Wins (CaseID,AttorneyID,Region,CaseOutcome) VALUES (1,1,'Northeast','Won'),(2,1,'Northeast','Lost'),(3,2,'Northeast','Won'),(4,2,'Northeast','Won'),(5,3,'Midwest','Won'),(6,3,'Midwest','Lost'),(7,4,'Southwest','Won'),(...
SELECT a.Name AS AttorneyName, a.Region AS Region, COUNT(w.CaseID) * 100.0 / SUM(COUNT(w.CaseID)) OVER (PARTITION BY a.Region) AS WinRate FROM Attorneys a JOIN Wins w ON a.AttorneyID = w.AttorneyID GROUP BY a.Name, a.Region;
What are the biosensor technology development records for 'BioSensor-B'?
CREATE TABLE biosensor_tech_development (id INT,tech_type TEXT,status TEXT,date_created DATE);
SELECT * FROM biosensor_tech_development WHERE tech_type = 'BioSensor-B';
Delete all records from the Games table where the genre is 'Puzzle'.
CREATE TABLE Games (GameID INT,GameName VARCHAR(20),Genre VARCHAR(10),VR BIT); INSERT INTO Games VALUES (1,'GameA','Action',1),(2,'GameB','Puzzle',0),(3,'GameC','Adventure',1);
DELETE FROM Games WHERE Genre = 'Puzzle';
Who are the directors who have produced more than 3 movies with an average rating of 8 or higher?
CREATE TABLE movies (id INT,title VARCHAR(255),rating FLOAT,release_year INT,director VARCHAR(50)); INSERT INTO movies (id,title,rating,release_year,director) VALUES (1,'Movie1',8.5,2010,'Director1'),(2,'Movie2',8.2,2012,'Director1'),(3,'Movie3',6.8,2015,'Director1'),(4,'Movie4',8.8,2011,'Director2'),(5,'Movie5',7.5,20...
SELECT director FROM movies WHERE rating >= 8 GROUP BY director HAVING COUNT(*) > 3;
Find the total research grant amount awarded to each PI in descending order.
CREATE TABLE faculty (faculty_id INT,name VARCHAR(50),department VARCHAR(50)); INSERT INTO faculty (faculty_id,name,department) VALUES (1,'John Doe','Physics'); INSERT INTO faculty (faculty_id,name,department) VALUES (2,'Jane Smith','Chemistry'); CREATE TABLE grants (grant_id INT,pi_faculty_id INT,amount DECIMAL(10,2))...
SELECT pi_faculty_id, SUM(amount) as total_grant_amount FROM grants GROUP BY pi_faculty_id ORDER BY total_grant_amount DESC;
What is the total funding raised by startups founded by women in the AI sector?
CREATE TABLE company (id INT,name TEXT,industry TEXT,founder_gender TEXT); INSERT INTO company (id,name,industry,founder_gender) VALUES (1,'BrainyStart','AI','Female'); INSERT INTO company (id,name,industry,founder_gender) VALUES (2,'Shopify','E-commerce','Male'); CREATE TABLE funding_round (company_id INT,round_size I...
SELECT SUM(funding_round.round_size) FROM company INNER JOIN funding_round ON company.id = funding_round.company_id WHERE company.founder_gender = 'Female' AND company.industry = 'AI';
What is the total biomass of fish in freshwater farms?
CREATE TABLE freshwater_farms (id INT,species VARCHAR(50),biomass FLOAT); INSERT INTO freshwater_farms (id,species,biomass) VALUES (1,'Tilapia',1500.0),(2,'Catfish',2000.0);
SELECT SUM(biomass) FROM freshwater_farms WHERE species IN ('Tilapia', 'Catfish');
What is the average number of days to resolve a security incident for each sector?
CREATE TABLE incidents (incident_id INT,incident_sector VARCHAR(255),incident_resolution_time INT);
SELECT incident_sector, AVG(incident_resolution_time) as avg_resolution_time FROM incidents GROUP BY incident_sector;
What is the average number of hospital beds in rural hospitals of Delaware that have more than 150 beds?
CREATE TABLE hospitals (id INT,name TEXT,location TEXT,beds INT,rural BOOLEAN); INSERT INTO hospitals (id,name,location,beds,rural) VALUES (1,'Hospital A','Delaware',180,true),(2,'Hospital B','Delaware',220,true);
SELECT AVG(beds) FROM hospitals WHERE location = 'Delaware' AND rural = true AND beds > 150;
What are the Green building certifications in cities with smart city projects using geothermal technology?
CREATE TABLE green_buildings (id INT,name VARCHAR(50),city VARCHAR(50),country VARCHAR(50),certification VARCHAR(50)); INSERT INTO green_buildings (id,name,city,country,certification) VALUES (1,'GreenHeights','San Francisco','USA','LEED Platinum'); CREATE TABLE smart_cities (id INT,city VARCHAR(50),country VARCHAR(50),...
SELECT g.certification, s.city, s.technology FROM green_buildings g INNER JOIN smart_cities s ON g.city = s.city WHERE s.technology = 'geothermal';
What's the average donation amount for each country?
CREATE TABLE donations (id INT,donation_amount DECIMAL,country TEXT); INSERT INTO donations (id,donation_amount,country) VALUES (1,150.00,'Germany'),(2,250.00,'Germany'),(3,300.00,'Canada'),(4,50.00,'USA'),(5,100.00,'USA');
SELECT country, AVG(donation_amount) FROM donations GROUP BY country;
Which football teams in the 'bundesliga_teams' table have a stadium with a capacity greater than 50000?
CREATE TABLE bundesliga_teams (team_name VARCHAR(50),stadium_name VARCHAR(50),stadium_capacity INT);
SELECT team_name FROM bundesliga_teams WHERE stadium_capacity > 50000;
What is the total renewable energy production in MWh for the state of New York in 2021?
CREATE TABLE renewable_energy (state VARCHAR(20),production DECIMAL(10,2),year INT); INSERT INTO renewable_energy (state,production,year) VALUES ('New York',2500.00,2021),('New York',2700.00,2021),('New York',2900.00,2021);
SELECT SUM(production) FROM renewable_energy WHERE state = 'New York' AND year = 2021;
How many incidents were recorded for Vessel3 between January 1, 2021 and June 30, 2021?
CREATE TABLE VesselIncidents(IncidentID INT,VesselID INT,IncidentType TEXT,IncidentDate DATETIME); INSERT INTO VesselIncidents(IncidentID,VesselID,IncidentType,IncidentDate) VALUES (1,3,'Collision','2021-03-15 14:30:00'),(2,3,'Mechanical Failure','2021-05-02 08:00:00');
SELECT COUNT(*) FROM VesselIncidents WHERE VesselID = 3 AND IncidentDate BETWEEN '2021-01-01' AND '2021-06-30';
Update the water temperature for record ID 4 to 9.5 degrees.
CREATE TABLE temperature_data (id INT,fish_id INT,record_date DATE,water_temp DECIMAL(5,2)); INSERT INTO temperature_data (id,fish_id,record_date,water_temp) VALUES (1,1,'2022-03-01',27.5),(2,1,'2022-03-15',28.2),(3,2,'2022-03-01',8.3),(4,2,'2022-03-15',8.9);
UPDATE temperature_data SET water_temp = 9.5 WHERE id = 4;
List all urban gardens in 'North America' with their respective sizes.
CREATE TABLE gardens (id INT,name TEXT,location TEXT,size INT); INSERT INTO gardens (id,name,location,size) VALUES (1,'Garden A','USA',500),(2,'Garden B','Canada',600),(3,'Garden C','Mexico',400);
SELECT name, size FROM gardens WHERE location LIKE 'North America';
Get total calories for each product with 'organic' in the name.
CREATE TABLE nutrition (product_id VARCHAR(10),calories INTEGER); INSERT INTO nutrition (product_id,calories) VALUES ('P001',150),('P002',200),('P003',250),('P004',120),('P005',180);CREATE TABLE products (product_id VARCHAR(10),name VARCHAR(50)); INSERT INTO products (product_id,name) VALUES ('P001','Apples'),('P002','...
SELECT products.name, SUM(nutrition.calories) FROM nutrition JOIN products ON nutrition.product_id = products.product_id WHERE products.name LIKE '%organic%' GROUP BY products.name;
What is the average population in drought-affected counties in the state of California?
CREATE TABLE CountyDroughtImpact (county_name VARCHAR(20),state VARCHAR(20),drought_status VARCHAR(10),population INT); INSERT INTO CountyDroughtImpact (county_name,state,drought_status,population) VALUES ('Los Angeles','California','Drought',1000000),('San Diego','California','Drought',800000);
SELECT AVG(population) FROM CountyDroughtImpact WHERE state = 'California' AND drought_status = 'Drought';
Find the top 3 content creators with the most followers from Canada, ordered by the number of followers in descending order.
CREATE TABLE content_creators (id INT,name VARCHAR(255),country VARCHAR(255)); INSERT INTO content_creators (id,name,country) VALUES (1,'Creator F','Canada'),(2,'Creator G','Canada'),(3,'Creator H','Canada'),(4,'Creator I','Brazil'),(5,'Creator J','Argentina');
SELECT name, COUNT(*) AS followers FROM content_creators WHERE country = 'Canada' GROUP BY name ORDER BY followers DESC LIMIT 3;
What is the total value of Defense contracts awarded to women-owned businesses in 2019?
CREATE TABLE DefenseContracts (contract_id INT,contractor_name VARCHAR(255),gender VARCHAR(255),contract_date DATE,contract_value DECIMAL(10,2)); INSERT INTO DefenseContracts (contract_id,contractor_name,gender,contract_date,contract_value) VALUES (1,'TechCo','Female','2019-01-15',50000),(2,'GreenTech','Male','2019-02-...
SELECT SUM(contract_value) FROM DefenseContracts WHERE gender = 'Female' AND contract_date BETWEEN '2019-01-01' AND '2019-12-31';
List all IoT sensors that monitor Soil Moisture or Temperature.
CREATE TABLE IoT_Sensors (id INT,sensor_type VARCHAR(50),Farm_id INT); INSERT INTO IoT_Sensors (id,sensor_type,Farm_id) VALUES (1,'Soil Moisture',1),(2,'Temperature',2),(3,'Humidity',3);
SELECT sensor_type FROM IoT_Sensors WHERE sensor_type IN ('Soil Moisture', 'Temperature');
How many military bases of each type are there for each country?
CREATE TABLE MilitaryBases (BaseID INT,BaseType VARCHAR(255),BaseName VARCHAR(255),Country VARCHAR(255));
SELECT Country, BaseType, COUNT(*) as BaseCount FROM MilitaryBases GROUP BY Country, BaseType;
What is the average calorie count of vegetarian meals served in Canada?
CREATE TABLE meals (id INT,name TEXT,cuisine TEXT,calorie_count INT,country TEXT); INSERT INTO meals (id,name,cuisine,calorie_count,country) VALUES (1,'Quinoa Salad','Vegetarian',350,'Canada'); INSERT INTO meals (id,name,cuisine,calorie_count,country) VALUES (2,'Lentil Soup','Vegetarian',200,'Canada');
SELECT AVG(calorie_count) FROM meals WHERE cuisine = 'Vegetarian' AND country = 'Canada';
Which country has the largest textile industry in terms of quantity sourced?
CREATE TABLE textiles (country VARCHAR(10),quantity INT); INSERT INTO textiles (country,quantity) VALUES ('China',15000),('India',12000),('Bangladesh',9000);
SELECT country, MAX(quantity) FROM textiles GROUP BY country LIMIT 1;
What is the total number of bookings for virtual tours in each region, sorted by the number of bookings in descending order?
CREATE TABLE virtual_tours (tour_id INT,region VARCHAR(20),bookings INT); INSERT INTO virtual_tours (tour_id,region,bookings) VALUES (1,'North America',500),(2,'North America',600),(3,'Europe',400),(4,'Europe',300),(5,'South America',200),(6,'South America',100);
SELECT region, SUM(bookings) AS total_bookings FROM virtual_tours GROUP BY region ORDER BY total_bookings DESC;
What is the average volunteer hours per volunteer in 'volunteers' table?
CREATE TABLE volunteers (id INT,name TEXT,volunteer_hours INT);
SELECT AVG(volunteer_hours) as avg_volunteer_hours FROM volunteers;
Which aircraft have spent the most time in flight for a specific airline?
CREATE TABLE aircrafts (aircraft_id INT,model VARCHAR(50),airline_id INT); INSERT INTO aircrafts (aircraft_id,model,airline_id) VALUES (1,'B737',101),(2,'A320',101),(3,'B747',101),(4,'B777',101),(5,'B787',101); CREATE TABLE flight_hours (flight_hour_id INT,aircraft_id INT,flight_hours DECIMAL(18,2)); INSERT INTO flight...
SELECT a.model, SUM(fh.flight_hours) as total_flight_hours FROM aircrafts a JOIN flight_hours fh ON a.aircraft_id = fh.aircraft_id WHERE a.airline_id = 101 GROUP BY a.model ORDER BY total_flight_hours DESC;
What is the total funding amount for startups founded by immigrants in the renewable energy sector?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founding_year INT,founder_citizenship TEXT); INSERT INTO companies (id,name,industry,founding_year,founder_citizenship) VALUES (1,'SolarRev','Renewable Energy',2020,'Foreign'); INSERT INTO companies (id,name,industry,founding_year,founder_citizenship) VALUES (2,'Gr...
SELECT SUM(funding_records.funding_amount) FROM companies JOIN funding_records ON companies.id = funding_records.company_id WHERE companies.founder_citizenship != 'US Citizen' AND companies.industry = 'Renewable Energy';
List the number of vehicles in need of maintenance for each type
CREATE TABLE vehicle_maintenance (vehicle_id INT,vehicle_type VARCHAR(10),maintenance_needed BOOLEAN); INSERT INTO vehicle_maintenance (vehicle_id,vehicle_type,maintenance_needed) VALUES (1,'Bus',true),(2,'Train',false),(3,'Bus',false),(4,'Tram',true);
SELECT vehicle_type, COUNT(*) as number_of_vehicles FROM vehicle_maintenance WHERE maintenance_needed = true GROUP BY vehicle_type;
What is the average age of players who play games in the RPG genre?
CREATE TABLE player (player_id INT,name VARCHAR(50),age INT,game_genre VARCHAR(20)); INSERT INTO player (player_id,name,age,game_genre) VALUES (1,'John Doe',25,'Racing'); INSERT INTO player (player_id,name,age,game_genre) VALUES (2,'Jane Smith',30,'RPG'); INSERT INTO player (player_id,name,age,game_genre) VALUES (3,'Al...
SELECT AVG(age) FROM player WHERE game_genre = 'RPG';
Update the name of a country from 'Republic of Z' to 'Democratic Republic of Z'
CREATE TABLE countries (id INT,name VARCHAR);
UPDATE countries SET name = 'Democratic Republic of Z' WHERE name = 'Republic of Z';
Find the maximum threat intelligence report value in the last quarter.
CREATE TABLE Threat_Intel (id INT,report_number VARCHAR(50),report_date DATE,report_value FLOAT);
SELECT MAX(report_value) FROM Threat_Intel WHERE report_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH);
What is the total number of mental health parity violations in each region?
CREATE TABLE ParityViolations (ViolationID int,RegionID int,ViolationCount int);
SELECT RegionID, SUM(ViolationCount) as TotalViolations FROM ParityViolations GROUP BY RegionID;
What is the total exploration cost in Nigeria for the year 2020 in the Exploration_Data table?
CREATE TABLE Exploration_Data (country text,exploration_date date,exploration_cost real); INSERT INTO Exploration_Data (country,exploration_date,exploration_cost) VALUES ('Nigeria','2020-01-01',50000),('Nigeria','2020-02-01',60000),('Nigeria','2020-12-01',70000);
SELECT SUM(exploration_cost) FROM Exploration_Data WHERE country = 'Nigeria' AND exploration_date BETWEEN '2020-01-01' AND '2020-12-31';
Calculate the total number of maintenance activities for public works projects in Florida
CREATE TABLE Infrastructure (id INT,name VARCHAR(255),type VARCHAR(255),location VARCHAR(255),is_public_works BOOLEAN); CREATE TABLE Maintenance (id INT,infrastructure_id INT,maintenance_date DATE,maintenance_type VARCHAR(255)); INSERT INTO Infrastructure (id,name,type,location,is_public_works) VALUES (1,'Road A','Road...
SELECT COUNT(*) FROM Maintenance INNER JOIN Infrastructure ON Maintenance.infrastructure_id = Infrastructure.id WHERE Infrastructure.location = 'Florida' AND Infrastructure.is_public_works = TRUE;
What is the average donation amount per day for each country?
CREATE TABLE daily_donations (country TEXT,donation_date DATE,donation FLOAT); INSERT INTO daily_donations (country,donation_date,donation) VALUES ('Haiti','2021-01-01',50.00),('Haiti','2021-01-02',50.00),('Pakistan','2021-01-01',100.00),('Pakistan','2021-01-02',100.00),('Syria','2021-01-01',150.00),('Syria','2021-01-0...
SELECT country, AVG(donation) OVER (PARTITION BY country) AS avg_donation_per_day FROM daily_donations;
What is the average age of offenders who committed violent crimes in the last 5 years, grouped by the type of violence?
CREATE TABLE Offenders (ID INT,Age INT,CrimeType VARCHAR(255)); INSERT INTO Offenders (ID,Age,CrimeType) VALUES (1,25,'Murder'),(2,30,'Assault'),(3,35,'Robbery');
SELECT CrimeType, AVG(Age) as AvgAge FROM Offenders WHERE CrimeType IN ('Murder', 'Assault') AND YEAR(CURRENT_DATE) - YEAR(DateOfCrime) <= 5 GROUP BY CrimeType;
What is the total quantity of products sold by each brand, ordered by the total quantity in descending order, for the 'ethical_products' table?
CREATE TABLE ethical_products (product_id INT,brand VARCHAR(255),quantity_sold INT); INSERT INTO ethical_products (product_id,brand,quantity_sold) VALUES (1,'BrandA',500),(2,'BrandB',300),(3,'BrandC',700);
SELECT brand, SUM(quantity_sold) AS total_quantity_sold FROM ethical_products GROUP BY brand ORDER BY total_quantity_sold DESC;
Display the smart contracts with the lowest and highest transaction counts for each decentralized application.
CREATE TABLE Transactions (TransactionID int,ContractAddress varchar(50),DAppName varchar(50),Transactions int); INSERT INTO Transactions (TransactionID,ContractAddress,DAppName,Transactions) VALUES (1,'ContractA','DApp1',100),(2,'ContractB','DApp1',200),(3,'ContractC','DApp2',300),(4,'ContractD','DApp2',400),(5,'Contr...
SELECT DAppName, MIN(Transactions) as MinTransactions, MAX(Transactions) as MaxTransactions FROM Transactions GROUP BY DAppName;
What is the average harvest date for the Shrimp_Farming table?
CREATE TABLE Shrimp_Farming (Farm_ID INT,Farm_Name TEXT,Harvest_Date DATE,Quantity_Harvested INT); INSERT INTO Shrimp_Farming (Farm_ID,Farm_Name,Harvest_Date,Quantity_Harvested) VALUES (1,'Farm 1','2021-04-15',3000),(2,'Farm 2','2021-05-01',4000),(3,'Farm 3','2021-05-10',3500);
SELECT AVG(DATEDIFF('2021-05-01', Harvest_Date))/2 AS Average_Harvest_Date FROM Shrimp_Farming;
List the vessels that have never visited port 'NY'
CREATE TABLE ports (port_id INT,port_name VARCHAR(50)); INSERT INTO ports (port_id,port_name) VALUES (1,'LA'),(2,'NY'); CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(50)); INSERT INTO vessels (vessel_id,vessel_name) VALUES (1,'Vessel1'),(2,'Vessel2'),(3,'Vessel3'); CREATE TABLE port_visits (visit_id INT,vesse...
SELECT v.vessel_name FROM vessels v WHERE v.vessel_id NOT IN (SELECT pv.vessel_id FROM port_visits pv WHERE pv.port_id = (SELECT port_id FROM ports WHERE port_name = 'NY'));
What is the total number of employees working in coal mines in India?
CREATE TABLE Mines (MineID INT,MineType VARCHAR(255),Country VARCHAR(255),NumEmployees INT); INSERT INTO Mines (MineID,MineType,Country,NumEmployees) VALUES (1,'Coal','Canada',500); INSERT INTO Mines (MineID,MineType,Country,NumEmployees) VALUES (2,'Gold','Canada',600); INSERT INTO Mines (MineID,MineType,Country,NumEmp...
SELECT SUM(m.NumEmployees) as TotalEmployees FROM Mines m WHERE m.MineType = 'Coal' AND m.Country = 'India';
What is the minimum processing time for each algorithm in the Algorithmic Fairness table?
CREATE TABLE Algorithmic_Fairness (algorithm_id INT,algorithm_name VARCHAR(50),processing_time FLOAT); INSERT INTO Algorithmic_Fairness (algorithm_id,algorithm_name,processing_time) VALUES (1,'AlgoA',0.15),(2,'AlgoB',0.22),(3,'AlgoC',0.31),(4,'AlgoD',0.17);
SELECT algorithm_name, MIN(processing_time) FROM Algorithmic_Fairness GROUP BY algorithm_name;
What is the average number of days it takes for a criminal case to be resolved in Alameda County in 2020?
CREATE TABLE criminal_cases (id INT PRIMARY KEY,county VARCHAR(255),case_year INT,resolution_days INT); INSERT INTO criminal_cases (id,county,case_year,resolution_days) VALUES (1,'Alameda',2020,90),(2,'Alameda',2020,120),(3,'Alameda',2020,75),(4,'Alameda',2020,100),(5,'Alameda',2020,110);
SELECT AVG(resolution_days) FROM criminal_cases WHERE county = 'Alameda' AND case_year = 2020;
What is the minimum ESG score for investments in the Tech sector?
CREATE TABLE investments(id INT,sector VARCHAR(20),esg_score INT); INSERT INTO investments VALUES(1,'Tech',85),(2,'Healthcare',75),(3,'Tech',82);
SELECT MIN(esg_score) as min_esg_score FROM investments WHERE sector = 'Tech';
What is the total revenue for online art auctions in the Americas by year?
CREATE TABLE Auctions (AuctionID INT,AuctionName TEXT,Year INT,Region TEXT,Revenue DECIMAL(10,2)); INSERT INTO Auctions (AuctionID,AuctionName,Year,Region,Revenue) VALUES (1,'Christie''s NY Online',2019,'Americas',4500000); INSERT INTO Auctions (AuctionID,AuctionName,Year,Region,Revenue) VALUES (2,'Sotheby''s LA Online...
SELECT Year, SUM(Revenue) as TotalRevenue FROM Auctions WHERE Region = 'Americas' AND AuctionName LIKE '%Online%' GROUP BY Year;
List the top 3 consumers of ethical fashion by total spending on sustainable garments.
CREATE TABLE consumers (id INT,name VARCHAR(100),country VARCHAR(50),spend DECIMAL(10,2)); INSERT INTO consumers (id,name,country,spend) VALUES (1,'Alice','USA',500.00),(2,'Bob','UK',450.00),(3,'Charlie','Germany',600.00);
SELECT name, country, SUM(spend) as total_spend FROM consumers GROUP BY country ORDER BY total_spend DESC LIMIT 3;
What is the sum of sales for vegan skincare products in the UK in February?
CREATE TABLE sales (sale_id INT,product_id INT,sale_date DATE,quantity INT,price DECIMAL(10,2),is_vegan BOOLEAN,country VARCHAR(255)); INSERT INTO sales (sale_id,product_id,sale_date,quantity,price,is_vegan,country) VALUES (1,1,'2022-02-01',3,15.99,true,'UK'),(2,2,'2022-02-02',1,39.99,false,'US'),(3,3,'2022-03-01',2,9....
SELECT SUM(quantity * price) FROM sales WHERE is_vegan = true AND EXTRACT(MONTH FROM sale_date) = 2 AND country = 'UK';
Which countries have more than 5 marine protected areas?
CREATE TABLE marine_protected_areas (mpa_id INT,name TEXT,country TEXT,avg_depth FLOAT);
SELECT country, COUNT(*) FROM marine_protected_areas GROUP BY country HAVING COUNT(*) > 5;
What is the total number of funding records for companies with female founders in the Healthcare industry?
CREATE TABLE Companies (id INT,name VARCHAR(50),industry VARCHAR(50),country VARCHAR(50),founding_year INT,founder_gender VARCHAR(10)); CREATE TABLE Funding (id INT,company_name VARCHAR(50),funding_amount INT); INSERT INTO Companies (id,name,industry,country,founding_year,founder_gender) VALUES (1,'HealthHer','Healthca...
SELECT COUNT(*) as funding_records_count FROM Funding INNER JOIN Companies ON Funding.company_name = Companies.name WHERE Companies.industry = 'Healthcare' AND Companies.founder_gender = 'Female';
Get the city with the least number of electric vehicle sales.
CREATE TABLE CitySales (City VARCHAR(50),Quantity INT); INSERT INTO CitySales (City,Quantity) VALUES ('San Francisco',2500),('Los Angeles',3000),('New York',1800);
SELECT City, MIN(Quantity) FROM CitySales;
Calculate the average budget for accessible buildings in the 'East' region
CREATE TABLE support_programs (program_id INT,program_name VARCHAR(30),budget DECIMAL(10,2),region VARCHAR(20)); INSERT INTO support_programs (program_id,program_name,budget,region) VALUES (1,'Mobility Support',25000,'North'),(2,'Assistive Technology',30000,'South'),(3,'Note Taking',15000,'East'),(4,'Diversity Training...
SELECT AVG(budget) FROM support_programs WHERE program_name = 'Accessible Buildings' AND region = 'East';
What is the maximum number of affected users for data breaches in Latin America?
CREATE TABLE data_breaches (id INT,region TEXT,affected_users INT); INSERT INTO data_breaches (id,region,affected_users) VALUES (1,'Latin America',10000); INSERT INTO data_breaches (id,region,affected_users) VALUES (2,'North America',5000); INSERT INTO data_breaches (id,region,affected_users) VALUES (3,'Latin America',...
SELECT MAX(affected_users) FROM data_breaches WHERE region = 'Latin America';
What is the total annual production of Terbium from all mines in 2020?
CREATE TABLE mine (id INT,name TEXT,location TEXT,Terbium_annual_production FLOAT,timestamp TIMESTAMP); INSERT INTO mine (id,name,location,Terbium_annual_production,timestamp) VALUES (1,'Australian Mine','Australia',1500.5,'2020-01-01'),(2,'Californian Mine','USA',1700.3,'2020-01-01'),(3,'Brazilian Mine','Brazil',1000....
SELECT SUM(Terbium_annual_production) FROM mine WHERE EXTRACT(YEAR FROM timestamp) = 2020;
What is the daily water consumption for each mining site in the last 60 days, ordered by date?
CREATE TABLE water_consumption (site_id INT,consumption_date DATE,water_amount INT); INSERT INTO water_consumption (site_id,consumption_date,water_amount) VALUES (1,'2022-01-01',1000),(1,'2022-01-02',1500),(2,'2022-01-01',2000);
SELECT site_id, consumption_date, AVG(water_amount) as avg_water_amount FROM water_consumption WHERE consumption_date >= CURRENT_DATE - INTERVAL '60 days' GROUP BY site_id, consumption_date ORDER BY consumption_date;
List the countries with their respective average stock levels.
CREATE TABLE FarmLocation (LocationID INT,FarmName VARCHAR(50),Country VARCHAR(50),AvgStockLevel DECIMAL(5,2)); INSERT INTO FarmLocation (LocationID,FarmName,Country,AvgStockLevel) VALUES (1,'FishFirst Farm','United States',450.00); INSERT INTO FarmLocation (LocationID,FarmName,Country,AvgStockLevel) VALUES (2,'Seafood...
SELECT Country, AVG(AvgStockLevel) FROM FarmLocation GROUP BY Country;
What is the total funding for biotech startups in Massachusetts?
CREATE SCHEMA if not exists biotech; CREATE TABLE if not exists biotech.startups (id INT,name TEXT,location TEXT,funding FLOAT); INSERT INTO biotech.startups (id,name,location,funding) VALUES (1,'StartupA','Massachusetts',4000000.00); INSERT INTO biotech.startups (id,name,location,funding) VALUES (2,'StartupB','Califor...
SELECT SUM(funding) FROM biotech.startups WHERE location = 'Massachusetts';
Who are the top 3 artists with the most songs in the jazz genre?
CREATE TABLE artists (id INT,name TEXT); CREATE TABLE songs_artists (song_id INT,artist_id INT); CREATE TABLE songs (id INT,title TEXT,length FLOAT,genre TEXT); INSERT INTO artists (id,name) VALUES (1,'Artist1'),(2,'Artist2'),(3,'Artist3'); INSERT INTO songs_artists (song_id,artist_id) VALUES (1,1),(2,2),(3,1),(4,3); I...
SELECT artists.name, COUNT(songs.id) AS song_count FROM artists JOIN songs_artists ON artists.id = songs_artists.artist_id JOIN songs ON songs_artists.song_id = songs.id WHERE songs.genre = 'jazz' GROUP BY artists.name ORDER BY song_count DESC LIMIT 3;
How many dispensaries were there in the city of Denver in the year 2020?
CREATE TABLE dispensaries (id INT,city VARCHAR(50),year INT,count INT); INSERT INTO dispensaries (id,city,year,count) VALUES (1,'Denver',2020,100);
SELECT SUM(count) FROM dispensaries WHERE city = 'Denver' AND year = 2020;
Which districts have seen a decrease in lifelong learning program enrollment in the last 5 years?
CREATE TABLE lifelong_learning (student_id INT,district_id INT,year INT,enrolled BOOLEAN); INSERT INTO lifelong_learning (student_id,district_id,year,enrolled) VALUES (1,1001,2016,true),(2,1001,2017,true),(3,1001,2018,false),(4,1001,2019,false),(5,1001,2020,true),(6,1002,2016,true),(7,1002,2017,true),(8,1002,2018,false...
SELECT district_id, year, CASE WHEN LAG(enrolled) OVER (PARTITION BY district_id ORDER BY year) = true AND enrolled = false THEN 1 ELSE 0 END as enrollment_decreased FROM lifelong_learning WHERE year BETWEEN 2016 AND 2020 GROUP BY district_id, year HAVING SUM(enrollment_decreased) > 0;