instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total amount donated by each donor in 2023, ranked in ascending order?
CREATE TABLE Donors (DonorID INT,DonorName VARCHAR(50),DonationDate DATE,Amount DECIMAL(10,2)); INSERT INTO Donors (DonorID,DonorName,DonationDate,Amount) VALUES (1,'Jane Smith','2023-01-01',50.00),(2,'John Doe','2023-02-01',100.00),(3,'Alice Johnson','2023-01-15',75.00);
SELECT DonorName, SUM(Amount) AS TotalDonated FROM Donors WHERE YEAR(DonationDate) = 2023 GROUP BY DonorName ORDER BY TotalDonated ASC;
How many candidates from underrepresented communities have been interviewed for each job category in the past 6 months?
CREATE TABLE Interviews (InterviewID int,InterviewDate date,CandidateName varchar(50),CandidateGender varchar(10),CandidateCommunity varchar(50),JobCategory varchar(50)); INSERT INTO Interviews (InterviewID,InterviewDate,CandidateName,CandidateGender,CandidateCommunity,JobCategory) VALUES (1,'2023-02-01','David Kim','Male','LGBTQ+','Software Engineer'),(2,'2023-02-02','Sophia Lee','Female','Women in Tech','Data Analyst'),(3,'2023-02-03','Daniel Park','Male','Neurodiverse','Software Engineer'),(4,'2023-02-04','Olivia Choi','Female','First Generation Immigrant','Data Scientist'),(5,'2023-02-05','William Han','Male','Racial Minority','Software Engineer'),(6,'2023-02-06','Ava Kim','Female','LGBTQ+','Data Analyst'),(7,'2023-02-07','Mohamed Ahmed','Male','First Generation Immigrant','Data Scientist');
SELECT JobCategory, CandidateCommunity, COUNT(*) AS num_candidates FROM Interviews WHERE InterviewDate >= DATEADD(month, -6, GETDATE()) GROUP BY JobCategory, CandidateCommunity;
What is the maximum number of wells drilled, in a single month, for all operators in the Bakken Formation, in the year 2019?
CREATE TABLE DrillingWells (WellID INT,Location VARCHAR(20),DrillingMonth DATE,DrillingOperator VARCHAR(20),NumberOfWells INT); INSERT INTO DrillingWells (WellID,Location,DrillingMonth,DrillingOperator,NumberOfWells) VALUES (1,'Bakken Formation','2019-01-01','Operator A',50),(2,'Bakken Formation','2019-02-01','Operator B',60),(3,'Barnett Shale','2018-01-01','Operator A',40);
SELECT DrillingOperator, MAX(NumberOfWells) FROM DrillingWells WHERE Location = 'Bakken Formation' AND YEAR(DrillingMonth) = 2019 GROUP BY DrillingOperator;
How many times has each NHL team played against international opponents?
CREATE TABLE nhl_teams (team_id INT,team_name VARCHAR(100)); CREATE TABLE nhl_games (game_id INT,home_team_id INT,away_team_id INT,opponent_type VARCHAR(50));
SELECT ht.team_name, COUNT(*) as game_count FROM nhl_teams ht JOIN nhl_games g ON ht.team_id = g.home_team_id WHERE g.opponent_type = 'International' GROUP BY ht.team_name;
What is the total number of yellow cards given to a single team in the 'soccer_matches' table?
CREATE TABLE soccer_matches (id INT,home_team VARCHAR(50),away_team VARCHAR(50),location VARCHAR(50),date DATE,yellow_cards_home INT,yellow_cards_away INT); INSERT INTO soccer_matches (id,home_team,away_team,location,date,yellow_cards_home,yellow_cards_away) VALUES (1,'Manchester City','Liverpool','Manchester','2022-01-01',3,2); INSERT INTO soccer_matches (id,home_team,away_team,location,date,yellow_cards_home,yellow_cards_away) VALUES (2,'Real Madrid','Barcelona','Madrid','2022-02-10',1,0);
SELECT (SUM(yellow_cards_home) + SUM(yellow_cards_away)) FROM soccer_matches;
What is the win-loss record for each team in the last 10 matches?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); CREATE TABLE matches (match_id INT,home_team_id INT,away_team_id INT,home_team_score INT,away_team_score INT,match_date DATE,home_team_won BOOLEAN);
SELECT t.team_name, SUM(CASE WHEN m.home_team_won THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN NOT m.home_team_won THEN 1 ELSE 0 END) as losses FROM matches m JOIN teams t ON (m.home_team_id = t.team_id OR m.away_team_id = t.team_id) WHERE m.match_date >= DATEADD(day, -10, GETDATE()) GROUP BY t.team_name;
How many schools and hospitals are there in Colombia and which ones need repairs?
CREATE TABLE schools (id INT,country VARCHAR(20),name VARCHAR(50),needs_repair BOOLEAN); CREATE TABLE hospitals (id INT,country VARCHAR(20),name VARCHAR(50),needs_repair BOOLEAN);
SELECT 'Schools' as facility_type, COUNT(*) as total, SUM(needs_repair) as repairs_needed FROM schools WHERE country = 'Colombia' UNION ALL SELECT 'Hospitals' as facility_type, COUNT(*) as total, SUM(needs_repair) as repairs_needed FROM hospitals WHERE country = 'Colombia';
How many unique donors have contributed to the 'community_development' table?
CREATE TABLE community_development (donation_id INT,donor VARCHAR(50),amount DECIMAL(10,2),donation_date DATE); INSERT INTO community_development (donation_id,donor,amount,donation_date) VALUES (1,'Charlie Brown',75.00,'2021-01-01'),(2,'David Wilson',125.00,'2021-02-01'),(3,'Charlie Brown',50.00,'2021-03-01');
SELECT COUNT(DISTINCT donor) FROM community_development;
Which countries received the most humanitarian aid in 2020?
CREATE TABLE donations (id INT,donor_name VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE,country_code CHAR(2));
SELECT country_code, SUM(donation_amount) FROM donations WHERE YEAR(donation_date) = 2020 AND program_type = 'Humanitarian Aid' GROUP BY country_code ORDER BY SUM(donation_amount) DESC;
Delete the "social_impact_scores" table
CREATE TABLE social_impact_scores (company TEXT,score INTEGER,year INTEGER); INSERT INTO social_impact_scores (company,score,year) VALUES ('Microsoft',85,2021); INSERT INTO social_impact_scores (company,score,year) VALUES ('Google',82,2021); INSERT INTO social_impact_scores (company,score,year) VALUES ('Amazon',78,2021); CREATE TABLE technology_companies (name TEXT,region TEXT,industry TEXT);
DROP TABLE social_impact_scores;
List all the organizations involved in technology for social good in Asia.
CREATE TABLE organizations (id INT,name VARCHAR(50),region VARCHAR(50),involvement VARCHAR(50)); INSERT INTO organizations (id,name,region,involvement) VALUES (1,'Tech4Good','Asia','social good'),(2,'GreenTechAsia','Asia','green technology'),(3,'AIforAsia','Asia','social good');
SELECT name FROM organizations WHERE region = 'Asia' AND involvement = 'social good';
Find the total fare collected and number of trips per payment type
CREATE TABLE payment_stats (route_id INT,payment_type VARCHAR(10),trips_taken INT,fare_collected DECIMAL(5,2)); INSERT INTO payment_stats (route_id,payment_type,trips_taken,fare_collected) VALUES (1,'Cash',250,625.00),(1,'Card',250,750.00),(2,'Cash',300,825.00),(2,'Card',300,1125.00);
SELECT payment_type, SUM(trips_taken) as total_trips, SUM(fare_collected) as total_fare FROM payment_stats GROUP BY payment_type;
Identify the average price of fair trade clothing items in the 'EthicalFashion' database
CREATE TABLE clothing_items (item_id INT,item_name VARCHAR(255),price DECIMAL(10,2),is_fair_trade BOOLEAN);
SELECT AVG(price) FROM clothing_items WHERE is_fair_trade = TRUE;
What are the top 3 countries with the most users on the social media platform, based on user location data?
CREATE TABLE user_location (user_id INT,country VARCHAR(50)); INSERT INTO user_location (user_id,country) VALUES (1,'USA'),(2,'Canada'),(3,'Mexico'),(4,'Brazil'),(5,'Argentina');
SELECT country, COUNT(user_id) as user_count FROM user_location GROUP BY country ORDER BY user_count DESC LIMIT 3;
Which countries source the most silk and wool textiles?
CREATE TABLE TextileSourcing (country VARCHAR(20),material VARCHAR(20),quantity INT); INSERT INTO TextileSourcing VALUES ('China','Silk',5000),('Italy','Wool',3000),('Australia','Wool',4000);
SELECT country, SUM(quantity) FROM TextileSourcing WHERE material IN ('Silk', 'Wool') GROUP BY country ORDER BY SUM(quantity) DESC;
What is the total amount of socially responsible loans issued to women in 2021?
CREATE TABLE socially_responsible_lending (id INT PRIMARY KEY,loan_amount DECIMAL(10,2),borrower_gender TEXT,lending_date DATE);
SELECT SUM(loan_amount) FROM socially_responsible_lending WHERE borrower_gender = 'Female' AND lending_date BETWEEN '2021-01-01' AND '2021-12-31';
List all reverse logistics metrics for January 2023
CREATE TABLE ReverseLogistics (id INT,metric INT,date DATE); INSERT INTO ReverseLogistics (id,metric,date) VALUES (1,200,'2023-01-01'),(2,300,'2023-01-05');
SELECT metric FROM ReverseLogistics WHERE date BETWEEN '2023-01-01' AND '2023-01-31';
Update bioprocess engineering project information
CREATE TABLE bioprocess_engineering_projects (project_id INT,project_name VARCHAR(255),project_leader VARCHAR(255));
UPDATE bioprocess_engineering_projects SET project_leader = 'Dr. Jane Smith' WHERE project_id = 1;
What are the names of genetic researchers who have expertise in CRISPR or gene therapy and are based in the US or Canada?
CREATE SCHEMA if not exists genetics; CREATE TABLE if not exists genetics.researchers (id INT,name VARCHAR(100),country VARCHAR(50),expertise VARCHAR(50)); INSERT INTO genetics.researchers (id,name,country,expertise) VALUES (1,'John Doe','US','CRISPR'); INSERT INTO genetics.researchers (id,name,country,expertise) VALUES (2,'Jane Smith','CA','Gene Therapy'); INSERT INTO genetics.researchers (id,name,country,expertise) VALUES (3,'Alice Johnson','MX','Genomics');
SELECT name FROM genetics.researchers WHERE (expertise = 'CRISPR' OR expertise = 'Gene Therapy') AND (country = 'US' OR country = 'CA');
What is the maximum funding received by a biotech startup in the year 2020?
CREATE TABLE startups (id INT,name VARCHAR(100),industry VARCHAR(50),location VARCHAR(50),funding DECIMAL(10,2)); INSERT INTO startups (id,name,industry,location,funding) VALUES (1,'StartupA','Biotech','US',20000000.50),(2,'StartupB','Biotech','UK',30000000.00),(3,'StartupC','Pharma','US',15000000.00),(4,'StartupD','Biotech','DE',25000000.75);
SELECT MAX(funding) FROM startups WHERE industry = 'Biotech' AND YEAR(start_date) = 2020;
What is the total number of open data initiatives by state?
CREATE TABLE state_data (state VARCHAR(255),num_initiatives INT); INSERT INTO state_data VALUES ('Alabama',15),('Alaska',12),('Arizona',20);
SELECT state, SUM(num_initiatives) FROM state_data GROUP BY state;
How many mental health parity complaints were filed in the last 12 months by state?
CREATE TABLE mental_health_parity_complaints (complaint_id INT,complaint_date DATE,state VARCHAR(20)); INSERT INTO mental_health_parity_complaints (complaint_id,complaint_date,state) VALUES (1,'2021-01-01','California'),(2,'2021-03-15','New York'),(3,'2020-12-31','Texas');
SELECT state, COUNT(*) as num_complaints FROM mental_health_parity_complaints WHERE complaint_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) GROUP BY state;
What is the total number of mental health parity coverage in each state, in descending order?
CREATE TABLE MentalHealthParity (State VARCHAR(20),Coverage DECIMAL(5,2)); INSERT INTO MentalHealthParity (State,Coverage) VALUES ('California',0.75),('Texas',0.82),('New York',0.91),('Florida',0.68),('Illinois',0.77);
SELECT State, SUM(Coverage) as TotalCoverage FROM MentalHealthParity GROUP BY State ORDER BY TotalCoverage DESC;
List all unique hotel_ids from the 'virtual_tour_stats' table
CREATE TABLE virtual_tour_stats (hotel_id INT,view_date DATE,view_duration INT);
SELECT DISTINCT hotel_id FROM virtual_tour_stats;
Which artists have their works exhibited in the 'Contemporary Art Museum' located in 'New York'?
CREATE TABLE Artists (ArtistID int,Name varchar(50),Nationality varchar(50)); INSERT INTO Artists VALUES (1,'Pablo Picasso','Spanish'); INSERT INTO Artists VALUES (2,'Andy Warhol','American'); CREATE TABLE Exhibitions (ExhibitionID int,Title varchar(50),Museum varchar(50),City varchar(50)); INSERT INTO Exhibitions VALUES (1,'Cubism','Museum of Modern Art','New York'); INSERT INTO Exhibitions VALUES (2,'Pop Art','Contemporary Art Museum','New York'); CREATE TABLE Exhibits (ExhibitionID int,ArtistID int); INSERT INTO Exhibits VALUES (2,2);
SELECT Artists.Name FROM Artists JOIN Exhibits ON Artists.ArtistID = Exhibits.ArtistID JOIN Exhibitions ON Exhibits.ExhibitionID = Exhibitions.ExhibitionID WHERE Exhibitions.Museum = 'Contemporary Art Museum' AND Exhibitions.City = 'New York';
What is the total biomass of each species in the 'species_biomass' table, grouped by species name?
CREATE TABLE species_biomass (species_id INT,species_name TEXT,biomass FLOAT);
SELECT species_name, SUM(biomass) FROM species_biomass GROUP BY species_name;
Calculate the percentage of endangered languages in each continent, ordered by the percentage in descending order.
CREATE TABLE languages (language_id INT,language_name TEXT,continent TEXT,endangered BOOLEAN); INSERT INTO languages (language_id,language_name,continent,endangered) VALUES (1,'Quechua','South America',true),(2,'Maori','Oceania',false);
SELECT continent, ROUND(100.0 * SUM(CASE WHEN endangered THEN 1 ELSE 0 END) / COUNT(*), 2) as percentage FROM languages GROUP BY continent ORDER BY percentage DESC;
What events have taken place at heritage sites established after the site's establishment?
CREATE TABLE HeritageSites (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),year_established INT); INSERT INTO HeritageSites (id,name,location,year_established) VALUES (2,'Angkor Wat','Cambodia',1113);
SELECT hs.name, hs.year_established, e.event_name, e.year FROM HeritageSites hs INNER JOIN Events e ON hs.id = e.heritage_site_id WHERE hs.year_established < e.year;
List all public awareness campaigns in New York focused on anxiety disorders.
CREATE TABLE campaigns (id INT,name TEXT,state TEXT,condition TEXT); INSERT INTO campaigns (id,name,state,condition) VALUES (1,'BraveNY','New York','Anxiety'); INSERT INTO campaigns (id,name,state,condition) VALUES (2,'TexasTough','Texas','Depression');
SELECT name FROM campaigns WHERE state = 'New York' AND condition = 'Anxiety';
Find the maximum construction cost for wastewater treatment plants in 'Ontario'
CREATE TABLE wastewater_treatment_plants (id INT,name VARCHAR(50),location VARCHAR(50),construction_cost DECIMAL(10,2)); INSERT INTO wastewater_treatment_plants (id,name,location,construction_cost) VALUES (1,'Toronto Wastewater Treatment Plant','Ontario',80000000.00);
SELECT MAX(construction_cost) FROM wastewater_treatment_plants WHERE location = 'Ontario';
List all legal technology patents filed in the EU between 2015 and 2018.
CREATE TABLE patents (patent_id INT,filed_date DATE,country VARCHAR(20)); INSERT INTO patents (patent_id,filed_date,country) VALUES (1,'2015-01-01','Germany'),(2,'2018-12-31','France');
SELECT patent_id FROM patents WHERE country LIKE 'EU%' AND filed_date BETWEEN '2015-01-01' AND '2018-12-31';
What is the average depth of marine life zones, grouped by type?
CREATE TABLE marine_life (id INT,type TEXT,depth FLOAT); INSERT INTO marine_life (id,type,depth) VALUES (1,'Trench',6000.0),(2,'Abyssal',4000.0),(3,'Hadal',10000.0);
SELECT type, AVG(depth) avg_depth FROM marine_life GROUP BY type;
How many broadband subscribers are there in the state of New York, excluding customers with speeds less than 100 Mbps?
CREATE TABLE broadband_subscribers (subscriber_id INT,speed FLOAT,state VARCHAR(20)); INSERT INTO broadband_subscribers (subscriber_id,speed,state) VALUES (1,75,'New York'),(2,150,'California');
SELECT COUNT(*) FROM broadband_subscribers WHERE state = 'New York' AND speed >= 100;
What is the total revenue generated by concert ticket sales in the US?
CREATE TABLE concert_tickets (ticket_id int,venue_id int,ticket_price decimal,timestamp datetime,country varchar(255)); INSERT INTO concert_tickets (ticket_id,venue_id,ticket_price,timestamp,country) VALUES (1,789,50.00,'2022-06-01 12:00:00','United States');
SELECT SUM(ticket_price) as total_revenue FROM concert_tickets WHERE timestamp BETWEEN '2022-01-01' AND '2022-12-31' AND country = 'United States';
What is the average number of articles published per day?
CREATE TABLE news_articles (article_id INT PRIMARY KEY,title TEXT,topic TEXT,author TEXT,publication_date DATE);
SELECT AVG(1.0 * COUNT(*) / COUNT(DISTINCT publication_date)) FROM news_articles;
What is the total number of volunteers for each country, for countries with more than 500 total volunteer hours?
CREATE TABLE organizations (id INT,name TEXT,country TEXT,total_volunteer_hours INT); INSERT INTO organizations (id,name,country,total_volunteer_hours) VALUES (1,'Org A','USA',1200),(2,'Org B','Canada',800),(3,'Org C','Mexico',1500);
SELECT country, SUM(total_volunteer_hours) as total_hours FROM organizations GROUP BY country HAVING SUM(total_volunteer_hours) > 500;
Which causes received funding from donors in both the United States and Canada?
CREATE TABLE donor_location (donor_id INT,country VARCHAR(50),cause VARCHAR(50),donation DECIMAL(10,2)); INSERT INTO donor_location (donor_id,country,cause,donation) VALUES (1,'United States','Global Health',1000.00),(2,'Canada','Education',2000.00),(3,'United States','Environment',1500.00),(4,'Canada','Animal Welfare',2500.00);
SELECT cause FROM donor_location WHERE country = 'United States' INTERSECT SELECT cause FROM donor_location WHERE country = 'Canada';
What is the average temperature in Texas for the past month?
CREATE TABLE Weather (location VARCHAR(50),temperature INT,timestamp TIMESTAMP);
SELECT AVG(temperature) FROM Weather WHERE location = 'Texas' AND timestamp > NOW() - INTERVAL '1 month';
Calculate the average property price per square foot in Sydney for properties built since 2015.
CREATE TABLE Sydney_Properties (PropertyID INT,Neighborhood VARCHAR(255),Year INT,Units INT,Price INT,SquareFootage INT); INSERT INTO Sydney_Properties (PropertyID,Neighborhood,Year,Units,Price,SquareFootage) VALUES (1,'Bondi',2014,3,1200000,1000),(2,'Manly',2015,4,1500000,1200),(3,'Coogee',2016,5,1800000,1500),(4,'Paddington',2017,2,1000000,800);
SELECT AVG(Price / SquareFootage) FROM Sydney_Properties WHERE Year >= 2015;
Determine the average food safety inspection scores for restaurants located in 'City A' and 'City B'.
CREATE TABLE restaurants (id INT,name VARCHAR(255),city VARCHAR(255),score INT); INSERT INTO restaurants (id,name,city,score) VALUES (1,'Restaurant A','City A',90),(2,'Restaurant B','City B',85),(3,'Restaurant C','City A',95);
SELECT city, AVG(score) FROM restaurants GROUP BY city HAVING city IN ('City A', 'City B');
Determine the number of days since the last food safety inspection for each restaurant
CREATE TABLE Restaurants (RestaurantID int,RestaurantName varchar(255)); INSERT INTO Restaurants (RestaurantID,RestaurantName) VALUES (1,'Mama Mia'),(2,'Taqueria Los Compadres'),(3,'Wok Express'); CREATE TABLE Inspections (InspectionID int,RestaurantID int,Violation varchar(255),InspectionDate date); INSERT INTO Inspections (InspectionID,RestaurantID,Violation,InspectionDate) VALUES (1,2,'Cross-contamination','2022-01-01'),(2,3,'Improper food storage','2022-01-05');
SELECT R.RestaurantName, DATEDIFF(CURDATE(), MAX(I.InspectionDate)) as DaysSinceLastInspection FROM Restaurants R LEFT JOIN Inspections I ON R.RestaurantID = I.RestaurantID GROUP BY R.RestaurantID;
What is the name of the vendor with the highest revenue from organic products?
CREATE TABLE Vendors (VendorID INT,VendorName TEXT,Country TEXT);CREATE TABLE Products (ProductID INT,ProductName TEXT,Price DECIMAL,Organic BOOLEAN,VendorID INT); INSERT INTO Vendors VALUES (1,'VendorF','UK'),(2,'VendorG','UK'); INSERT INTO Products VALUES (1,'Carrot',0.6,true,1),(2,'Broccoli',1.2,true,1),(3,'Apple',1.5,true,2),(4,'Banana',0.8,true,2);
SELECT v.VendorName FROM Vendors v JOIN Products p ON v.VendorID = p.VendorID WHERE p.Organic = true GROUP BY v.VendorID, v.VendorName HAVING SUM(Price) = (SELECT MAX(TotalPrice) FROM (SELECT SUM(Price) AS TotalPrice FROM Products p JOIN Vendors v ON p.VendorID = v.VendorID WHERE p.Organic = true GROUP BY v.VendorID) t);
What is the maximum temperature ever recorded in space?
CREATE TABLE space_temperatures (id INT,temperature FLOAT); INSERT INTO space_temperatures (id,temperature) VALUES (1,1000);
SELECT MAX(temperature) FROM space_temperatures;
Find the number of fans who have attended games of teams with mascots that include the word 'wolf'?
CREATE TABLE teams (team_id INT,team_name VARCHAR(50),mascot VARCHAR(50));CREATE TABLE fans (fan_id INT,team_id INT,attended BOOLEAN);INSERT INTO teams (team_id,team_name,mascot) VALUES (1,'Timberwolves','Wolf'),(2,'Grizzlies','Bear'),(3,'Lynx','Cat');INSERT INTO fans (fan_id,team_id,attended) VALUES (1,1,1),(2,1,1),(3,2,0),(4,3,1);
SELECT COUNT(*) AS wolf_fans FROM teams t INNER JOIN fans f ON t.team_id = f.team_id WHERE t.mascot LIKE '%wolf%' AND f.attended = 1;
How many times has a specific IP address been associated with malicious activity in the past year?
CREATE TABLE malicious_activity (id INT,ip_address VARCHAR(255),date DATE); INSERT INTO malicious_activity (id,ip_address,date) VALUES (1,'192.168.1.1','2022-01-01'),(2,'10.0.0.1','2022-01-05'),(3,'192.168.1.1','2022-01-20');
SELECT COUNT(*) FROM malicious_activity WHERE ip_address = '192.168.1.1' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 365 DAY);
List all cities with their respective counts of autonomous vehicles
CREATE TABLE public.vehicles (id INT,type VARCHAR(20),city VARCHAR(20)); INSERT INTO public.vehicles (id,type,city) VALUES (1,'autonomous_bus','Toronto'),(2,'conventional_bus','Toronto'),(3,'autonomous_car','Montreal'),(4,'conventional_car','Montreal');
SELECT city, COUNT(*) FROM public.vehicles WHERE type LIKE 'autonomous%' GROUP BY city;
What is the total number of electric buses across all cities?
CREATE TABLE transportation (id INT,city VARCHAR(255),vehicle_type VARCHAR(255),quantity INT); INSERT INTO transportation (id,city,vehicle_type,quantity) VALUES (1,'NYC','Electric Bus',200);
SELECT SUM(quantity) FROM transportation WHERE vehicle_type = 'Electric Bus';
Calculate the total revenue for garments manufactured in the US and sold in California.
CREATE TABLE garment_manufacturing(id INT PRIMARY KEY,garment_id INT,country VARCHAR(50),material VARCHAR(50),manufacturing_date DATE,quantity INT); CREATE TABLE garment_sales(id INT PRIMARY KEY,garment_id INT,store_id INT,sale_date DATE,units INT,revenue DECIMAL(10,2));
SELECT SUM(gs.revenue) FROM garment_manufacturing gm JOIN garment_sales gs ON gm.garment_id = gs.garment_id WHERE gm.country = 'United States' AND gs.store_id IN (SELECT id FROM stores WHERE region = 'California');
Count the number of 'T-Shirt' items manufactured in Turkey in 2022.
CREATE TABLE Manufacturing (id INT,garment_type VARCHAR(20),country VARCHAR(20),year INT,quantity INT); INSERT INTO Manufacturing (id,garment_type,country,year,quantity) VALUES (1,'Dress','Turkey',2022,300),(2,'Shirt','Turkey',2022,450),(3,'Pant','Turkey',2022,600),(4,'T-Shirt','Turkey',2022,250);
SELECT COUNT(*) as num_tshirts FROM Manufacturing WHERE garment_type = 'T-Shirt' AND country = 'Turkey' AND year = 2022;
What was the total sales amount for each product category in 2021?
CREATE TABLE sales_2021 AS SELECT * FROM sales WHERE sale_date BETWEEN '2021-01-01' AND '2021-12-31'; ALTER TABLE sales_2021 ADD COLUMN product_category VARCHAR(50); UPDATE sales_2021 SET product_category = CASE WHEN product_id = 1 THEN 'Tops' WHEN product_id = 2 THEN 'Bottoms' WHEN product_id = 3 THEN 'Outerwear' WHEN product_id = 4 THEN 'Accessories' END;
SELECT product_category, SUM(sale_amount) FROM sales_2021 GROUP BY product_category;
Find the total premium for auto policies in New Jersey.
CREATE TABLE policyholders (id INT,name TEXT,state TEXT,policy_type TEXT,premium FLOAT); INSERT INTO policyholders (id,name,state,policy_type,premium) VALUES (1,'Rebecca Martinez','New Jersey','Auto',1500.00),(2,'Mohammed Ahmed','New York','Home',2000.00);
SELECT SUM(policyholders.premium) FROM policyholders WHERE policyholders.state = 'New Jersey' AND policyholders.policy_type = 'Auto';
What are the unique labor rights advocacy groups in Latin America?
CREATE TABLE labor_advocacy (group_name VARCHAR(50),region VARCHAR(50)); INSERT INTO labor_advocacy (group_name,region) VALUES ('CUT','Brazil'); INSERT INTO labor_advocacy (group_name,region) VALUES ('CNT','Argentina'); INSERT INTO labor_advocacy (group_name,region) VALUES ('CGT','Mexico'); INSERT INTO labor_advocacy (group_name,region) VALUES ('UNORCA','Colombia');
SELECT DISTINCT group_name FROM labor_advocacy WHERE region IN ('Brazil', 'Argentina', 'Mexico', 'Colombia');
What is the average union membership size for workplaces in the 'labor_rights' table?
CREATE TABLE labor_rights (workplace_id INT,union_membership_size INT);
SELECT AVG(union_membership_size) FROM labor_rights;
What are the vehicle models that have a battery range of 350 miles or more, and were sold between January and June 2023?
CREATE TABLE VehicleSales (SaleID INT,VehicleModel VARCHAR(50),SaleDate DATE); INSERT INTO VehicleSales (SaleID,VehicleModel,SaleDate) VALUES (1,'Model S','2023-02-01'); INSERT INTO VehicleSales (SaleID,VehicleModel,SaleDate) VALUES (2,'Model X','2023-03-15'); CREATE TABLE VehicleSpecifications (SpecID INT,VehicleModel VARCHAR(50),SpecName VARCHAR(50),SpecValue VARCHAR(50)); INSERT INTO VehicleSpecifications (SpecID,VehicleModel,SpecName,SpecValue) VALUES (1,'Model S','Battery Range','400'); INSERT INTO VehicleSpecifications (SpecID,VehicleModel,SpecName,SpecValue) VALUES (2,'Model X','Battery Range','360');
SELECT VehicleModel FROM VehicleSales INNER JOIN VehicleSpecifications ON VehicleSales.VehicleModel = VehicleSpecifications.VehicleModel WHERE VehicleSpecifications.SpecName = 'Battery Range' AND VehicleSpecifications.SpecValue >= 350 AND VehicleSales.SaleDate BETWEEN '2023-01-01' AND '2023-06-30'
What is the average landfill tipping fee in the state of New York?
CREATE TABLE landfill (state VARCHAR(2),tipping_fee DECIMAL(5,2)); INSERT INTO landfill (state,tipping_fee) VALUES ('NY',65.30),('NJ',71.50),('CA',51.75);
SELECT AVG(tipping_fee) FROM landfill WHERE state = 'NY';
Insert new water conservation initiatives in the 'Great Lakes' region
CREATE TABLE conservation_initiatives (id INT PRIMARY KEY,region VARCHAR(255),initiative_name VARCHAR(255),start_date DATE,end_date DATE);
INSERT INTO conservation_initiatives (id, region, initiative_name, start_date, end_date) VALUES (1, 'Great Lakes', 'Rainwater harvesting program', CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 YEAR));
How many users joined in the last 30 days?
CREATE TABLE user_registrations (id INT,registration_date DATE); INSERT INTO user_registrations (id,registration_date) VALUES (1,'2022-06-15'),(2,'2022-07-10'),(3,'2022-07-28'),(4,'2022-08-01');
SELECT COUNT(*) FROM user_registrations WHERE registration_date >= CURDATE() - INTERVAL 30 DAY;
What is the average safety rating of all creative AI applications?
CREATE TABLE creative_ai (app_name TEXT,safety_rating INTEGER); INSERT INTO creative_ai (app_name,safety_rating) VALUES ('AI Painter',85),('AI Music Composer',90),('AI Poet',80);
SELECT AVG(safety_rating) FROM creative_ai;
What's the total number of farmers in the 'young_farmer_program' table?
CREATE TABLE young_farmer_program (id INT PRIMARY KEY,first_name VARCHAR(50),last_name VARCHAR(50),age INT,gender VARCHAR(10),location VARCHAR(50));
SELECT COUNT(*) FROM young_farmer_program;
Determine the difference in launch dates for each pair of consecutive satellite launches, partitioned by country.
CREATE TABLE SatelliteLaunches (LaunchID INT,Country VARCHAR(50),LaunchDate DATE); INSERT INTO SatelliteLaunches (LaunchID,Country,LaunchDate) VALUES (1,'USA','2015-01-01'); INSERT INTO SatelliteLaunches (LaunchID,Country,LaunchDate) VALUES (2,'USA','2016-01-01'); INSERT INTO SatelliteLaunches (LaunchID,Country,LaunchDate) VALUES (3,'China','2014-01-01'); INSERT INTO SatelliteLaunches (LaunchID,Country,LaunchDate) VALUES (4,'China','2015-01-01'); INSERT INTO SatelliteLaunches (LaunchID,Country,LaunchDate) VALUES (5,'Russia','2013-01-01');
SELECT Country, LaunchDate, LEAD(LaunchDate) OVER (PARTITION BY Country ORDER BY LaunchDate) AS Next_LaunchDate, DATEDIFF(day, LaunchDate, LEAD(LaunchDate) OVER (PARTITION BY Country ORDER BY LaunchDate)) AS Days_Between_Launches FROM SatelliteLaunches;
List all aircraft produced by Orbital Manufacturing with a production cost greater than $12 million.
CREATE TABLE Aircraft (aircraft_id INT,manufacturer VARCHAR(255),production_cost FLOAT); INSERT INTO Aircraft (aircraft_id,manufacturer,production_cost) VALUES (1,'Orbital Manufacturing',15000000),(2,'Aerodyne Inc.',11000000),(3,'Orbital Manufacturing',13500000);
SELECT aircraft_id, manufacturer, production_cost FROM Aircraft WHERE manufacturer = 'Orbital Manufacturing' AND production_cost > 12000000;
What is the distribution of aircraft accidents by year for each airline type?
CREATE TABLE AircraftAccidentsByYear (id INT,airline VARCHAR(50),airline_type VARCHAR(50),accident_year INT); INSERT INTO AircraftAccidentsByYear (id,airline,airline_type,accident_year) VALUES (1,'Delta','737',2015),(2,'Delta','757',2017),(3,'United','747',2013),(4,'United','777',2018),(5,'Southwest','737',2016),(6,'Southwest','738',2019);
SELECT airline_type, accident_year, COUNT(*) as total_accidents FROM AircraftAccidentsByYear GROUP BY airline_type, accident_year ORDER BY airline_type, accident_year;
DELETE all records of donors who have not donated more than $5000 in total between 2018 and 2022.
CREATE TABLE Donors (donor_id INT,donor_name VARCHAR(50),total_donations DECIMAL(10,2)); INSERT INTO Donors (donor_id,donor_name,total_donations) VALUES (1,'John Smith',8000),(2,'Jane Doe',6000),(3,'Bob Brown',3000),(4,'Alice Johnson',5000),(5,'Charlie Davis',7000);
DELETE FROM Donors WHERE donor_id NOT IN (SELECT donor_id FROM (SELECT donor_id, SUM(donation_amount) AS total_donations FROM Donations WHERE donation_year BETWEEN 2018 AND 2022 GROUP BY donor_id) AS DonationTotals WHERE total_donations > 5000);
Find the number of attendees at an event in New York City.
CREATE TABLE Events (EventID INT,EventName TEXT,City TEXT,Attendees INT); INSERT INTO Events (EventID,EventName,City,Attendees) VALUES (1,'Art Exhibit','New York City',200),(2,'Theater Performance','Chicago',150),(3,'Music Concert','Los Angeles',300);
SELECT COUNT(Attendees) FROM Events WHERE City = 'New York City';
What is the total funding received by art programs for underrepresented communities in the last 5 years?
CREATE TABLE FundingSources (ID INT,FundingSource VARCHAR(255),Amount DECIMAL(10,2),FundingDate DATE); CREATE TABLE ArtPrograms (ID INT,ProgramName VARCHAR(255),ProgramType VARCHAR(255),StartDate DATE,EndDate DATE);
SELECT SUM(f.Amount) as TotalFunding FROM FundingSources f JOIN ArtPrograms a ON f.FundingDate BETWEEN a.StartDate AND a.EndDate WHERE a.ProgramType = 'Underrepresented Communities' AND f.FundingDate >= DATEADD(year, -5, GETDATE());
What was the average age of attendees at musical events in New York?
CREATE TABLE Events (event_id INT,event_type VARCHAR(50),location VARCHAR(50)); INSERT INTO Events (event_id,event_type,location) VALUES (1,'Musical','New York'),(2,'Theater','Los Angeles'); CREATE TABLE Attendance (attendee_id INT,event_id INT,age INT); INSERT INTO Attendance (attendee_id,event_id,age) VALUES (1,1,35),(2,1,45),(3,1,28),(4,2,50);
SELECT AVG(age) FROM Attendance A WHERE EXISTS (SELECT 1 FROM Events E WHERE E.event_id = A.event_id AND E.event_type = 'Musical' AND E.location = 'New York')
insert new tv show 'Money Heist' into the tv_shows table
CREATE TABLE tv_shows(id INT PRIMARY KEY,name VARCHAR(255),rating INT);
INSERT INTO tv_shows(id, name, rating) VALUES(1, 'Money Heist', 8);
Delete records of completed projects from the Projects table.
CREATE TABLE Projects (ProjectID INT,ProjectName VARCHAR(50),StartDate DATE,EndDate DATE,EmployeeID INT,FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID));
DELETE FROM Projects WHERE EndDate < CURDATE();
Update the name of the contractor, 'Smith Inc.', to 'GreenSmith Inc.' in the 'contractors' table where the contractor_id is 101
CREATE TABLE contractors (contractor_id INT,name VARCHAR(50)); INSERT INTO contractors (contractor_id,name) VALUES (101,'Smith Inc.');
UPDATE contractors SET name = 'GreenSmith Inc.' WHERE contractor_id = 101;
Update the permit status to 'approved' for permit ID 1234
CREATE TABLE building_permits (permit_id INT,status VARCHAR(20));
UPDATE building_permits SET status = 'approved' WHERE permit_id = 1234;
Which dispensaries sold the most pre-rolls in Q2 2021, sorted by total sales?
CREATE TABLE Dispensaries (DispensaryID INT,Name VARCHAR(100),Location VARCHAR(100)); CREATE TABLE Inventory (ProductID INT,ProductName VARCHAR(100),DispensaryID INT,QuantitySold INT,SaleDate DATE);
SELECT I.ProductName, SUM(I.QuantitySold) as TotalSales FROM Inventory I JOIN Dispensaries D ON I.DispensaryID = D.DispensaryID WHERE I.ProductName = 'Pre-rolls' AND I.SaleDate BETWEEN '2021-04-01' AND '2021-06-30' GROUP BY I.ProductName ORDER BY TotalSales DESC;
Find the minimum billing amount for cases in the 'Northern' region.
CREATE TABLE cases (id INT,region VARCHAR(10),billing_amount INT); INSERT INTO cases (id,region,billing_amount) VALUES (1,'Eastern',5000),(2,'Western',7000),(3,'Eastern',6000),(4,'Northern',8000),(5,'Northern',3000);
SELECT MIN(billing_amount) FROM cases WHERE region = 'Northern';
List the case number, outcome, and corresponding attorney ID for cases in the 'criminal' schema, ordered by case number.
CREATE SCHEMA criminal; CREATE TABLE case_outcomes (case_number INT,outcome VARCHAR(255)); CREATE TABLE cases (case_id INT,case_number INT,attorney_id INT);
SELECT co.case_number, co.outcome, c.attorney_id FROM criminal.case_outcomes co INNER JOIN cases c ON co.case_number = c.case_number ORDER BY co.case_number;
What is the average settlement amount for cases with billable hours greater than 30?
CREATE TABLE Billing (BillID INT,CaseID INT,Hours INT,BillAmount INT); INSERT INTO Billing (BillID,CaseID,Hours,BillAmount) VALUES (2,2,35,7000);CREATE TABLE Settlements (SettlementID INT,CaseID INT,SettlementAmount INT); INSERT INTO Settlements (SettlementID,CaseID,SettlementAmount) VALUES (2,2,12000);
SELECT AVG(s.SettlementAmount) FROM Settlements s JOIN Billing b ON s.CaseID = b.CaseID WHERE b.Hours > 30
What is the minimum number of successful cases handled by attorneys who identify as Latinx?
CREATE TABLE attorneys (attorney_id INT,ethnicity VARCHAR(20),successful_cases INT); INSERT INTO attorneys (attorney_id,ethnicity,successful_cases) VALUES (1,'Caucasian',15),(2,'African',10),(3,'Latinx',14),(4,'Asian',12);
SELECT MIN(successful_cases) FROM attorneys WHERE ethnicity = 'Latinx';
Which chemical manufacturers produce a specific type of chemical and have not reported any safety incidents in the past year?
CREATE TABLE chemical_manufacturers (manufacturer_id INT,name VARCHAR(255)); INSERT INTO chemical_manufacturers (manufacturer_id,name) VALUES (1,'ManufacturerA'),(2,'ManufacturerB'),(3,'ManufacturerC'); CREATE TABLE produces (producer_id INT,manufacturer_id INT,chemical_type VARCHAR(255)); INSERT INTO produces (producer_id,manufacturer_id,chemical_type) VALUES (1,1,'ChemicalA'),(2,2,'ChemicalB'),(3,3,'ChemicalA'); CREATE TABLE safety_incidents (incident_id INT,manufacturer_id INT,reported_date DATE); INSERT INTO safety_incidents (incident_id,manufacturer_id,reported_date) VALUES (1,1,'2020-01-01'),(2,2,'2020-05-05'),(3,3,'2020-12-25');
SELECT p.name FROM produces p JOIN chemical_manufacturers cm ON p.manufacturer_id = cm.manufacturer_id WHERE p.chemical_type = 'ChemicalA' AND cm.manufacturer_id NOT IN (SELECT si.manufacturer_id FROM safety_incidents si WHERE si.reported_date BETWEEN DATEADD(year, -1, GETDATE()) AND GETDATE())
What is the number of climate change-related news articles published in Australia in 2019 and 2020?
CREATE TABLE NewsArticles (title VARCHAR(50),year INT,location VARCHAR(50)); INSERT INTO NewsArticles (title,year,location) VALUES ('Climate change in Australia',2019,'Australia'),('Climate change in Australia',2020,'Australia');
SELECT location, COUNT(*) as 'Number of News Articles' FROM NewsArticles WHERE year IN (2019, 2020) AND location = 'Australia' GROUP BY location;
What are the R&D expenses per quarter for a specific drug?
CREATE TABLE r_and_d_expenses (expense_id INT,drug_id INT,expense_date DATE,amount FLOAT); INSERT INTO r_and_d_expenses (expense_id,drug_id,expense_date,amount) VALUES (1,1001,'2019-01-01',50000.0),(2,1001,'2019-04-01',55000.0),(3,1001,'2019-07-01',60000.0),(4,1001,'2019-10-01',65000.0),(5,1002,'2019-01-01',45000.0);
SELECT drug_id, DATE_TRUNC('quarter', expense_date) as quarter, SUM(amount) as total_expenses FROM r_and_d_expenses WHERE drug_id = 1001 GROUP BY drug_id, quarter;
What are the top 5 countries with the highest sales for a specific drug?
CREATE TABLE sales_data (id INT,drug VARCHAR(255),country VARCHAR(255),sales DECIMAL(10,2)); INSERT INTO sales_data (id,drug,country,sales) VALUES (1,'DrugA','USA',1000000.00); INSERT INTO sales_data (id,drug,country,sales) VALUES (2,'DrugA','Canada',500000.00); INSERT INTO sales_data (id,drug,country,sales) VALUES (3,'DrugB','USA',800000.00);
SELECT drug, country, SUM(sales) FROM sales_data GROUP BY drug, country ORDER BY SUM(sales) DESC LIMIT 5;
What are the names and number of females in the vaccination_sites table who administer the Moderna vaccine?
CREATE TABLE vaccination_sites (site_id INT,site_name TEXT,vaccine TEXT,num_female_staff INT); INSERT INTO vaccination_sites (site_id,site_name,vaccine,num_female_staff) VALUES (1,'Site A','Moderna',15),(2,'Site B','Johnson',8),(3,'Site C','Pfizer',12);
SELECT site_name, num_female_staff FROM vaccination_sites WHERE vaccine = 'Moderna' AND num_female_staff > 0;
What is the percentage of the population fully vaccinated against COVID-19, by race and ethnicity?
CREATE TABLE covid_vaccinations (race_ethnicity VARCHAR(20),pct_fully_vaccinated FLOAT); INSERT INTO covid_vaccinations (race_ethnicity,pct_fully_vaccinated) VALUES ('White',70.5),('Black',62.3),('Hispanic',58.1),('Asian',75.6),('Native American',55.0),('Pacific Islander',65.4);
SELECT race_ethnicity, (SUM(pct_fully_vaccinated) / COUNT(race_ethnicity) * 100) as pct_fully_vaccinated FROM covid_vaccinations GROUP BY race_ethnicity;
Delete diversity metrics for 2019 from the database.
CREATE TABLE Diversity (Company VARCHAR(50),Year INT,DiverseEmployees INT); INSERT INTO Diversity (Company,Year,DiverseEmployees) VALUES ('Acme Inc.',2018,50),('Acme Inc.',2019,75),('Acme Inc.',2020,85),('Beta Corp.',2018,30),('Beta Corp.',2019,35),('Beta Corp.',2020,40);
DELETE FROM Diversity WHERE Year = 2019;
What is the percentage of crop yield by crop in 'crop_distribution' table?
CREATE TABLE crop_distribution (country VARCHAR(50),crop VARCHAR(50),yield INT); INSERT INTO crop_distribution (country,crop,yield) VALUES ('Canada','corn',1000),('Canada','wheat',2000),('USA','corn',3000),('USA','wheat',4000),('Mexico','corn',2500),('Mexico','wheat',1500);
SELECT crop, ROUND(100.0 * yield / SUM(yield) OVER (), 2) as yield_percentage FROM crop_distribution;
Which indigenous food systems have the highest production in Africa?
CREATE TABLE indigenous_systems (continent VARCHAR(255),system_name VARCHAR(255),production INT); INSERT INTO indigenous_systems (continent,system_name,production) VALUES ('Africa','SystemA',3000),('Africa','SystemB',3500),('Europe','SystemC',2000); CREATE VIEW african_indigenous_systems AS SELECT * FROM indigenous_systems WHERE continent = 'Africa';
SELECT system_name, MAX(production) FROM african_indigenous_systems GROUP BY system_name
How many support programs were offered in each region?
CREATE TABLE support_program (id INT,name VARCHAR(255),region VARCHAR(255)); INSERT INTO support_program (id,name,region) VALUES (1,'Tutoring','Northeast'),(2,'Mentoring','Northeast'),(3,'Skills Training','Southeast'),(4,'Counseling','Southeast'),(5,'Job Placement','Midwest');
SELECT region, COUNT(id) as total_programs FROM support_program GROUP BY region;
Delete all records from the "ocean_temperature" table where the temperature is below -2 degrees Celsius
CREATE TABLE ocean_temperature (id INT PRIMARY KEY,location VARCHAR(255),temperature FLOAT); INSERT INTO ocean_temperature (id,location,temperature) VALUES (1,'Pacific Ocean',28.5); INSERT INTO ocean_temperature (id,location,temperature) VALUES (2,'Atlantic Ocean',29.8); INSERT INTO ocean_temperature (id,location,temperature) VALUES (3,'Indian Ocean',27.3);
DELETE FROM ocean_temperature WHERE temperature < -2;
What is the minimum depth of all marine protected areas in the Pacific region?
CREATE TABLE marine_protected_areas (name TEXT,region TEXT,min_depth FLOAT); INSERT INTO marine_protected_areas (name,region,min_depth) VALUES ('MPA1','Pacific',123.45); INSERT INTO marine_protected_areas (name,region,min_depth) VALUES ('MPA2','Atlantic',234.56);
SELECT MIN(min_depth) FROM marine_protected_areas WHERE region = 'Pacific';
List all smart contracts and their respective total transaction volume for Q3 2021, ordered by the smart contracts with the highest transaction volume in Q3 2021.
CREATE TABLE SmartContracts (contract_id INT,contract_name VARCHAR(255),transaction_volume DECIMAL(18,2)); INSERT INTO SmartContracts (contract_id,contract_name,transaction_volume) VALUES (1,'Uniswap',156789.12),(2,'SushiSwap',256789.12),(3,'Aave',356789.12),(4,'Compound',456789.12),(5,'Yearn Finance',556789.12);
SELECT contract_name, transaction_volume FROM (SELECT contract_name, transaction_volume, RANK() OVER (ORDER BY transaction_volume DESC) as rank FROM SmartContracts WHERE SmartContracts.transaction_date BETWEEN '2021-07-01' AND '2021-09-30') AS ranked_contracts ORDER BY rank;
What are the top 3 decentralized applications by transaction volume?
CREATE TABLE decentralized_applications (id INT,dapp_name VARCHAR(255),transaction_volume INT); INSERT INTO decentralized_applications (id,dapp_name,transaction_volume) VALUES (1,'Uniswap',10000000),(2,'Aave',5000000),(3,'Compound',7000000),(4,'SushiSwap',8000000),(5,'Yearn Finance',6000000),(6,'MakerDAO',9000000);
SELECT dapp_name, transaction_volume FROM decentralized_applications ORDER BY transaction_volume DESC LIMIT 3;
What is the total area of 'Temperate Forests' under sustainable management?
CREATE TABLE TemperateForests (region VARCHAR(20),area FLOAT,management_status VARCHAR(10)); INSERT INTO TemperateForests (region,area,management_status) VALUES ('Temperate Forests',12345.67,'sustainable'),('Temperate Forests',8765.43,'unsustainable');
SELECT SUM(area) FROM TemperateForests WHERE region = 'Temperate Forests' AND management_status = 'sustainable';
Which beauty products have lead ingredients associated with health risks?
CREATE TABLE products (product_id INT,product_name VARCHAR(100),brand_name VARCHAR(100));CREATE TABLE ingredients (ingredient_id INT,ingredient_name VARCHAR(100),lead_indicator BOOLEAN);CREATE TABLE product_ingredients (product_id INT,ingredient_id INT);
SELECT p.product_name, i.ingredient_name FROM products p JOIN product_ingredients pi ON p.product_id = pi.product_id JOIN ingredients i ON pi.ingredient_id = i.ingredient_id WHERE i.lead_indicator = true;
What is the total revenue for each cultural event category, and how many events are there in total for each category?
CREATE TABLE revenue (id INT,event TEXT,category TEXT,price DECIMAL(5,2),quantity INT); INSERT INTO revenue (id,event,category,price,quantity) VALUES (1,'Concert','music',50.00,100),(2,'Jazz Festival','music',35.00,200),(3,'Theatre Play','theatre',75.00,150);
SELECT category, SUM(price * quantity) as total_revenue, COUNT(DISTINCT event) as num_events FROM revenue GROUP BY category;
What is the minimum transaction amount for clients who made their first transaction in Q1 2023 and have a credit score over 800?
CREATE TABLE clients (client_id INT,name VARCHAR(50),credit_score INT,first_transaction_date DATE);CREATE TABLE transactions (transaction_id INT,client_id INT,transaction_date DATE,total_amount DECIMAL(10,2));
SELECT MIN(total_amount) FROM transactions t INNER JOIN clients c ON t.client_id = c.client_id WHERE c.first_transaction_date = t.transaction_date AND c.credit_score > 800 AND t.transaction_date BETWEEN '2023-01-01' AND '2023-03-31'
Find the total number of units produced by each worker, ranked by the highest total.
CREATE TABLE worker (id INT,name VARCHAR(50),units_produced INT); INSERT INTO worker (id,name,units_produced) VALUES (1,'John Doe',1000),(2,'Jane Smith',1200),(3,'Mike Johnson',1500),(4,'Alice Williams',1800);
SELECT name, SUM(units_produced) as total_units FROM worker GROUP BY name ORDER BY total_units DESC;
Update the 'Angkor Wat' excavation to have a start date of 1300-01-01.
CREATE TABLE ExcavationSites (SiteID INT PRIMARY KEY,Name VARCHAR(255),Country VARCHAR(255),StartDate DATE,EndDate DATE); INSERT INTO ExcavationSites (SiteID,Name,Country,StartDate,EndDate) VALUES (5,'Angkor Wat','Cambodia','1860-01-01','1860-05-01');
UPDATE ExcavationSites SET StartDate = '1300-01-01' WHERE Name = 'Angkor Wat';
Update the location of a rural clinic in 'rural_clinics' table.
CREATE TABLE rural_clinics (id INT,name TEXT,location TEXT,num_workers INT,avg_age FLOAT);
UPDATE rural_clinics SET location = 'Rural Area 6' WHERE id = 3;
What is the total number of patients served by rural healthcare centers in Canada and the UK, excluding those served in urban areas?
CREATE TABLE patients_canada_uk (name TEXT,location TEXT,healthcare_center TEXT,served_in INT); INSERT INTO patients_canada_uk (name,location,healthcare_center,served_in) VALUES ('Patient A','Rural Canada','HC A',1),('Patient B','Urban Canada','HC B',1),('Patient C','Rural UK','HC C',1);
SELECT SUM(served_in) as total_patients FROM patients_canada_uk WHERE location LIKE 'Rural%';
What's the total number of sustainable investments made by venture capital firms in the United States?
CREATE TABLE venture_capitals (id INT,name VARCHAR(100),location VARCHAR(100)); INSERT INTO venture_capitals (id,name,location) VALUES (1,'Sequoia Capital','United States'),(2,'Kleiner Perkins','United States'); CREATE TABLE sustainable_investments (id INT,venture_capital_id INT,value FLOAT); INSERT INTO sustainable_investments (id,venture_capital_id,value) VALUES (1,1,10000000),(2,1,20000000),(3,2,15000000);
SELECT SUM(value) FROM sustainable_investments JOIN venture_capitals ON sustainable_investments.venture_capital_id = venture_capitals.id WHERE venture_capitals.location = 'United States';
How many volunteer hours were recorded for each program in Q2 2021?
CREATE TABLE VolunteerHours (VolunteerID INT,ProgramID INT,Hours DECIMAL(5,2),HourDate DATE); INSERT INTO VolunteerHours (VolunteerID,ProgramID,Hours,HourDate) VALUES (1,1,5,'2021-04-15'),(2,2,3,'2021-06-02'),(1,1,4,'2021-05-31'),(3,3,2,'2021-04-01'); CREATE TABLE Programs (ProgramID INT,ProgramName TEXT); INSERT INTO Programs (ProgramID,ProgramName) VALUES (1,'Arts & Culture'),(2,'Health & Wellness'),(3,'Environment');
SELECT ProgramID, SUM(Hours) as TotalHours FROM VolunteerHours WHERE HourDate BETWEEN '2021-04-01' AND '2021-06-30' GROUP BY ProgramID;
Find the CO2 emissions (t) of the energy sector in Australia
CREATE TABLE co2_emissions (id INT,country VARCHAR(50),sector VARCHAR(50),emissions FLOAT); INSERT INTO co2_emissions (id,country,sector,emissions) VALUES (1,'Canada','Transportation',120),(2,'Canada','Energy',150),(3,'Australia','Energy',200);
SELECT emissions FROM co2_emissions WHERE country = 'Australia' AND sector = 'Energy';