instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total number of emergency calls and fire incidents in the city of Oakland?
CREATE TABLE emergency_calls (id INT,call_type VARCHAR(255),call_date TIMESTAMP); INSERT INTO emergency_calls (id,call_type,call_date) VALUES (1,'Medical Emergency','2022-01-01 12:00:00'); CREATE TABLE fire_incidents (id INT,incident_type VARCHAR(255),incident_date TIMESTAMP); INSERT INTO fire_incidents (id,incident_ty...
SELECT COUNT(*) FROM emergency_calls UNION ALL SELECT COUNT(*) FROM fire_incidents;
How many traffic violations were reported in districts with the highest and lowest population densities in 2019?
CREATE TABLE districts (id INT,name TEXT,population INT,area FLOAT); INSERT INTO districts (id,name,population,area) VALUES (1,'DistrictA',50000,50),(2,'DistrictB',100000,100),(3,'DistrictC',25000,20); CREATE TABLE violations (id INT,district_id INT,year INT,num_violations INT); INSERT INTO violations (id,district_id,y...
SELECT v1.num_violations + v2.num_violations FROM (SELECT dv.num_violations FROM violations dv INNER JOIN districts d ON dv.district_id = d.id ORDER BY d.population/d.area DESC LIMIT 1) v1, (SELECT dv.num_violations FROM violations dv INNER JOIN districts d ON dv.district_id = d.id ORDER BY d.population/d.area LIMIT 1)...
List all museums and their total exhibition space, in square feet, along with the number of artworks in their collection.
CREATE TABLE museums (id INT,name VARCHAR(50),location VARCHAR(30),exhibition_space INT); INSERT INTO museums (id,name,location,exhibition_space) VALUES (1,'Museum1','NYC',50000),(2,'Museum2','LA',75000); CREATE TABLE artworks (id INT,museum_id INT,title VARCHAR(50)); INSERT INTO artworks (id,museum_id,title) VALUES (1...
SELECT m.name, m.location, m.exhibition_space, COUNT(a.id) as artwork_count FROM museums m LEFT JOIN artworks a ON m.id = a.museum_id GROUP BY m.id;
What is the total crop yield for small-scale farms (less than 50 acres) in the United States?
CREATE TABLE farms (id INT,farm_name VARCHAR(50),acres INT,total_yield INT); INSERT INTO farms (id,farm_name,acres,total_yield) VALUES (1,'Farm 1',25,10000),(2,'Farm 2',75,20000),(3,'Farm 3',45,15000),(4,'Farm 4',55,25000),(5,'Farm 5',35,12000);
SELECT SUM(total_yield) FROM farms WHERE acres < 50;
What is the total number of community engagement events by category?
CREATE TABLE community_engagement (id INT,event_name VARCHAR(255),category VARCHAR(255),country VARCHAR(255)); INSERT INTO community_engagement (id,event_name,category,country) VALUES (1,'Dance Performance','Architecture','Greece'),(2,'Music Concert','Architecture','Italy'); CREATE VIEW community_engagement_by_category...
SELECT category, SUM(event_count) as total_events FROM community_engagement_by_category;
For each team, find the number of ticket sales in each month of 2023, ranked from highest to lowest.
CREATE TABLE Teams (TeamID INT,TeamName VARCHAR(50)); CREATE TABLE TicketSales (TicketID INT,TeamID INT,SaleDate DATE); INSERT INTO Teams (TeamID,TeamName) VALUES (1,'TeamA'),(2,'TeamB'); INSERT INTO TicketSales (TicketID,TeamID,SaleDate) VALUES (1,1,'2023-01-01'),(2,1,'2023-04-03'),(3,2,'2023-03-02'),(4,2,'2023-01-04'...
SELECT TeamName, EXTRACT(MONTH FROM SaleDate) AS Month, COUNT(*) AS SaleCount FROM TicketSales JOIN Teams ON TicketSales.TeamID = Teams.TeamID GROUP BY TeamName, Month ORDER BY TeamName, SaleCount DESC;
What is the average mass of chemicals produced per day?
CREATE TABLE ChemicalProduction (date DATE,chemical VARCHAR(10),mass FLOAT); INSERT INTO ChemicalProduction (date,chemical,mass) VALUES ('2021-01-01','A',100),('2021-01-01','B',150),('2021-01-02','A',120),('2021-01-02','B',170);
SELECT date, AVG(mass) as AvgMass FROM ChemicalProduction GROUP BY date;
Insert a new movie 'Black Panther 2' with a rating of 4.6 and a 2022 release.
CREATE TABLE movies (movie_id INT,title VARCHAR(100),release_year INT,rating FLOAT);
INSERT INTO movies (title, release_year, rating) VALUES ('Black Panther 2', 2022, 4.6);
How many hotels have adopted AI technology in 'APAC' region?
CREATE TABLE hotel_tech_adoption (hotel_id INT,hotel_name TEXT,region TEXT,ai_adoption BOOLEAN); INSERT INTO hotel_tech_adoption (hotel_id,hotel_name,region,ai_adoption) VALUES (1,'Hotel A','APAC',true),(2,'Hotel B','APAC',false),(3,'Hotel C','APAC',true),(4,'Hotel D','APAC',true);
SELECT COUNT(*) FROM hotel_tech_adoption WHERE region = 'APAC' AND ai_adoption = true;
What is the average number of hours donated by volunteers in '2020'?
CREATE TABLE Volunteers (VolunteerID int,VolunteerName varchar(50),HoursDonated int,VolunteerYear int); INSERT INTO Volunteers (VolunteerID,VolunteerName,HoursDonated,VolunteerYear) VALUES (1,'Karen Green',20,2020),(2,'Lisa White',25,2020),(3,'Mia Black',30,2020),(4,'Noah Red',15,2020);
SELECT AVG(HoursDonated) as AverageHours FROM Volunteers WHERE VolunteerYear = 2020;
What was the median food safety score for a restaurant in Los Angeles in 2021?
CREATE TABLE food_safety (restaurant VARCHAR(255),score INT,city VARCHAR(255),year INT); INSERT INTO food_safety (restaurant,score,city,year) VALUES ('Restaurant C',90,'Los Angeles',2021),('Restaurant D',85,'Los Angeles',2021);
SELECT AVG(score) FROM (SELECT score FROM food_safety WHERE city = 'Los Angeles' AND year = 2021 ORDER BY score LIMIT 2 OFFSET 1) AS temp;
What is the sum of all fines issued by the traffic department in the city of Chicago?
CREATE TABLE traffic_fines (fine_id INT,fine_amount INT,department TEXT,city TEXT); INSERT INTO traffic_fines (fine_id,fine_amount,department,city) VALUES (1,100,'Traffic','Chicago'),(2,200,'Traffic','Chicago'),(3,50,'Parks','Chicago'),(4,300,'Traffic','New York');
SELECT SUM(fine_amount) FROM traffic_fines WHERE department = 'Traffic' AND city = 'Chicago';
List all funding sources for 'Theater' programs in 2022.
CREATE TABLE if not exists program (id INT,name VARCHAR(50),category VARCHAR(50)); CREATE TABLE if not exists funding (id INT,program_id INT,year INT,amount DECIMAL(10,2),source VARCHAR(50)); INSERT INTO program (id,name,category) VALUES (1,'Theater 101','Theater'),(2,'Broadway Hits','Theater'),(3,'Shakespeare Plays','...
SELECT source FROM funding f JOIN program p ON f.program_id = p.id WHERE p.name LIKE '%Theater%' AND f.year = 2022;
What is the most popular tourist destination in South America?
CREATE TABLE south_american_tourists (id INT,country VARCHAR(20),destination VARCHAR(20),visitors INT); INSERT INTO south_american_tourists (id,country,destination,visitors) VALUES (1,'Brazil','Rio de Janeiro',1000000),(2,'Argentina','Buenos Aires',800000),(3,'Colombia','Bogota',600000);
SELECT destination, SUM(visitors) as total_visitors FROM south_american_tourists GROUP BY destination ORDER BY total_visitors DESC LIMIT 1;
What is the total energy efficiency savings in Germany and France, grouped by country?
CREATE TABLE energy_efficiency (id INT,name VARCHAR(255),savings FLOAT,country VARCHAR(50)); INSERT INTO energy_efficiency (id,name,savings,country) VALUES (1,'Efficiency A',10.5,'Germany'),(2,'Efficiency B',15.2,'France'),(3,'Efficiency C',8.0,'Germany');
SELECT ee.country, SUM(ee.savings) as total_savings FROM energy_efficiency ee GROUP BY ee.country;
What is the total cost of projects per year?
CREATE TABLE yearly_projects (id INT,name VARCHAR(50),year INT,cost FLOAT); INSERT INTO yearly_projects VALUES (1,'Dam Construction',2020,7000000),(2,'Road Widening',2019,4000000),(3,'Bridge Construction',2021,3500000);
SELECT year, SUM(cost) FROM yearly_projects GROUP BY year;
What is the average safety score for each AI algorithm, grouped by algorithm type?
CREATE TABLE ai_algorithms (algorithm_id INT,algorithm_name VARCHAR(50),algorithm_type VARCHAR(50),safety_score FLOAT); INSERT INTO ai_algorithms (algorithm_id,algorithm_name,algorithm_type,safety_score) VALUES (1,'Algo1','Reinforcement Learning',0.85),(2,'Algo2','Computer Vision',0.92),(3,'Algo3','Reinforcement Learni...
SELECT algorithm_type, AVG(safety_score) AS avg_safety_score FROM ai_algorithms GROUP BY algorithm_type;
What is the total number of police officers in San Francisco?
CREATE TABLE sf_police_officers (id INT,officer_name VARCHAR(20),station VARCHAR(20)); INSERT INTO sf_police_officers (id,officer_name,station) VALUES (1,'Officer Smith','Precinct 1'),(2,'Officer Johnson','Precinct 1');
SELECT COUNT(*) FROM sf_police_officers;
How many unique vehicle IDs were used for public transportation services in Paris during the month of June?
CREATE TABLE if not exists paris_public_transport_vehicles (id INT,vehicle_id INT,vehicle_type VARCHAR(20),timestamp TIMESTAMP);
SELECT COUNT(DISTINCT vehicle_id) FROM paris_public_transport_vehicles WHERE EXTRACT(MONTH FROM timestamp) = 6;
Update the positions of all goalkeepers to 'Goalkeeper'
CREATE TABLE players (player_id INT,name VARCHAR(100),position VARCHAR(50),team_id INT); INSERT INTO players (player_id,name,position,team_id) VALUES (1,'John Doe','Forward',1),(2,'Jane Smith','Goalie',2);
UPDATE players SET position = 'Goalkeeper' WHERE position = 'Goalie';
How many water treatment plants in the state of Illinois have water consumption per day greater than 1,500,000 liters?
CREATE TABLE WaterTreatmentPlants (plant_id INT,state VARCHAR(20),water_consumption_per_day FLOAT); INSERT INTO WaterTreatmentPlants (plant_id,state,water_consumption_per_day) VALUES (1,'Illinois',1800000),(2,'Illinois',1300000);
SELECT COUNT(*) FROM WaterTreatmentPlants WHERE state = 'Illinois' AND water_consumption_per_day > 1500000;
List the number of streams for each artist's top-performing song.
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(255)); INSERT INTO Artists (ArtistID,ArtistName) VALUES (1,'ArtistA'),(2,'ArtistB'),(3,'ArtistC'); CREATE TABLE Songs (SongID INT,ArtistID INT,SongName VARCHAR(255),Streams INT); INSERT INTO Songs (SongID,ArtistID,SongName,Streams) VALUES (1,1,'TopSongA',10000),(2,2...
SELECT A.ArtistName, MAX(S.Streams) AS TopStreams FROM Artists A JOIN Songs S ON A.ArtistID = S.ArtistID GROUP BY A.ArtistName;
What is the average booking amount for hotels that have implemented AI integration and are located in Japan?
CREATE TABLE HotelTechAdoption (hotel_id INT,ai_integration BOOLEAN,virtual_tour BOOLEAN); CREATE TABLE OnlineTravelAgency (ota_id INT,hotel_id INT,bookings INT); CREATE TABLE AIHospitalityTrends (hotel_id INT,ai_trend VARCHAR(255)); CREATE TABLE HotelGeolocation (hotel_id INT,country VARCHAR(255),city VARCHAR(255));
SELECT AVG(bookings) as avg_bookings FROM OnlineTravelAgency ota JOIN HotelTechAdoption hta ON ota.hotel_id = hta.hotel_id JOIN HotelGeolocation hgl ON ota.hotel_id = hgl.hotel_id WHERE hta.ai_integration = TRUE AND hgl.country = 'Japan';
What is the difference in the number of flights operated by 'AstroFlights' and 'GalacticAirlines'?
CREATE TABLE flights (id INT,airline VARCHAR(255)); INSERT INTO flights (id,airline) VALUES (1,'AstroFlights'),(2,'GalacticAirlines'),(3,'AstroFlights'),(4,'GalacticAirlines'),(5,'AstroFlights');
SELECT COUNT(*) FILTER (WHERE airline = 'AstroFlights') - COUNT(*) FILTER (WHERE airline = 'GalacticAirlines') as difference;
What is the average ad spend per user in the last month?
CREATE TABLE users (id INT,country VARCHAR(255)); INSERT INTO users (id,country) VALUES (1,'France'),(2,'Canada'),(3,'Germany'); CREATE TABLE ad_spend (id INT,user_id INT,amount DECIMAL(10,2),spend_date DATE); INSERT INTO ad_spend (id,user_id,amount,spend_date) VALUES (1,1,500.00,'2022-01-01'),(2,1,600.00,'2022-01-02')...
SELECT AVG(ad_spend.amount) FROM ad_spend INNER JOIN users ON ad_spend.user_id = users.id WHERE ad_spend.spend_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
What are the names and locations of all the vulnerabilities with a high severity level in the last 30 days?
CREATE TABLE vulnerabilities (id INT,name VARCHAR(255),severity VARCHAR(255),location VARCHAR(255),timestamp TIMESTAMP);
SELECT name, location FROM vulnerabilities WHERE severity = 'high' AND timestamp >= NOW() - INTERVAL 30 DAY;
What is the total billing amount for cases with a successful outcome in New York?
CREATE TABLE cases (case_id INT,case_outcome VARCHAR(20),billing_amount DECIMAL(10,2),case_location VARCHAR(20)); INSERT INTO cases (case_id,case_outcome,billing_amount,case_location) VALUES (1,'Successful',3000,'New York'),(2,'Unsuccessful',2000,'New York');
SELECT SUM(billing_amount) FROM cases WHERE case_outcome = 'Successful' AND case_location = 'New York';
What is the average dissolved oxygen level for each fish species in the past 6 months?
CREATE TABLE fish_species (id INT,name VARCHAR(255)); INSERT INTO fish_species (id,name) VALUES (1,'Salmon'),(2,'Tilapia'),(3,'Cod'); CREATE TABLE oxygen_readings (id INT,fish_id INT,date DATE,level FLOAT); INSERT INTO oxygen_readings (id,fish_id,date,level) VALUES (1,1,'2021-01-01',6.5),(2,1,'2021-01-02',6.8),(3,2,'20...
SELECT f.name, AVG(o.level) as avg_level FROM oxygen_readings o JOIN fish_species f ON o.fish_id = f.id WHERE o.date >= DATEADD(month, -6, GETDATE()) GROUP BY f.name;
What is the average project timeline for non-green buildings in Florida?
CREATE TABLE project_timeline_florida_data (region VARCHAR(255),building_type VARCHAR(255),timeline INT); INSERT INTO project_timeline_florida_data (region,building_type,timeline) VALUES ('Florida','Green',200),('Florida','Non-Green',250);
SELECT AVG(timeline) FROM project_timeline_florida_data WHERE region = 'Florida' AND building_type = 'Non-Green';
What is the total water consumption for the city of NYC in the last quarter?
CREATE TABLE MonthlyWaterUsage (Month DATE,City VARCHAR(20),Usage FLOAT); INSERT INTO MonthlyWaterUsage (Month,City,Usage) VALUES ('2022-01-01','NYC',2500),('2022-02-01','NYC',3000),('2022-03-01','NYC',3500);
SELECT SUM(Usage) FROM MonthlyWaterUsage WHERE City = 'NYC' AND Month >= DATEADD(QUARTER, -1, GETDATE());
What is the average preference score for eco-friendly products launched before 2010?
CREATE TABLE Products (id INT,ProductName VARCHAR(50),Category VARCHAR(50),Price DECIMAL(5,2),IsEcoFriendly BOOLEAN,LaunchDate DATE); CREATE TABLE CrueltyFreeCertification (id INT,ProductID INT,CertificationDate DATE);
SELECT AVG(CP.PreferenceScore) as AveragePreferenceScore FROM ConsumerPreference CP JOIN Products P ON CP.ProductID = P.id JOIN CrueltyFreeCertification CFC ON P.id = CFC.ProductID WHERE P.IsEcoFriendly = TRUE AND P.LaunchDate < '2010-01-01' AND CFC.CertificationDate IS NOT NULL;
What is the maximum interest rate for Islamic savings accounts?
CREATE TABLE islamic_savings (account_type VARCHAR(50),interest_rate FLOAT); INSERT INTO islamic_savings (account_type,interest_rate) VALUES ('Al-Wadiah',1.5),('Mudarabah',2.5),('Wakalah',2.0);
SELECT MAX(interest_rate) FROM islamic_savings WHERE account_type = 'Al-Wadiah';
Calculate the average funding for startups with at least one female founder in the healthcare industry
CREATE TABLE industry (company_id INT,industry TEXT); INSERT INTO industry (company_id,industry) VALUES (1,'Healthcare'); INSERT INTO industry (company_id,industry) VALUES (2,'Retail');
SELECT AVG(funding_amount) FROM investment_rounds ir INNER JOIN company c ON ir.company_id = c.id INNER JOIN diversity d ON c.id = d.company_id INNER JOIN industry i ON c.id = i.company_id WHERE i.industry = 'Healthcare' AND d.founder_gender = 'Female';
How many military technology assets were acquired by country in 2021?
CREATE TABLE military_tech_assets (asset_id INT PRIMARY KEY,asset_name VARCHAR(255),acquisition_year INT,country VARCHAR(255)); INSERT INTO military_tech_assets (asset_id,asset_name,acquisition_year,country) VALUES (1,'F-35 Fighter Jet',2019,'USA'),(2,'Type-26 Frigate',2020,'UK'),(3,'Dolphin-class Submarine',2021,'Isra...
SELECT country, COUNT(*) FROM military_tech_assets WHERE acquisition_year = 2021 GROUP BY country;
What is the number of people who have received the COVID-19 vaccine, grouped by age and gender?
CREATE TABLE vaccine_data (id INT,age INT,gender TEXT,vaccinated BOOLEAN); INSERT INTO vaccine_data (id,age,gender,vaccinated) VALUES (1,20,'Male',true); INSERT INTO vaccine_data (id,age,gender,vaccinated) VALUES (2,30,'Female',true); INSERT INTO vaccine_data (id,age,gender,vaccinated) VALUES (3,40,'Male',false);
SELECT age, gender, SUM(vaccinated) as number_vaccinated FROM vaccine_data GROUP BY age, gender;
How many tourists visited the United States from 2018 to 2021 who were traveling sustainably?
CREATE TABLE us_tourism (year INT,visitors INT,sustainability_rating INT); INSERT INTO us_tourism (year,visitors,sustainability_rating) VALUES (2018,50000000,3),(2019,55000000,4),(2020,40000000,5),(2021,45000000,5);
SELECT SUM(visitors) FROM us_tourism WHERE sustainability_rating >= 4 AND year BETWEEN 2018 AND 2021;
What is the total fare collected from 'tram' routes in April 2022?
CREATE TABLE public.collected_fare (fare_id SERIAL PRIMARY KEY,fare DECIMAL(5,2),fare_date DATE,route_type_id INTEGER,FOREIGN KEY (route_type_id) REFERENCES public.route_type(route_type_id)); INSERT INTO public.collected_fare (fare,fare_date,route_type_id) VALUES (2.00,'2022-04-01',3),(1.00,'2022-04-05',3),(2.00,'2022-...
SELECT SUM(fare) FROM public.collected_fare INNER JOIN public.route_type ON public.collected_fare.route_type_id = public.route_type.route_type_id WHERE route_type = 'tram' AND fare_date >= '2022-04-01' AND fare_date <= '2022-04-30'
Update the exit value for startup with ID 3 in the exits table to 12000000.
CREATE TABLE exits(startup_id INT,exit_type TEXT,exit_date DATE,exit_value INT); INSERT INTO exits (startup_id,exit_type,exit_date,exit_value) VALUES (1,'Acquisition','2021-10-01',20000000),(2,'IPO','2021-06-01',50000000),(3,'Acquisition','2021-02-01',1000000);
UPDATE exits SET exit_value = 12000000 WHERE startup_id = 3;
How many policy violations have occurred in each month of the past year from the 'policy_violations' table?
CREATE TABLE policy_violations (id INT,policy VARCHAR(50),violations INT,year INT,month INT);
SELECT month, SUM(violations) FROM policy_violations WHERE year = YEAR(CURRENT_DATE) - 1 GROUP BY month;
What's the total revenue of cruelty-free skincare products from Canada?
CREATE TABLE sales (id INT,product_id INT,quantity INT,sale_price DECIMAL); CREATE TABLE products (id INT,name TEXT,is_cruelty_free BOOLEAN,product_type TEXT,sale_price DECIMAL,country TEXT);
SELECT SUM(sales.quantity * sales.sale_price) FROM sales JOIN products ON sales.product_id = products.id WHERE products.is_cruelty_free = true AND products.product_type = 'skincare' AND products.country = 'Canada';
How many autonomous test vehicles were produced between 2018 and 2020?
CREATE TABLE autonomous_test_vehicles (vehicle_id INT,make VARCHAR(50),model VARCHAR(50),production_year INT,autonomous BOOLEAN);
SELECT COUNT(*) FROM autonomous_test_vehicles WHERE production_year BETWEEN 2018 AND 2020 AND autonomous = TRUE;
Which organizations provided medical assistance in Syria and Yemen between 2017 and 2020?
CREATE TABLE syria_assistance (org_id INT,org_name VARCHAR(50),year INT,medical_assistance BOOLEAN); INSERT INTO syria_assistance (org_id,org_name,year,medical_assistance) VALUES (1,'WHO',2017,TRUE),(2,'UNICEF',2018,TRUE),(3,'MSF',2019,TRUE),(4,'IFRC',2020,TRUE); CREATE TABLE yemen_assistance (org_id INT,org_name VARCH...
SELECT o.org_name FROM syria_assistance s INNER JOIN yemen_assistance y ON s.org_name = y.org_name WHERE s.medical_assistance = TRUE AND y.medical_assistance = TRUE AND s.year BETWEEN 2017 AND 2020;
What is the maximum delivery time for shipments to 'Africa'?
CREATE TABLE shipments (id INT,destination VARCHAR(20),delivery_time INT); INSERT INTO shipments (id,destination,delivery_time) VALUES (1,'Africa',8),(2,'Africa',10),(3,'Africa',9);
SELECT MAX(delivery_time) FROM shipments WHERE destination = 'Africa';
What is the total budget for rural infrastructure projects in Nigeria in 2020?
CREATE TABLE RuralInfrastructure (id INT,country VARCHAR(50),project VARCHAR(50),budget FLOAT,year INT); INSERT INTO RuralInfrastructure (id,country,project,budget,year) VALUES (1,'Nigeria','Road Construction',800000,2020),(2,'Nigeria','Bridge Building',500000,2019),(3,'Kenya','Electricity Grid Expansion',1000000,2020)...
SELECT SUM(budget) FROM RuralInfrastructure WHERE country = 'Nigeria' AND year = 2020;
What is the total number of electric vehicle charging stations in the state of California, grouped by station type?
CREATE TABLE ev_charging_stations (id INT,station_name VARCHAR(255),state VARCHAR(255),station_type VARCHAR(255),num_stalls INT);
SELECT station_type, COUNT(station_name) FROM ev_charging_stations WHERE state = 'California' GROUP BY station_type;
Find the total donation amount for each donor
CREATE TABLE DonationAmounts (DonationID INT,DonorID INT,DonationDate DATE,DonationAmount DECIMAL(10,2));
SELECT DonorID, SUM(DonationAmount) FROM DonationAmounts GROUP BY DonorID;
What is the total budget allocated for each program in 2021, grouped by program name?
CREATE TABLE Budget (BudgetID int,ProgramName varchar(50),BudgetYear int,BudgetAmount int); INSERT INTO Budget (BudgetID,ProgramName,BudgetYear,BudgetAmount) VALUES (1,'Education',2021,50000),(2,'Healthcare',2021,75000),(3,'Education',2022,60000);
SELECT ProgramName, SUM(BudgetAmount) as TotalBudget FROM Budget WHERE BudgetYear = 2021 GROUP BY ProgramName;
What was the age distribution of visitors who engaged with digital installations?
CREATE TABLE visitors_engagement (visitor_id INT,birth_date DATE,engaged BOOLEAN); INSERT INTO visitors_engagement (visitor_id,birth_date,engaged) VALUES (1,'1990-01-01',TRUE),(2,'2000-01-01',FALSE);
SELECT FLOOR(DATEDIFF(y, birth_date, GETDATE()) / 10) * 10 AS age_decade, COUNT(*) AS num_visitors FROM visitors_engagement WHERE engaged = TRUE GROUP BY FLOOR(DATEDIFF(y, birth_date, GETDATE()) / 10) * 10;
What is the average popularity score of trends associated with more than 3 garments?
CREATE TABLE trends (trend_id INT PRIMARY KEY,name VARCHAR(255),popularity_score INT); CREATE TABLE garments (garment_id INT PRIMARY KEY,name VARCHAR(255),trend_id INT,FOREIGN KEY (trend_id) REFERENCES trends(trend_id));
SELECT trends.name, AVG(trends.popularity_score) FROM trends JOIN garments ON trends.trend_id = garments.trend_id GROUP BY trends.name HAVING COUNT(garments.garment_id) > 3;
What is the average budget and number of hospitals in Washington with more than 50 beds?
CREATE TABLE hospitals (name TEXT,budget INTEGER,beds INTEGER,state TEXT); INSERT INTO hospitals (name,budget,beds,state) VALUES ('HospitalA',1000000,75,'Washington'),('HospitalB',1200000,60,'Washington'),('HospitalC',800000,50,'Washington'),('HospitalD',900000,80,'Washington'),('HospitalE',1100000,100,'Washington');
SELECT AVG(budget) as avg_budget, COUNT(*) as num_hospitals FROM hospitals WHERE state = 'Washington' AND beds > 50;
What is the total number of products sold, by category, for each store in the past week?
CREATE TABLE sales (id INT,date DATE,product VARCHAR(50),category VARCHAR(50),store VARCHAR(50),quantity INT); CREATE TABLE stores (id INT,name VARCHAR(50),location VARCHAR(50));
SELECT store, category, SUM(quantity) as total_sold FROM sales JOIN stores ON sales.store = stores.name WHERE date >= DATEADD(week, -1, GETDATE()) GROUP BY store, category;
How many artworks are there in the collection by female artists from Africa?
CREATE TABLE artworks (id INT,artist VARCHAR(100),collection VARCHAR(50),gender VARCHAR(10)); INSERT INTO artworks (id,artist,collection,gender) VALUES (1,'Nandi','African','Female'),(2,'John','European','Male'),(3,'Amina','African','Female');
SELECT COUNT(*) FROM artworks WHERE collection = 'African' AND gender = 'Female';
What is the average water footprint for crops grown in Morocco and Algeria?
CREATE TABLE Crops (id INT,country VARCHAR(255),crop VARCHAR(255),water_footprint INT); INSERT INTO Crops (id,country,crop,water_footprint) VALUES (1,'Morocco','Oranges',300),(2,'Morocco','Olives',150),(3,'Algeria','Dates',400),(4,'Algeria','Grapes',200);
SELECT AVG(water_footprint) FROM Crops WHERE country IN ('Morocco', 'Algeria') GROUP BY country;
Insert a new employee record into the "employees" table
CREATE TABLE employees (id INT,first_name VARCHAR(50),last_name VARCHAR(50),department VARCHAR(50),hire_date DATE);
INSERT INTO employees (id, first_name, last_name, department, hire_date) VALUES (101, 'Jamal', 'Johnson', 'IT', '2022-06-01');
What is the maximum lifespan of a communication satellite in geostationary orbit?
CREATE TABLE communication_satellites (id INT PRIMARY KEY,name VARCHAR(255),manufacturer VARCHAR(255),type VARCHAR(255),launch_date DATE,lifespan INT);
SELECT MAX(lifespan) FROM communication_satellites WHERE orbit_type = 'Geostationary';
What is the average daily revenue for hotels in the 'EMEA' region for the year 2022?
CREATE TABLE daily_revenue (id INT,hotel_id INT,region TEXT,calendar DATE,revenue FLOAT);
SELECT region, AVG(revenue) FROM daily_revenue WHERE region = 'EMEA' AND YEAR(calendar) = 2022 GROUP BY region;
What is the total yield of organic crops in France?
CREATE TABLE crop_yield (id INT,farm_id INT,crop_id INT,yield INT); INSERT INTO crop_yield (id,farm_id,crop_id,yield) VALUES (1,1,1,100),(2,2,2,50);
SELECT crops.name, SUM(crop_yield.yield) FROM crop_yield JOIN farms ON crop_yield.farm_id = farms.id JOIN crops ON crop_yield.crop_id = crops.id JOIN provinces ON farms.id = provinces.id JOIN farm_certifications ON farms.id = farm_certifications.farm_id WHERE provinces.country = 'France' AND farm_certifications.certifi...
How many accidents were reported for vessels with the word 'Carrier' in their name in April 2021?
CREATE TABLE vessels (id INT,name VARCHAR(255)); INSERT INTO vessels (id,name) VALUES (1,'Tanker Carrier'),(2,'Bulk Carrier'),(3,'Container Ship'),(4,'Passenger Carrier'); CREATE TABLE accidents (id INT,vessel_id INT,date DATE); INSERT INTO accidents (id,vessel_id,date) VALUES (1,1,'2021-04-12'),(2,1,'2021-04-01'),(3,4...
SELECT COUNT(a.vessel_id) as accidents_count FROM accidents a JOIN vessels v ON a.vessel_id = v.id WHERE v.name LIKE '%Carrier%' AND date_format(a.date, '%Y-%m') = '2021-04';
How many 'social_impact' investments have been made?
CREATE TABLE investments (id INT,sector VARCHAR(20))
SELECT COUNT(*) FROM investments WHERE sector = 'social_impact'
Which support programs have the highest and lowest enrollment?
CREATE TABLE Support_Programs (program_name TEXT,enrollment INT); CREATE VIEW Max_Enrollment AS SELECT program_name,enrollment FROM Support_Programs WHERE enrollment = (SELECT MAX(enrollment) FROM Support_Programs); CREATE VIEW Min_Enrollment AS SELECT program_name,enrollment FROM Support_Programs WHERE enrollment = (S...
SELECT * FROM Max_Enrollment UNION SELECT * FROM Min_Enrollment;
What was the average agricultural innovation metric per region for the last quarter?
CREATE TABLE agricultural_innovation_metrics (id INT PRIMARY KEY,region VARCHAR(50),metric_name VARCHAR(50),value DECIMAL(10,2),measurement_date DATE);
SELECT region, AVG(value) as avg_metric FROM agricultural_innovation_metrics WHERE measurement_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY region;
What is the total inventory cost for the NY region?
CREATE TABLE inventory (item_id INT,item_name TEXT,quantity INT,cost_per_unit DECIMAL(5,2),region TEXT); INSERT INTO inventory (item_id,item_name,quantity,cost_per_unit,region) VALUES (1,'Veggie Burger',50,2.50,'NY'),(2,'Chicken Caesar Salad',30,3.50,'NY'),(3,'BBQ Ribs',20,5.00,'NY');
SELECT SUM(quantity * cost_per_unit) as total_inventory_cost FROM inventory WHERE region = 'NY';
Which menu items have had their prices increased by more than 10% in the 'asian' cuisine category?
CREATE TABLE menu_items (id INT,name VARCHAR(50),cuisine VARCHAR(50),price DECIMAL(5,2)); INSERT INTO menu_items (id,name,cuisine,price) VALUES (1,'Pad Thai','asian',12.99); INSERT INTO menu_items (id,name,cuisine,price) VALUES (2,'Sushi Roll','asian',15.99);
SELECT name, cuisine, price, (price - LAG(price) OVER (PARTITION BY cuisine ORDER BY name))/LAG(price) OVER (PARTITION BY cuisine ORDER BY name) as price_increase_percentage FROM menu_items WHERE cuisine = 'asian' AND (price - LAG(price) OVER (PARTITION BY cuisine ORDER BY name))/LAG(price) OVER (PARTITION BY cuisine O...
Show the total number of ads served and the total revenue generated per country, for countries with more than 100,000 ad impressions.
CREATE TABLE countries (country_id INT,country_name VARCHAR(255)); INSERT INTO countries VALUES (1,'United States'),(2,'Canada'),(3,'Mexico'); CREATE TABLE ad_impressions (ad_id INT,country_id INT,impressions INT); CREATE TABLE ad_revenue (ad_id INT,revenue DECIMAL(10,2));
SELECT co.country_name, SUM(ai.impressions) as total_impressions, SUM(ar.revenue) as total_revenue FROM countries co INNER JOIN ad_impressions ai ON co.country_id = ai.country_id INNER JOIN ad_revenue ar ON ai.ad_id = ar.ad_id GROUP BY co.country_name HAVING total_impressions > 100000;
List all electric vehicles in the database.
CREATE TABLE Vehicles (Id INT,Make VARCHAR(255),Model VARCHAR(255),Year INT,Fuel_Type VARCHAR(255)); INSERT INTO Vehicles (Id,Make,Model,Year,Fuel_Type) VALUES (1,'Tesla','Model 3',2020,'Electric'); INSERT INTO Vehicles (Id,Make,Model,Year,Fuel_Type) VALUES (2,'Toyota','Prius',2020,'Hybrid'); INSERT INTO Vehicles (Id,M...
SELECT Make, Model FROM Vehicles WHERE Fuel_Type = 'Electric';
What is the name and efficiency of the solar panel with the lowest efficiency?
CREATE TABLE solar_panels (id INT,name VARCHAR(255),efficiency FLOAT); INSERT INTO solar_panels (id,name,efficiency) VALUES (1,'SolarPanel A',18.5),(2,'SolarPanel B',20.3),(3,'SolarPanel C',19.1);
SELECT name, MIN(efficiency) FROM solar_panels;
What is the total number of subway trips in Seoul on a Sunday?
CREATE TABLE subway_trips (trip_id INT,day_of_week VARCHAR(10),city VARCHAR(50)); INSERT INTO subway_trips (trip_id,day_of_week,city) VALUES (1,'Monday','Seoul'),(2,'Tuesday','Seoul'),(3,'Sunday','Seoul');
SELECT COUNT(*) FROM subway_trips WHERE day_of_week = 'Sunday' AND city = 'Seoul';
What is the total cargo weight transported by each shipping line in the last month, and what is the average weight per container for those shipments?
CREATE TABLE shipping_lines (shipping_line_id INT,shipping_line_name VARCHAR(100)); CREATE TABLE containers (container_id INT,container_weight INT,shipping_line_id INT,shipped_date DATE); INSERT INTO shipping_lines VALUES (1,'Maersk Line'); INSERT INTO shipping_lines VALUES (2,'MSC Mediterranean Shipping Company'); INS...
SELECT shipping_lines.shipping_line_name, SUM(containers.container_weight) as total_weight, AVG(containers.container_weight) as avg_weight_per_container FROM shipping_lines INNER JOIN containers ON shipping_lines.shipping_line_id = containers.shipping_line_id WHERE containers.shipped_date > DATE_SUB(CURRENT_DATE, INTER...
List all companies that have had an exit strategy through an IPO
CREATE TABLE company (id INT,name TEXT,exit_strategy TEXT); INSERT INTO company (id,name,exit_strategy) VALUES (1,'Delta Inc','IPO'); INSERT INTO company (id,name,exit_strategy) VALUES (2,'Epsilon Corp','Acquisition'); INSERT INTO company (id,name,exit_strategy) VALUES (3,'Zeta Inc',NULL); INSERT INTO company (id,name,...
SELECT id, name FROM company WHERE exit_strategy = 'IPO';
Delete records in landfill_capacity table where location is 'Texas'
CREATE TABLE landfill_capacity (id INT PRIMARY KEY,location VARCHAR(255),capacity INT,date DATE);
DELETE FROM landfill_capacity WHERE location = 'Texas';
What is the total revenue for each concert in descending order, for concerts with more than 5000 attendees?
CREATE SCHEMA if not exists music_schema;CREATE TABLE if not exists concerts (id INT,name VARCHAR,city VARCHAR,revenue FLOAT);INSERT INTO concerts (id,name,city,revenue) VALUES (1,'Music Festival','New York',200000.00),(2,'Rock Concert','Chicago',75000.00),(3,'Jazz Festival','Los Angeles',125000.00);
SELECT name, SUM(revenue) as total_revenue FROM music_schema.concerts WHERE attendees > 5000 GROUP BY name ORDER BY total_revenue DESC;
Create a table named 'drought_impact'
CREATE TABLE drought_impact (id INT PRIMARY KEY,region VARCHAR(50),drought_duration INT);
CREATE TABLE drought_impact (id INT PRIMARY KEY, region VARCHAR(50), drought_duration INT);
What is the total number of green buildings in the 'green_buildings' schema, by city, that have achieved a CO2 emission reduction (in metric tons) greater than 1000?
CREATE TABLE green_buildings.green_buildings_data (city VARCHAR(20),co2_emission_reduction_tons INT);
SELECT city, COUNT(*) FROM green_buildings.green_buildings_data WHERE co2_emission_reduction_tons > 1000 GROUP BY city;
Find the number of military equipment sales in 2020 from the 'sales' table
CREATE TABLE sales (id INT,equipment_type VARCHAR(255),sale_date DATE,quantity INT,country VARCHAR(255)); INSERT INTO sales (id,equipment_type,sale_date,quantity,country) VALUES (1,'tank','2019-07-15',5,'US'); INSERT INTO sales (id,equipment_type,sale_date,quantity,country) VALUES (2,'fighter_jet','2020-11-27',12,'UK')...
SELECT SUM(quantity) FROM sales WHERE YEAR(sale_date) = 2020 AND equipment_type IN ('military_equipment');
List all smart contracts and their respective developers who have more than 5 years of experience.
CREATE TABLE SmartContracts (ContractId INT,ContractName VARCHAR(50),DeveloperId INT); CREATE TABLE Developers (DeveloperId INT,DeveloperName VARCHAR(50),ExperienceYears INT); INSERT INTO SmartContracts (ContractId,ContractName,DeveloperId) VALUES (1,'Contract1',1); INSERT INTO SmartContracts (ContractId,ContractName,D...
SELECT s.ContractName, d.DeveloperName FROM SmartContracts s INNER JOIN Developers d ON s.DeveloperId = d.DeveloperId WHERE d.ExperienceYears > 5;
What is the minimum amount of climate finance provided by a single country for a climate mitigation project?
CREATE TABLE climate_finance_projects (country VARCHAR(50),finance_amount NUMERIC(10,2),project_type VARCHAR(50)); INSERT INTO climate_finance_projects (country,finance_amount,project_type) VALUES ('USA',5000000,'climate mitigation'),('China',4000000,'climate mitigation'),('India',3000000,'climate mitigation'),('Brazil...
SELECT country, MIN(finance_amount) FROM climate_finance_projects WHERE project_type = 'climate mitigation' GROUP BY country;
What is the total number of 'health insurance' policies and the percentage of those policies that have a claim amount greater than 2000?
CREATE TABLE policyholders (id INT,policy_type VARCHAR(20),policy_id INT); INSERT INTO policyholders (id,policy_type,policy_id) VALUES (1,'health insurance',1),(2,'life insurance',2),(3,'health insurance',3); CREATE TABLE claims (id INT,policy_id INT,claim_amount INT); INSERT INTO claims (id,policy_id,claim_amount) VAL...
SELECT COUNT(DISTINCT policyholders.id) FILTER (WHERE policy_type = 'health insurance') AS health_insurance_policies, COUNT(DISTINCT claims.policy_id) FILTER (WHERE claim_amount > 2000) * 100.0 / COUNT(DISTINCT policyholders.id) FILTER (WHERE policy_type = 'health insurance') AS high_claim_percentage FROM policyholders...
What is the average age of members who joined in 2020 and own a smartwatch?
CREATE TABLE Members (MemberID INT,JoinDate DATE,Age INT,HasSmartwatch BOOLEAN);
SELECT AVG(Age) FROM Members WHERE JoinDate BETWEEN '2020-01-01' AND '2020-12-31' AND HasSmartwatch = TRUE;
What is the name and district location of the library with the most books, and the school with the highest student count in that district?
CREATE TABLE Library (library_id INT,library_name VARCHAR(50),district_location INT,book_count INT,opened_date DATE); INSERT INTO Library (library_id,library_name,district_location,book_count,opened_date) VALUES (3,'Downtown Library',2,700000,'1895-09-21'); CREATE TABLE School (school_id INT,school_name VARCHAR(50),dis...
SELECT l.library_name, s.school_name FROM Library l JOIN School s ON l.district_location = s.district_served WHERE l.book_count = (SELECT MAX(l2.book_count) FROM Library l2) AND s.student_count = (SELECT MAX(s2.student_count) FROM School s2 WHERE s2.district_served = s.district_served);
Identify the top 3 donors who contributed the most to the 'Arts & Culture' project category in 2021.
CREATE TABLE donors (donor_id INT,donor_name VARCHAR(255),donation_amount DECIMAL,donation_date DATE,project_category VARCHAR(255)); INSERT INTO donors (donor_id,donor_name,donation_amount,donation_date,project_category) VALUES (1,'John Smith',500,'2021-06-15','Arts & Culture'),(2,'Jane Doe',750,'2021-03-01','Arts & Cu...
SELECT donor_name, SUM(donation_amount) as total_donation FROM donors WHERE donation_date BETWEEN '2021-01-01' AND '2021-12-31' AND project_category = 'Arts & Culture' GROUP BY donor_name ORDER BY total_donation DESC LIMIT 3;
Find the total revenue for each restaurant in the month of January 2021
CREATE TABLE restaurants (id INT,name VARCHAR(255)); INSERT INTO restaurants (id,name) VALUES (1,'Restaurant A'),(2,'Restaurant B'); CREATE TABLE revenue (restaurant_id INT,revenue DECIMAL(10,2),date DATE); INSERT INTO revenue (restaurant_id,revenue,date) VALUES (1,5000,'2021-01-01'),(1,6000,'2021-01-02'),(2,4000,'2021...
SELECT r.name, SUM(r.revenue) as total_revenue FROM revenue r JOIN restaurants res ON r.restaurant_id = res.id WHERE EXTRACT(MONTH FROM r.date) = 1 AND EXTRACT(YEAR FROM r.date) = 2021 GROUP BY r.name;
What is the total number of sustainable tourism initiatives worldwide?
CREATE TABLE initiatives (id INT,name TEXT,location TEXT,type TEXT); INSERT INTO initiatives (id,name,location,type) VALUES (1,'Green Safari','Kenya','Sustainable'),(2,'Eco-Lodge','Morocco','Sustainable'),(3,'Sustainable Winery','Spain','Sustainable');
SELECT COUNT(*) FROM initiatives WHERE type = 'Sustainable';
What are the sales figures for organic cosmetic products in Japan?
CREATE TABLE products (product_id INT,product_name TEXT,sales FLOAT,country TEXT,certified TEXT); INSERT INTO products (product_id,product_name,sales,country,certified) VALUES (1,'Lipstick A',5000,'USA','organic'),(2,'Eye Shadow B',3500,'Canada','vegan'),(3,'Mascara C',4200,'Germany','organic'),(4,'Foundation D',6000,'...
SELECT p.sales FROM products p WHERE p.certified = 'organic' AND p.country = 'Japan';
What is the average number of hours served per volunteer in Japan, for volunteers who have served more than 5 hours?
CREATE TABLE volunteers (volunteer_id int,hours_served int,country varchar(50)); INSERT INTO volunteers (volunteer_id,hours_served,country) VALUES (1,10,'Japan'),(2,2,'Japan'),(3,15,'Japan');
SELECT AVG(hours_served) FROM volunteers WHERE country = 'Japan' GROUP BY volunteer_id HAVING COUNT(volunteer_id) > 5;
Which venture capital firms have invested in companies based in Africa?
CREATE TABLE investment (id INT,company_id INT,vc_firm TEXT,investment_year INT); CREATE TABLE company (id INT,name TEXT,location TEXT); INSERT INTO investment (id,company_id,vc_firm,investment_year) VALUES (1,1,'Global Capital',2018); INSERT INTO company (id,name,location) VALUES (1,'Acme Inc','Nigeria');
SELECT DISTINCT vc_firm FROM investment JOIN company ON investment.company_id = company.id WHERE company.location = 'Nigeria';
What is the maximum reported yield (in tons) of a single crop in urban agriculture?
CREATE TABLE urban_agriculture (crop_id INT,crop_name TEXT,yield FLOAT); INSERT INTO urban_agriculture (crop_id,crop_name,yield) VALUES (1,'Tomatoes',2.3),(2,'Lettuce',1.9),(3,'Cucumbers',3.1);
SELECT MAX(yield) FROM urban_agriculture;
Delete all records from the Inventory table that have a quantity of 0.
CREATE TABLE Inventory (ItemID int,ItemName varchar(50),Quantity int); INSERT INTO Inventory VALUES (1,'Item 1',5),(2,'Item 2',0),(3,'Item 3',10),(4,'Item 4',0);
DELETE FROM Inventory WHERE Quantity = 0;
What was the capacity of the landfill 'North Disposal Site' in the year 2018?
CREATE TABLE LandfillCapacity (ID INT PRIMARY KEY,Landfill VARCHAR(50),City VARCHAR(50),Year INT,Capacity INT); INSERT INTO LandfillCapacity (ID,Landfill,City,Year,Capacity) VALUES (1,'North Disposal Site','Denver',2018,1000000);
SELECT Capacity FROM LandfillCapacity WHERE Landfill = 'North Disposal Site' AND Year = 2018;
What is the average donation amount by gender, for donors who made a donation in the last month?
CREATE TABLE donors (id INT,name TEXT,gender TEXT,donation_amount FLOAT,donation_date DATE);
SELECT gender, AVG(donation_amount) as avg_donation FROM donors WHERE donation_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY gender;
List the names and types of all sustainable farms in the 'farming' database that are located in the 'Northeast' region, sorted by name in ascending order.
CREATE TABLE farm (id INT,name VARCHAR(255),type VARCHAR(255),sustainability VARCHAR(255),region VARCHAR(255)); INSERT INTO farm (id,name,type,sustainability,region) VALUES (1,'Smith Farm','organic','sustainable','Midwest'),(2,'Johnson Farm','conventional','non-sustainable','South'),(3,'Brown Farm','organic','sustainab...
SELECT name, type FROM farm WHERE sustainability = 'sustainable' AND region = 'Northeast' ORDER BY name ASC;
Identify the top 3 manufacturers with the most successful satellite launches since 2010.
CREATE TABLE Satellites (SatelliteID INT,Name VARCHAR(50),Manufacturer VARCHAR(50),LaunchDate DATE,Orbit VARCHAR(50),Status VARCHAR(50)); INSERT INTO Satellites (SatelliteID,Name,Manufacturer,LaunchDate,Orbit,Status) VALUES (7,'Galileo I','Thales Alenia Space','2011-10-21','GEO','Active'),(8,'Galileo II','Airbus Defenc...
SELECT Manufacturer, COUNT(*) AS SuccessfulLaunches FROM Satellites WHERE LaunchDate >= '2010-01-01' GROUP BY Manufacturer ORDER BY SuccessfulLaunches DESC FETCH FIRST 3 ROWS ONLY;
List all legal precedents for a specific judge ID.
CREATE TABLE judge_precedents (judge_id INT,precedent_id INT); CREATE TABLE precedents (precedent_id INT,description TEXT);
SELECT p.description FROM judge_precedents jp JOIN precedents p ON jp.precedent_id = p.precedent_id WHERE jp.judge_id = 1;
Add Mental Health Parity scores for each Health Worker
CREATE TABLE CulturalCompetency (ID INT PRIMARY KEY,HealthWorkerName VARCHAR(100),CulturalCompetencyScore INT); CREATE TABLE MentalHealthParity (ID INT PRIMARY KEY,HealthWorkerName VARCHAR(100),MentalHealthParityScore INT);
ALTER TABLE MentalHealthParity ADD HealthWorkerName VARCHAR(100); INSERT INTO MentalHealthParity (ID, HealthWorkerName, MentalHealthParityScore) VALUES (1, 'John Doe', 75), (2, 'Jane Smith', 80), (3, 'Alice Johnson', 85);
How many minutes did members with a platinum membership spend working out in the last week?
CREATE TABLE membership (member_id INT,membership_type VARCHAR(20)); INSERT INTO membership (member_id,membership_type) VALUES (1,'Platinum'),(2,'Gold'),(3,'Platinum'); CREATE TABLE workout_data (member_id INT,duration INT,timestamp TIMESTAMP); INSERT INTO workout_data (member_id,duration,timestamp) VALUES (1,30,'2022-...
SELECT SUM(duration)/60 as total_minutes FROM workout_data w JOIN membership m ON w.member_id = m.member_id WHERE membership_type = 'Platinum' AND timestamp BETWEEN '2022-01-01 00:00:00' AND '2022-01-08 23:59:59';
What is the total number of public schools and private schools in the state of New York?
CREATE TABLE public_schools (school_name VARCHAR(255),school_type VARCHAR(50),state VARCHAR(50)); INSERT INTO public_schools (school_name,school_type,state) VALUES ('School A','Public','NY'),('School B','Public','NY'),('School C','Private','NY');
SELECT SUM(CASE WHEN school_type = 'Public' THEN 1 ELSE 0 END) as total_public_schools, SUM(CASE WHEN school_type = 'Private' THEN 1 ELSE 0 END) as total_private_schools FROM public_schools;
What was the average daily revenue for each dispensary in Washington in Q2 2021?
CREATE TABLE Dispensaries (id INT,name TEXT,state TEXT); INSERT INTO Dispensaries (id,name,state) VALUES (1,'Dispensary C','Washington'); INSERT INTO Dispensaries (id,name,state) VALUES (2,'Dispensary D','Washington'); CREATE TABLE Sales (dispensary_id INT,sale_date DATE,revenue DECIMAL(10,2)); INSERT INTO Sales (dispe...
SELECT d.name, AVG(s.revenue) as avg_daily_revenue FROM Dispensaries d JOIN Sales s ON d.id = s.dispensary_id WHERE s.sale_date BETWEEN '2021-04-01' AND '2021-06-30' GROUP BY d.name;
Show the change in ocean pH levels for the Mariana Trench over time, with weekly intervals.
CREATE TABLE OCEAN_PH (LOCATION VARCHAR(20),MEASUREMENT_DATE DATE,PH FLOAT); INSERT INTO OCEAN_PH (LOCATION,MEASUREMENT_DATE,PH) VALUES ('Mariana Trench','2022-01-01',7.8),('Mariana Trench','2022-01-07',7.7),('Mariana Trench','2022-01-14',7.6),('Mariana Trench','2022-01-21',7.5),('Mariana Trench','2022-01-28',7.4);
SELECT LOCATION, MEASUREMENT_DATE, PH, LEAD(PH, 1) OVER (PARTITION BY LOCATION ORDER BY MEASUREMENT_DATE) AS NEXT_PH FROM OCEAN_PH WHERE LOCATION = 'Mariana Trench' ORDER BY MEASUREMENT_DATE;
Find the top 3 countries with the most tourists in Asia, excluding China and Japan.
CREATE TABLE asia_tourists (id INT,country VARCHAR(20),tourists INT); INSERT INTO asia_tourists (id,country,tourists) VALUES (1,'China',60000000),(2,'Japan',20000000),(3,'India',35000000),(4,'Indonesia',15000000),(5,'Thailand',25000000);
SELECT country, tourists FROM (SELECT country, tourists, ROW_NUMBER() OVER (ORDER BY tourists DESC) AS rank FROM asia_tourists WHERE country NOT IN ('China', 'Japan') ) AS top_asia_countries WHERE rank <= 3;
How many unique donors are there for each category, sorted alphabetically?
CREATE TABLE donations (id INT,donor_id INT,category VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,category,amount) VALUES (1,1,'healthcare',1000),(2,1,'education',2000),(3,2,'healthcare',500),(4,2,'healthcare',1500),(5,3,'education',3000);
SELECT category, COUNT(DISTINCT donor_id) AS unique_donors FROM donations GROUP BY category ORDER BY category ASC;
What is the ratio of Lanthanum to Cerium production in 2019?
CREATE TABLE Lanthanum_Production (year INT,production FLOAT); INSERT INTO Lanthanum_Production (year,production) VALUES (2015,1500),(2016,1600),(2017,1700),(2018,1800),(2019,1900),(2020,2000); CREATE TABLE Cerium_Production (year INT,production FLOAT); INSERT INTO Cerium_Production (year,production) VALUES (2015,3000)...
SELECT production[year=2019]/(SELECT production FROM Cerium_Production WHERE year = 2019) FROM Lanthanum_Production WHERE year = 2019;