instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum dissolved oxygen level (in mg/L) for each species in PondFarm2?
CREATE TABLE PondFarm2 (species VARCHAR(20),dissolved_oxygen FLOAT); INSERT INTO PondFarm2 (species,dissolved_oxygen) VALUES ('Shrimp',4.5),('Crab',5.2),('Lobster',6.8);
SELECT species, MIN(dissolved_oxygen) FROM PondFarm2 GROUP BY species;
What is the average permit value for sustainable building projects in New York, for the past 24 months?
CREATE TABLE ny_permits (id INT,permit_id VARCHAR(50),permit_value FLOAT,permit_date DATE,city VARCHAR(50),state VARCHAR(50),sustainable_building VARCHAR(50)); INSERT INTO ny_permits (id,permit_id,permit_value,permit_date,city,state,sustainable_building) VALUES (1,'123456',1500000,'2021-04-20','New York','NY','Yes'),(2,'789101',1200000,'2021-03-15','New York','NY','No'),(3,'111213',900000,'2021-02-05','New York','NY','Yes');
SELECT AVG(permit_value) as avg_permit_value FROM ny_permits WHERE state = 'NY' AND permit_date >= DATEADD(MONTH, -24, CURRENT_DATE) AND sustainable_building = 'Yes' GROUP BY sustainable_building;
What is the maximum billing amount for cases in California?
CREATE TABLE Cases (CaseID INT,State VARCHAR(20),BillingAmount DECIMAL(10,2)); INSERT INTO Cases (CaseID,State,BillingAmount) VALUES (1,'California',5000.00),(2,'Texas',3500.00),(3,'California',4000.00),(4,'New York',6000.00);
SELECT MAX(BillingAmount) FROM Cases WHERE State = 'California';
What was the total R&D expenditure for each division in Q1 2020?
CREATE TABLE r_d_expenditure (division VARCHAR(20),date DATE,amount NUMERIC(12,2)); INSERT INTO r_d_expenditure (division,date,amount) VALUES ('Oncology','2020-01-01',1500000.00),('Cardiology','2020-01-01',1200000.00),('Neurology','2020-01-01',900000.00),('Oncology','2020-01-02',1550000.00),('Cardiology','2020-01-02',1230000.00),('Neurology','2020-01-02',915000.00);
SELECT division, SUM(amount) AS total_expenditure FROM r_d_expenditure WHERE date BETWEEN '2020-01-01' AND '2020-03-31' GROUP BY division;
How many HIV tests were performed in New York in the last 6 months?
CREATE TABLE hiv_tests (id INT,test_date DATE,location TEXT); INSERT INTO hiv_tests (id,test_date,location) VALUES (1,'2022-01-01','New York'); INSERT INTO hiv_tests (id,test_date,location) VALUES (2,'2022-02-15','New York');
SELECT COUNT(*) FROM hiv_tests WHERE location = 'New York' AND test_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
How many infectious disease outbreaks were reported in each region of the world in the year 2021?
CREATE TABLE public.outbreaks (id SERIAL PRIMARY KEY,region TEXT,year INTEGER,disease TEXT); INSERT INTO public.outbreaks (region,year,disease) VALUES ('Africa',2021,'Ebola'),('Asia',2021,'COVID-19'),('Europe',2021,'Monkeypox'),('North America',2021,'Measles'),('South America',2021,'Yellow Fever'),('Australia',2021,'Dengue');
SELECT region, COUNT(*) FROM public.outbreaks WHERE year = 2021 GROUP BY region;
Calculate the average diversity score for companies founded in each quarter, for the year 2017
CREATE TABLE company_founding (id INT,company_name VARCHAR(50),year INT,quarter INT,diversity_score DECIMAL(3,2));
SELECT quarter, AVG(diversity_score) AS avg_diversity_score FROM company_founding WHERE year = 2017 GROUP BY quarter;
Update the exit type for "Delta Inc" to "Merger" in the "exit_strategies" table
CREATE TABLE exit_strategies (company_name VARCHAR(255),exit_year INT,exit_type VARCHAR(50),exit_region VARCHAR(50));
UPDATE exit_strategies SET exit_type = 'Merger' WHERE company_name = 'Delta Inc';
What are the names of female founders who have received Series A funding or higher?
CREATE TABLE founder (id INT,name TEXT,gender TEXT,funding TEXT); INSERT INTO founder (id,name,gender,funding) VALUES (1,'Alice','Female','Series A');
SELECT name FROM founder WHERE gender = 'Female' AND funding IN ('Series A', 'Series B', 'Series C', 'Series D', 'Series E');
What is the average temperature for each crop type in the 'agriculture' database?
CREATE TABLE crop (id INT,type VARCHAR(255),temperature FLOAT); INSERT INTO crop (id,type,temperature) VALUES (1,'corn',20.5),(2,'wheat',15.3),(3,'rice',22.1);
SELECT type, AVG(temperature) as avg_temperature FROM crop GROUP BY type;
Which urban agriculture initiatives in 'Montreal' have an area greater than 0.5 hectares?
CREATE TABLE urban_agriculture_initiatives (id INT,name TEXT,location TEXT,area_ha FLOAT); INSERT INTO urban_agriculture_initiatives (id,name,location,area_ha) VALUES (1,'Initiative A','Montreal',0.8),(2,'Initiative B','Montreal',0.4),(3,'Initiative C','Toronto',0.6);
SELECT name FROM urban_agriculture_initiatives WHERE location = 'Montreal' AND area_ha > 0.5;
List all the marine species and their conservation status in the Atlantic Ocean.
CREATE TABLE marine_species (id INT,name VARCHAR(50),region VARCHAR(50),conservation_status VARCHAR(50)); INSERT INTO marine_species (id,name,region,conservation_status) VALUES (1,'Dolphin','Atlantic Ocean','Vulnerable'); CREATE TABLE conservation_status (id INT,name VARCHAR(50));
SELECT marine_species.name, marine_species.conservation_status FROM marine_species INNER JOIN conservation_status ON marine_species.conservation_status = conservation_status.name;
What is the total volume of timber harvested by each region?
CREATE TABLE regions (region_id INT,region_name VARCHAR(255)); INSERT INTO regions (region_id,region_name) VALUES (1,'North'),(2,'South'),(3,'East'),(4,'West'); CREATE TABLE timber_harvest (region_id INT,year INT,volume INT); INSERT INTO timber_harvest (region_id,year,volume) VALUES (1,2020,1200),(1,2021,1500),(2,2020,800),(2,2021,1000),(3,2020,1700),(3,2021,1900),(4,2020,1100),(4,2021,1300);
SELECT region_name, SUM(volume) as total_volume FROM timber_harvest TH JOIN regions ON TH.region_id = regions.region_id GROUP BY region_name;
Who are the top 3 customers by total spend on makeup products from Italy and Spain?
CREATE TABLE customers (customer_id INT,customer_name TEXT,country TEXT); INSERT INTO customers (customer_id,customer_name,country) VALUES (1,'Alessandro Martini','IT'),(2,'Laura Rossi','ES'),(3,'Daniela Gonzalez','MX'),(4,'Jose Hernandez','ES'),(5,'Sophia Rodriguez','IT'); CREATE TABLE sales (sale_id INT,customer_id INT,product_id INT,sale_quantity INT,sale_country TEXT); INSERT INTO sales (sale_id,customer_id,product_id,sale_quantity,sale_country) VALUES (1,1,1,100,'IT'),(2,2,2,150,'ES'),(3,3,3,200,'MX'),(4,4,4,250,'ES'),(5,5,5,300,'IT'); CREATE TABLE products (product_id INT,product_name TEXT,category TEXT); INSERT INTO products (product_id,product_name,category) VALUES (1,'Eyeshadow Palette','makeup'),(2,'Liquid Lipstick','makeup'),(3,'BB Cream','makeup'),(4,'Volumizing Mascara','makeup'),(5,'Nourishing Lip Balm','makeup');
SELECT c.customer_name, SUM(s.sale_quantity) as total_spent_on_makeup FROM sales s JOIN customers c ON s.customer_id = c.customer_id JOIN products p ON s.product_id = p.product_id WHERE c.country IN ('IT', 'ES') AND p.category = 'makeup' GROUP BY c.customer_name ORDER BY total_spent_on_makeup DESC LIMIT 3;
List the police stations with their corresponding community policing metric scores?
CREATE TABLE PoliceStations (ID INT,Name VARCHAR(50)); CREATE TABLE CommunityPolicing (StationID INT,Score INT);
SELECT PS.Name, CP.Score FROM PoliceStations PS INNER JOIN CommunityPolicing CP ON PS.ID = CP.StationID;
What is the maximum number of high-level threats reported by a single agency in a month?
CREATE TABLE Threat_Intelligence (Threat_ID INT,Threat_Type VARCHAR(50),Threat_Level VARCHAR(50),Reported_Date DATE,Reporting_Agency VARCHAR(50)); CREATE VIEW High_Level_Threats AS SELECT Threat_Type,Threat_Level,Reported_Date FROM Threat_Intelligence WHERE Threat_Level = 'High';
SELECT Reporting_Agency, MAX(Number_of_High_Level_Threats) as Max_High_Level_Threats_in_a_Month FROM (SELECT Reporting_Agency, TO_CHAR(Reported_Date, 'YYYY-MM') as Month, COUNT(*) as Number_of_High_Level_Threats FROM High_Level_Threats GROUP BY Reporting_Agency, Month) GROUP BY Reporting_Agency;
What was the total peacekeeping operations budget for African countries in 2020?
CREATE TABLE peacekeeping_operations_africa (country VARCHAR(50),year INT,budget INT); INSERT INTO peacekeeping_operations_africa (country,year,budget) VALUES ('Nigeria',2020,1200000),('South Africa',2020,1100000),('Egypt',2020,1000000),('Algeria',2020,900000),('Morocco',2020,800000);
SELECT SUM(budget) total_budget FROM peacekeeping_operations_africa WHERE country IN ('Nigeria', 'South Africa', 'Egypt', 'Algeria', 'Morocco') AND year = 2020;
Delete all records from the "Artifacts" table where the artifact type is "Pottery" and the artifact's age is greater than 1000 years old.
CREATE TABLE Artifacts (id INT,artifact_type VARCHAR(50),age INT); INSERT INTO Artifacts (id,artifact_type,age) VALUES (1,'Pottery',1200);
DELETE FROM Artifacts WHERE artifact_type = 'Pottery' AND age > 1000;
Show the distribution of military technology by category in the 'military_inventory' table.
CREATE TABLE military_inventory (id INT,tech_name VARCHAR(50),tech_category VARCHAR(50),quantity INT); INSERT INTO military_inventory (id,tech_name,tech_category,quantity) VALUES (1,'M1 Abrams','Tanks',2500),(2,'Tomahawk Missiles','Missiles',3000);
SELECT tech_category, SUM(quantity) AS total_quantity FROM military_inventory GROUP BY tech_category;
What is the total number of streams for songs released before 2010, grouped by platform?
CREATE TABLE songs (song_id INT,song_name VARCHAR(100),release_year INT,genre VARCHAR(50)); INSERT INTO songs (song_id,song_name,release_year,genre) VALUES (1,'Shape of You',2017,'Pop'),(2,'Thinking Out Loud',2014,'Pop'),(3,'Bohemian Rhapsody',1975,'Rock'); CREATE TABLE streams (stream_id INT,song_id INT,platform VARCHAR(50),streams INT); INSERT INTO streams (stream_id,song_id,platform,streams) VALUES (1,1,'Spotify',1000000),(2,1,'Apple Music',750000),(3,2,'Spotify',800000),(4,2,'Apple Music',600000),(5,3,'Spotify',50000),(6,3,'Apple Music',40000);
SELECT st.platform, SUM(s.streams) as total_streams FROM songs s INNER JOIN streams st ON s.song_id = st.song_id WHERE s.release_year < 2010 GROUP BY st.platform;
What is the average monthly donation amount per state?
CREATE TABLE Donations (id INT,donor_name TEXT,donation_amount FLOAT,donation_date DATE,state TEXT); INSERT INTO Donations (id,donor_name,donation_amount,donation_date,state) VALUES (1,'James Smith',500,'2022-02-01','CA');
SELECT AVG(donation_amount) as avg_donation, state FROM Donations GROUP BY state;
What is the maximum donation amount for the 'Health' program?
CREATE TABLE Donations (donation_id INT,amount DECIMAL(10,2),program VARCHAR(255));
SELECT MAX(amount) FROM Donations WHERE program = 'Health';
What is the minimum lifelong learning credit requirement for each grade level, grouped by school, from the "schools_lifelong_learning_requirements" table?
CREATE TABLE schools_lifelong_learning_requirements (school_id INT,grade_level INT,lifelong_learning_credit_requirement INT);
SELECT school_id, grade_level, MIN(lifelong_learning_credit_requirement) as min_credit_requirement FROM schools_lifelong_learning_requirements GROUP BY school_id, grade_level;
Add a new ethnicity called 'Middle Eastern' to the Ethnicity table
CREATE TABLE Ethnicity (EthnicityID INT PRIMARY KEY,EthnicityName VARCHAR(50));
INSERT INTO Ethnicity (EthnicityID, EthnicityName) VALUES (6, 'Middle Eastern');
Delete the record of employee with ID 2
CREATE SCHEMA IF NOT EXISTS hr;CREATE TABLE IF NOT EXISTS employees (id INT,name VARCHAR(50),department VARCHAR(50),hire_date DATE);INSERT INTO employees (id,name,department,hire_date) VALUES (1,'John Doe','IT','2020-01-15');INSERT INTO employees (id,name,department,hire_date) VALUES (2,'Jane Smith','HR','2019-06-20');INSERT INTO employees (id,name,department,hire_date) VALUES (3,'Jim Brown','Finance','2020-04-01');
DELETE FROM hr.employees WHERE id = 2;
What is the total number of employees hired in each quarter of 2021?
CREATE TABLE Employees (id INT,name VARCHAR(50),department VARCHAR(50),hire_date DATE); INSERT INTO Employees (id,name,department,hire_date) VALUES (1,'John Doe','HR','2021-01-15'); INSERT INTO Employees (id,name,department,hire_date) VALUES (2,'Jane Smith','IT','2021-03-20'); INSERT INTO Employees (id,name,department,hire_date) VALUES (3,'Alice Johnson','Finance','2021-06-10');
SELECT EXTRACT(QUARTER FROM hire_date) AS quarter, COUNT(*) AS total_hired FROM Employees WHERE hire_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY quarter;
How many healthcare facilities were established in total, by organizations located in "Africa" with the org_category "Community-based"?
CREATE TABLE healthcare_facilities (id INT,org_location VARCHAR(20),org_category VARCHAR(20),establishment_year INT); INSERT INTO healthcare_facilities (id,org_location,org_category,establishment_year) VALUES (1,'Africa','Community-based',2010),(2,'Asia','Governmental',2015),(3,'Africa','Community-based',2012);
SELECT COUNT(*) FROM healthcare_facilities WHERE org_location = 'Africa' AND org_category = 'Community-based';
What is the maximum donation amount made by 'CARE' to 'Health' projects in 'Africa'?
CREATE TABLE donations (id INT,donor VARCHAR(255),project VARCHAR(255),region VARCHAR(255),amount DECIMAL(10,2),donation_date DATE); INSERT INTO donations (id,donor,project,region,amount,donation_date) VALUES (1,'CARE','Health','Africa',15000,'2022-02-28');
SELECT MAX(amount) FROM donations WHERE donor = 'CARE' AND project = 'Health' AND region = 'Africa';
How many organizations are working on social good in the Middle East?
CREATE TABLE social_good_middle_east (organization_name VARCHAR(100),region VARCHAR(50)); INSERT INTO social_good_middle_east (organization_name,region) VALUES ('Tech4Peace','Middle East'),('DigitalEquality','Middle East'),('TechForChange','Middle East');
SELECT COUNT(organization_name) FROM social_good_middle_east WHERE region = 'Middle East';
What was the total fare collected from the Green Line on March 8th, 2022?
CREATE TABLE routes (route_id INT,route_name VARCHAR(255)); INSERT INTO routes (route_id,route_name) VALUES (1,'Red Line'),(2,'Blue Line'),(3,'Green Line'); CREATE TABLE fares (fare_id INT,route_id INT,fare_amount DECIMAL(5,2),fare_date DATE); INSERT INTO fares (fare_id,route_id,fare_amount,fare_date) VALUES (1,1,3.50,'2022-01-03'),(2,2,4.25,'2022-02-14'),(3,3,2.75,'2022-03-08');
SELECT SUM(fare_amount) FROM fares WHERE route_id = 3 AND fare_date = '2022-03-08';
Identify items that use a linear production method and are made of polyester
CREATE TABLE methods (id INT,item_id INT,quantity INT,method VARCHAR(255)); INSERT INTO methods (id,item_id,quantity,method) VALUES (1,1,100,'circular'),(2,2,75,'linear'),(3,1,50,'linear'); CREATE TABLE materials (id INT,item_id INT,material VARCHAR(255)); INSERT INTO materials (id,item_id,material) VALUES (1,1,'cotton'),(2,2,'polyester'),(3,3,'wool');
SELECT m.item_id FROM methods m JOIN materials mat ON m.item_id = mat.item_id WHERE m.method = 'linear' AND mat.material = 'polyester';
How many new users registered in the last week from the US?
CREATE TABLE users (id INT PRIMARY KEY,name VARCHAR(255),registered_date DATETIME,country VARCHAR(255));
SELECT COUNT(*) FROM users WHERE registered_date >= DATEADD(week, -1, GETDATE()) AND country = 'US';
Determine the number of financially capable customers in Q1 and Q2 of 2022.
CREATE TABLE financial_capability(customer_id INT,score DECIMAL(3,1),measure_date DATE); INSERT INTO financial_capability VALUES (1,75,'2022-01-15'),(2,80,'2022-04-01'),(3,70,'2022-03-05'),(4,85,'2022-05-12'),(5,72,'2022-02-01'),(6,78,'2022-01-02');
SELECT TO_CHAR(measure_date, 'YYYY-Q') AS quarter, COUNT(*) FROM financial_capability WHERE measure_date >= '2022-01-01' AND measure_date < '2022-07-01' GROUP BY quarter;
What is the average financial capability score for each occupation, pivoted by gender?
CREATE TABLE financial_capability_3 (occupation VARCHAR(255),gender VARCHAR(255),score INT); INSERT INTO financial_capability_3 (occupation,gender,score) VALUES ('Doctor','Male',1400),('Doctor','Female',1450),('Engineer','Male',1300),('Engineer','Female',1320),('Teacher','Male',1200),('Teacher','Female',1210),('Lawyer','Male',1500),('Lawyer','Female',1510);
SELECT occupation, SUM(CASE WHEN gender = 'Male' THEN score ELSE 0 END)/SUM(CASE WHEN gender = 'Male' THEN 1 ELSE 0 END) AS male_avg, SUM(CASE WHEN gender = 'Female' THEN score ELSE 0 END)/SUM(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) AS female_avg FROM financial_capability_3 GROUP BY occupation;
Find genetic researchers and their projects
CREATE TABLE researchers (id INT,name VARCHAR(50),domain VARCHAR(50)); INSERT INTO researchers (id,name,domain) VALUES (1,'Alice','Genetics'); INSERT INTO researchers (id,name,domain) VALUES (2,'Bob','Bioengineering'); CREATE TABLE projects (id INT,name VARCHAR(50),researcher_id INT); INSERT INTO projects (id,name,researcher_id) VALUES (1,'Genome Mapping',1); INSERT INTO projects (id,name,researcher_id) VALUES (2,'Protein Folding',1);
SELECT r.name, p.name as project_name FROM researchers r JOIN projects p ON r.id = p.researcher_id WHERE r.domain = 'Genetics';
List the number of eco-friendly hotels in each country and their total revenue.
CREATE TABLE eco_hotels (hotel_id INT,name TEXT,country TEXT,revenue FLOAT); INSERT INTO eco_hotels VALUES (1,'Green Hotel','France',350000),(2,'Eco Lodge','Spain',400000),(3,'Sustainable Resort','France',550000);
SELECT country, COUNT(*), SUM(revenue) FROM eco_hotels GROUP BY country;
Find the total number of artworks by female artists in the 'Renaissance' period.
CREATE TABLE Artworks(artist VARCHAR(20),period VARCHAR(20),art_id INT); INSERT INTO Artworks VALUES ('Leonardo da Vinci','Renaissance',1),('Michelangelo','Renaissance',2),('Raphael','Renaissance',3),('Artemisia Gentileschi','Renaissance',4),('Sofonisba Anguissola','Renaissance',5);
SELECT COUNT(*) FROM Artworks WHERE period = 'Renaissance' AND artist IN (SELECT artist FROM Artworks WHERE artist LIKE '%_%');
List all heritage sites in the Asian region with their corresponding preservation status.
CREATE TABLE heritage_sites (id INT PRIMARY KEY,name VARCHAR(50),region VARCHAR(30),status VARCHAR(20)); INSERT INTO heritage_sites (id,name,region,status) VALUES (1,'Angkor Wat','Asia','Preserved'),(2,'Forbidden City','Asia','Preserved'),(3,'Petra','Asia','At Risk');
SELECT name, status FROM heritage_sites WHERE region = 'Asia';
What is the average year of establishment for heritage sites in each country?
CREATE TABLE heritage_sites (site_id INT,name VARCHAR(50),location VARCHAR(50),year INT,type VARCHAR(50));
SELECT location, AVG(year) AS avg_year FROM heritage_sites GROUP BY location;
What is the name, length, and material for all railways in the province of Ontario with a length greater than 100 kilometers?
CREATE TABLE Railways (id INT,name VARCHAR(100),length FLOAT,material VARCHAR(50),province VARCHAR(50)); INSERT INTO Railways (id,name,length,material,province) VALUES (1,'Canadian National Railway',32000,'Steel','Ontario');
SELECT name, length, material FROM Railways WHERE province = 'Ontario' AND length > 100;
What is the average hotel price in Tokyo compared to Osaka?
CREATE TABLE hotel_prices (city VARCHAR(50),price DECIMAL(5,2)); INSERT INTO hotel_prices (city,price) VALUES ('Tokyo',120),('Tokyo',150),('Tokyo',100),('Osaka',90),('Osaka',80),('Osaka',100);
SELECT AVG(price) as avg_price FROM hotel_prices WHERE city = 'Tokyo' OR city = 'Osaka' GROUP BY city;
What is the percentage of legal technology patents granted to applicants in California since 2010?
CREATE TABLE legal_technology_patents (patent_id INT,grant_date DATE,state VARCHAR(20));
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM legal_technology_patents WHERE grant_date >= '2010-01-01')) AS percentage FROM legal_technology_patents WHERE state = 'California';
How many podcast episodes were published in 2019 by creators from underrepresented communities?
CREATE TABLE podcasts (id INT,title VARCHAR(100),publication_year INT,creator_community VARCHAR(50)); INSERT INTO podcasts (id,title,publication_year,creator_community) VALUES (1,'Podcast1',2019,'Underrepresented Community'),(2,'Podcast2',2018,'Mainstream Community'),(3,'Podcast3',2019,'Mainstream Community');
SELECT COUNT(*) FROM podcasts WHERE publication_year = 2019 AND creator_community = 'Underrepresented Community';
List all the unique content diversity topics in the 'content' table.
CREATE TABLE content (id INT,topic VARCHAR(255));
SELECT DISTINCT topic FROM content;
What is the average price of vegan menu items in the database?
CREATE TABLE menus (menu_id INT,menu_name TEXT,type TEXT,price DECIMAL); INSERT INTO menus (menu_id,menu_name,type,price) VALUES (1,'Quinoa Salad','Vegetarian',12.99),(2,'Chicken Caesar Wrap','Gluten-free',10.99),(3,'Vegan Burger','Vegan',14.99),(4,'Falafel Wrap','Vegan',9.99);
SELECT AVG(price) FROM menus WHERE type = 'Vegan';
What is the total value of military equipment sales to Africa in Q3 2020, partitioned by week?
CREATE TABLE Military_Equipment_Sales (sale_id INT,sale_date DATE,equipment_type VARCHAR(255),country VARCHAR(255),sale_value FLOAT); INSERT INTO Military_Equipment_Sales (sale_id,sale_date,equipment_type,country,sale_value) VALUES (1,'2020-07-01','Aircraft','Nigeria',5000000),(2,'2020-07-15','Armored Vehicles','Algeria',2000000),(3,'2020-09-01','Naval Vessels','Egypt',12000000);
SELECT sale_date, SUM(sale_value) AS total_sales FROM Military_Equipment_Sales WHERE country IN ('Nigeria', 'Algeria', 'Egypt') AND sale_date BETWEEN '2020-07-01' AND '2020-09-30' GROUP BY sale_date, WEEK(sale_date);
What is the number of diamond mines with an extraction rate higher than 90% in the African continent?
CREATE TABLE diamond_mines (id INT,name TEXT,country TEXT,extraction_rate FLOAT); INSERT INTO diamond_mines (id,name,country,extraction_rate) VALUES (1,'Diamond Mine 1','South Africa',0.92); INSERT INTO diamond_mines (id,name,country,extraction_rate) VALUES (2,'Diamond Mine 2','Botswana',0.88);
SELECT COUNT(*) FROM diamond_mines WHERE extraction_rate > 0.9 AND country IN ('South Africa', 'Botswana', 'Angola', 'DRC', 'Namibia', 'Lesotho', 'Sierra Leone', 'Ghana', 'Liberia', 'Guinea', 'Ivory Coast');
What is the total tonnage of copper mined in African mines?
CREATE TABLE mine (id INT,region VARCHAR(20),mineral VARCHAR(20),tons INT); INSERT INTO mine (id,region,mineral,tons) VALUES (1,'Asia-Pacific','gold',2000),(2,'Asia-Pacific','silver',3000),(3,'Americas','gold',5000),(4,'Americas','copper',8000),(5,'Africa','gold',1000),(6,'Africa','copper',6000);
SELECT SUM(tons) FROM mine WHERE mineral = 'copper' AND region = 'Africa';
What is the monthly data usage for the top 3 subscribers in 'Africa', ordered by usage in descending order?
CREATE TABLE subscribers (subscriber_id INT,data_usage FLOAT,region VARCHAR(10)); INSERT INTO subscribers (subscriber_id,data_usage,region) VALUES (4,35,'Africa'),(5,58,'Africa'),(6,45,'Africa'),(7,21,'Africa'),(8,90,'Africa');
SELECT subscriber_id, data_usage FROM (SELECT subscriber_id, data_usage, ROW_NUMBER() OVER (PARTITION BY region ORDER BY data_usage DESC) as rn FROM subscribers WHERE region = 'Africa') subquery WHERE rn <= 3 ORDER BY data_usage DESC;
What is the monthly data usage for the top 5 subscribers in the 'west' region, ordered by usage in descending order?
CREATE TABLE subscribers (subscriber_id INT,data_usage FLOAT,region VARCHAR(10)); INSERT INTO subscribers (subscriber_id,data_usage,region) VALUES (4,35,'west'),(5,28,'west'),(6,45,'west');
SELECT subscriber_id, data_usage FROM (SELECT subscriber_id, data_usage, ROW_NUMBER() OVER (PARTITION BY region ORDER BY data_usage DESC) as rn FROM subscribers WHERE region = 'west') subquery WHERE rn <= 5 ORDER BY data_usage DESC;
Determine the ticket sales revenue for each artist's first concert in their career.
CREATE TABLE ticket_sales (sale_id INT,artist_name VARCHAR(100),concert_location VARCHAR(100),num_tickets INT,ticket_price INT,sale_date DATE); INSERT INTO ticket_sales (sale_id,artist_name,concert_location,num_tickets,ticket_price,sale_date) VALUES (1,'Taylor Swift','Nashville,USA',5000,50,'2006-06-01'); INSERT INTO ticket_sales (sale_id,artist_name,concert_location,num_tickets,ticket_price,sale_date) VALUES (2,'BTS','Seoul,South Korea',10000,30,'2013-06-01');
SELECT artist_name, num_tickets * ticket_price as first_concert_revenue FROM ticket_sales WHERE sale_id = (SELECT MIN(sale_id) FROM ticket_sales WHERE artist_name = ticket_sales.artist_name);
Update the max_depth of the Arctic Ocean's Molloy Deep in the ocean_floors table to -5650.
CREATE TABLE ocean_floors (ocean VARCHAR(255),deepest_point VARCHAR(255),max_depth INT); INSERT INTO ocean_floors (ocean,deepest_point,max_depth) VALUES ('Atlantic','Puerto Rico Trench',-8673),('Arctic','Molloy Deep',-5607);
UPDATE ocean_floors SET max_depth = -5650 WHERE ocean = 'Arctic' AND deepest_point = 'Molloy Deep';
Which organizations have received donations from donors in India?
CREATE TABLE Donors (Id INT PRIMARY KEY,Name VARCHAR(100),Age INT,DonationAmount DECIMAL(10,2)); INSERT INTO Donors (Id,Name,Age,DonationAmount) VALUES (2,'Akshay Kumar',40,600.00); CREATE TABLE Donations (Id INT PRIMARY KEY,DonorId INT,OrganizationId INT,Amount DECIMAL(10,2)); INSERT INTO Donations (Id,DonorId,OrganizationId,Amount) VALUES (1,2,5,300.00); INSERT INTO Donations (Id,DonorId,OrganizationId,Amount) VALUES (2,3,6,500.00); CREATE TABLE Organizations (Id INT PRIMARY KEY,Name VARCHAR(100),Sector VARCHAR(50)); INSERT INTO Organizations (Id,Name,Sector) VALUES (5,'Asha for Education','Education'); INSERT INTO Organizations (Id,Name,Sector) VALUES (6,'CRY - Child Rights and You','Human Rights'); CREATE TABLE Countries (Id INT PRIMARY KEY,Name VARCHAR(100),Continent VARCHAR(50)); INSERT INTO Countries (Id,Name,Continent) VALUES (2,'India','Asia'); INSERT INTO Countries (Id,Name,Continent) VALUES (3,'Mali','Africa');
SELECT Organizations.Name FROM Organizations JOIN Donations ON Organizations.Id=Donations.OrganizationId JOIN Donors ON Donations.DonorId=Donors.Id JOIN Countries ON Donors.Name=Countries.Name WHERE Countries.Continent = 'Asia';
How many players from 'Europe' have played 'Space Explorers' for more than 4 hours?
CREATE TABLE Player_Details (Player_ID INT,Player_Name VARCHAR(50),Country VARCHAR(50),Playtime INT,Game_Name VARCHAR(50)); INSERT INTO Player_Details (Player_ID,Player_Name,Country,Playtime,Game_Name) VALUES (1,'John Doe','France',240,'Space Explorers'),(2,'Jane Smith','Germany',540,'Space Explorers'),(3,'Mike Johnson','UK',480,'Space Explorers'),(4,'Sara Connor','Spain',300,'Space Explorers'),(5,'David Brown','Italy',420,'Space Explorers');
SELECT COUNT(Player_ID) FROM Player_Details WHERE Game_Name = 'Space Explorers' AND Country = 'Europe' AND Playtime > 4 * 60;
Count the number of games released in 2020
CREATE TABLE Games (GameID INT,ReleaseYear INT); INSERT INTO Games (GameID,ReleaseYear) VALUES (1,2019); INSERT INTO Games (GameID,ReleaseYear) VALUES (2,2020);
SELECT COUNT(*) FROM Games WHERE ReleaseYear = 2020;
Identify the top 5 most common combinations of game genres played by female players.
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),GameGenre VARCHAR(10));CREATE TABLE MultiplayerGames (GameID INT,PlayerID INT);
SELECT g.GameGenre, COUNT(*) as Count FROM Players p INNER JOIN MultiplayerGames mg ON p.PlayerID = mg.PlayerID WHERE p.Gender = 'Female' GROUP BY g.GameGenre ORDER BY Count DESC LIMIT 5;
What was the minimum production volume of Europium in 2016?
CREATE TABLE europium_production (year INT,production_volume INT); INSERT INTO europium_production VALUES (2015,15),(2016,18),(2017,20),(2018,22),(2019,25);
SELECT MIN(production_volume) FROM europium_production WHERE year = 2016;
What is the average number of rental units in each income-restricted development?
CREATE TABLE IncomeRestrictedDevelopments (DevelopmentID INT,DevelopmentName VARCHAR(255)); CREATE TABLE RentalUnits (UnitID INT,DevelopmentID INT,UnitType VARCHAR(255));
SELECT D.DevelopmentName, AVG(COUNT(RU.UnitID)) as AvgRentalUnitsPerDevelopment FROM IncomeRestrictedDevelopments D JOIN RentalUnits RU ON D.DevelopmentID = RU.DevelopmentID GROUP BY D.DevelopmentName;
Add a new category 'Plant-based' in the menu_categories table
CREATE TABLE menu_categories (category_id INT,category_name TEXT);
INSERT INTO menu_categories (category_name) VALUES ('Plant-based');
What is the sum of the weights (in kg) of all spacecraft ever built by Blue Origin?
CREATE TABLE spacecraft_manufacturers(id INT,name VARCHAR(255)); CREATE TABLE spacecraft(id INT,name VARCHAR(255),manufacturer_id INT,weight_kg FLOAT); INSERT INTO spacecraft_manufacturers(id,name) VALUES (1,'Blue Origin'); INSERT INTO spacecraft(id,name,manufacturer_id,weight_kg) VALUES (1,'New Glenn',1),(2,'New Shepard',1);
SELECT SUM(spacecraft.weight_kg) FROM spacecraft WHERE spacecraft.manufacturer_id = (SELECT id FROM spacecraft_manufacturers WHERE name = 'Blue Origin');
What is the average age of fans who prefer basketball and football in the 'fan_demographics' table?
CREATE TABLE fan_demographics (fan_name VARCHAR(50),favorite_sport VARCHAR(20),age INT,city VARCHAR(30)); INSERT INTO fan_demographics (fan_name,favorite_sport,age,city) VALUES ('Alice','Basketball',25,'Chicago'),('Bob','Soccer',35,'Los Angeles'),('Charlie','Basketball',30,'Miami');
SELECT favorite_sport, AVG(age) FROM fan_demographics WHERE favorite_sport IN ('Basketball', 'Football') GROUP BY favorite_sport;
What is the minimum severity of vulnerabilities detected in the last month for the HR department?
CREATE TABLE vulnerabilities (id INT,department VARCHAR(255),severity INT,detection_date DATE); INSERT INTO vulnerabilities (id,department,severity,detection_date) VALUES (1,'finance',7,'2022-01-05'),(2,'finance',5,'2022-02-10'),(3,'HR',3,'2022-01-02');
SELECT MIN(severity) FROM vulnerabilities WHERE detection_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND department = 'HR';
Which vulnerabilities in the healthcare sector have been exploited in the last year with a severity score greater than 7?
CREATE TABLE Vulnerabilities (vuln_id INT,vuln_severity INT,vuln_date DATE,vuln_target_sector VARCHAR(50),vuln_exploited INT);
SELECT vuln_id FROM Vulnerabilities WHERE vuln_target_sector = 'healthcare' AND vuln_severity > 7 AND vuln_exploited = 1 AND vuln_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND CURRENT_DATE;
Show public transportation usage in cities with populations over 5 million
CREATE TABLE cities (city_id INT,city_name VARCHAR(50),population INT);CREATE TABLE pt_usage (usage_id INT,city INT,passengers INT);INSERT INTO cities (city_id,city_name,population) VALUES (1,'Tokyo',9000000),(2,'New York',8000000),(3,'Los Angeles',6000000);INSERT INTO pt_usage (usage_id,city,passengers) VALUES (1,1,1000),(2,2,2000),(3,3,1500),(4,1,1200),(5,2,1800);
SELECT c.city_name, pu.passengers FROM cities c JOIN pt_usage pu ON c.city_id = pu.city WHERE c.population > 5000000;
Show the number of electric vehicle charging stations in the top 10 most populous cities in the US.
CREATE TABLE cities (city_name TEXT,population INT);CREATE TABLE charging_stations (station_id INT,station_name TEXT,city_name TEXT,num_charging_points INT);
SELECT c.city_name, COUNT(cs.station_id) AS num_charging_stations FROM cities c JOIN charging_stations cs ON c.city_name = cs.city_name GROUP BY c.city_name ORDER BY population DESC LIMIT 10;
What was the maximum number of units sold for any product in Germany in 2020?
CREATE TABLE product_sales (product_name VARCHAR(30),country VARCHAR(20),year INT,units_sold INT); INSERT INTO product_sales (product_name,country,year,units_sold) VALUES ('t-shirt','Germany',2020,1500),('jeans','Germany',2020,2000),('hoodie','Germany',2020,2500);
SELECT MAX(units_sold) FROM product_sales WHERE country = 'Germany' AND year = 2020;
List all autonomous driving research programs in the US and the number of safety tests conducted.
CREATE TABLE SafetyTests (Id INT,TestType VARCHAR(50),VehicleId INT,TestDate DATE,Program VARCHAR(100)); CREATE TABLE AutonomousVehicles (Id INT,Name VARCHAR(100),Program VARCHAR(100)); INSERT INTO SafetyTests (Id,TestType,VehicleId,TestDate,Program) VALUES (4,'Obstacle Detection',2,'2021-03-23','AutonomousDrivingUS'),(5,'Pedestrian Detection',2,'2021-03-24','AutonomousDrivingUS'); INSERT INTO AutonomousVehicles (Id,Name,Program) VALUES (2,'AutonomousCar','AutonomousDrivingUS');
SELECT AutonomousVehicles.Program, COUNT(SafetyTests.Id) FROM AutonomousVehicles INNER JOIN SafetyTests ON AutonomousVehicles.Id = SafetyTests.VehicleId WHERE Program LIKE '%US%' GROUP BY AutonomousVehicles.Program;
What is the minimum safety rating of electric vehicles released in 2021?
CREATE TABLE Electric_Vehicles (id INT,name VARCHAR(255),safety_rating DECIMAL(3,2),release_year INT); INSERT INTO Electric_Vehicles (id,name,safety_rating,release_year) VALUES (1,'e-Tron',5.5,2021); INSERT INTO Electric_Vehicles (id,name,safety_rating,release_year) VALUES (2,'Bolt',5.1,2021);
SELECT MIN(safety_rating) FROM Electric_Vehicles WHERE release_year = 2021 AND name IN ('e-Tron', 'Bolt');
How many safety incidents were recorded for vessels in the past month, grouped by the severity of the incident?
CREATE TABLE Safety_Records(Vessel_ID INT,Incident_Date DATE,Incident_Severity VARCHAR(50)); INSERT INTO Safety_Records VALUES (1,'2022-03-12','Minor'),(2,'2022-03-15','Major'),(3,'2022-03-20','Minor'),(1,'2022-03-25','Serious');
SELECT Incident_Severity, COUNT(*) FROM Safety_Records WHERE Incident_Date >= DATEADD(MONTH, -1, GETDATE()) GROUP BY Incident_Severity;
How many vessels arrived in Algiers in the past 60 days?
CREATE TABLE VesselArrivals (ID INT,VesselName VARCHAR(50),ArrivalPort VARCHAR(50),ArrivalDate DATE); INSERT INTO VesselArrivals (ID,VesselName,ArrivalPort,ArrivalDate) VALUES (1,'Test Vessel 1','Algiers','2022-01-01'),(2,'Test Vessel 2','Algiers','2022-01-02'),(3,'Test Vessel 3','Algiers','2022-01-03'),(4,'Test Vessel 4','Algiers','2022-02-04'),(5,'Test Vessel 5','Algiers','2022-02-05');
SELECT COUNT(*) FROM VesselArrivals WHERE ArrivalPort = 'Algiers' AND ArrivalDate >= DATEADD(day, -60, GETDATE());
Determine the number of circular economy initiatives in the Americas that are more than 5 years old.
CREATE TABLE CircularEconomyAmericas (id INT,country VARCHAR(50),region VARCHAR(50),initiative_age INT); INSERT INTO CircularEconomyAmericas (id,country,region,initiative_age) VALUES (1,'USA','Americas',7),(2,'Canada','Americas',3),(3,'Brazil','Americas',6);
SELECT COUNT(*) FROM CircularEconomyAmericas WHERE initiative_age > 5 AND region = 'Americas';
What is the total water consumption by each industrial sector in 2021, if the consumption data is not available?
CREATE TABLE industrial_sectors (id INT,sector VARCHAR(255)); INSERT INTO industrial_sectors (id,sector) VALUES (1,'Manufacturing'),(2,'Mining'),(3,'Construction'); CREATE TABLE water_consumption (year INT,sector_id INT,consumption INT); INSERT INTO water_consumption (year,sector_id,consumption) VALUES (2020,1,10000),(2020,2,15000),(2020,3,12000);
SELECT i.sector, 0 as total_consumption FROM industrial_sectors i LEFT JOIN water_consumption w ON i.id = w.sector_id AND w.year = 2021 GROUP BY i.sector;
What is the total water usage by all agricultural customers in the Sacramento region?
CREATE TABLE agricultural_customers (customer_id INT,region VARCHAR(20),water_usage FLOAT); INSERT INTO agricultural_customers (customer_id,region,water_usage) VALUES (1,'Sacramento',5000),(2,'San_Diego',4000),(3,'Sacramento',7000); CREATE TABLE regions (region VARCHAR(20),PRIMARY KEY (region)); INSERT INTO regions (region) VALUES ('Sacramento'),('San_Diego');
SELECT SUM(water_usage) FROM agricultural_customers WHERE region = ('Sacramento');
Calculate the percentage of workout sessions that were Yoga for each member.
CREATE TABLE member_workout_duration (member_id INT,activity VARCHAR(50),duration INT); INSERT INTO member_workout_duration (member_id,activity,duration) VALUES (1,'Running',60); INSERT INTO member_workout_duration (member_id,activity,duration) VALUES (1,'Cycling',45); INSERT INTO member_workout_duration (member_id,activity,duration) VALUES (2,'Yoga',90); INSERT INTO member_workout_duration (member_id,activity,duration) VALUES (2,'Running',30);
SELECT member_id, (SUM(CASE WHEN activity = 'Yoga' THEN duration ELSE 0 END) / SUM(duration)) * 100 as yoga_percentage FROM member_workout_duration GROUP BY member_id;
List the top 2 AI algorithms with the highest explainability scores, by algorithm subtype, ordered by scores in descending order for the European region.
CREATE TABLE ai_algorithms (algorithm_id INT,algorithm_name VARCHAR(50),algorithm_subtype VARCHAR(50),region VARCHAR(50),explainability_score FLOAT); INSERT INTO ai_algorithms (algorithm_id,algorithm_name,algorithm_subtype,region,explainability_score) VALUES (1,'AlgoA','Tree-based','Europe',0.85),(2,'AlgoB','Computer Vision','Europe',0.92),(3,'AlgoC','Tree-based','Europe',0.78),(4,'AlgoD','Transformer','Europe',0.90),(5,'AlgoE','Tree-based','Europe',0.80);
SELECT algorithm_subtype, region, * FROM (SELECT algorithm_subtype, region, algorithm_id, algorithm_name, explainability_score, RANK() OVER (PARTITION BY algorithm_subtype ORDER BY explainability_score DESC) AS rank FROM ai_algorithms WHERE region = 'Europe') ranked WHERE rank <= 2 ORDER BY algorithm_subtype, region, explainability_score DESC;
What is the average amount of grants given to young farmers in Nigeria?
CREATE TABLE agricultural_innovation_projects (id INT,country VARCHAR(20),grant_amount DECIMAL(10,2),age_group VARCHAR(10)); INSERT INTO agricultural_innovation_projects (id,country,grant_amount,age_group) VALUES (1,'Nigeria',3000.00,'Young'),(2,'Nigeria',4000.00,'Experienced');
SELECT AVG(grant_amount) FROM agricultural_innovation_projects WHERE country = 'Nigeria' AND age_group = 'Young';
What is the average amount of loans issued per community development initiative in Africa?
CREATE TABLE CommunityDevelopment (ProjectID INT,ProjectName VARCHAR(50),Location VARCHAR(50),AmountOfLoans FLOAT); INSERT INTO CommunityDevelopment (ProjectID,ProjectName,Location,AmountOfLoans) VALUES (1,'Clean Water Project','Nigeria',50000.00),(2,'Renewable Energy Initiative','Kenya',75000.00);
SELECT AVG(AmountOfLoans) FROM (SELECT AmountOfLoans FROM CommunityDevelopment WHERE Location IN ('Nigeria', 'Kenya') ORDER BY AmountOfLoans) WHERE ROW_NUMBER() OVER (ORDER BY AmountOfLoans) % 2 = 1;
Which astronauts have spent the most time in space?
CREATE TABLE Astronaut(id INT,name VARCHAR(50),total_time_in_space INT); INSERT INTO Astronaut(id,name,total_time_in_space) VALUES (1,'Peggy Whitson',665),(2,'Scott Kelly',520),(3,'Gennady Padalka',879),(4,'Mike Fincke',382);
SELECT name, total_time_in_space FROM Astronaut ORDER BY total_time_in_space DESC LIMIT 2;
What is the total number of animals in each location?
CREATE TABLE animal_population (id INT,species VARCHAR(50),population INT,location VARCHAR(50));INSERT INTO animal_population (id,species,population,location) VALUES (1,'Tiger',250,'Asia'),(2,'Elephant',500,'Africa'),(3,'Giraffe',300,'Africa');CREATE TABLE habitat_preservation (id INT,animal_id INT,location VARCHAR(50),acres FLOAT);INSERT INTO habitat_preservation (id,animal_id,location,acres) VALUES (1,1,'Asia',10000),(2,2,'Africa',15000),(3,3,'Africa',5000);
SELECT h.location, SUM(ap.population) FROM animal_population ap JOIN habitat_preservation h ON ap.location = h.location GROUP BY h.location;
List all shrimp farms in Africa with water temperatures between 20 and 25 degrees Celsius.
CREATE TABLE Shrimp_Farms (id INT,region VARCHAR(255),temperature DECIMAL(5,2)); INSERT INTO Shrimp_Farms (id,region,temperature) VALUES (1,'Africa',22.5),(2,'Africa',19.8),(3,'Europe',26.1),(4,'Africa',24.2);
SELECT Shrimp_Farms.id FROM Shrimp_Farms WHERE Shrimp_Farms.region = 'Africa' AND Shrimp_Farms.temperature BETWEEN 20 AND 25;
Calculate the average number of construction labor hours worked per day for the month of February 2022
CREATE TABLE construction_labor (worker_id INT,hours_worked INT,work_date DATE);
SELECT AVG(hours_worked / 8) FROM construction_labor WHERE EXTRACT(MONTH FROM work_date) = 2
What is the total number of sustainable building projects in Texas in Q2 2022?
CREATE TABLE Projects (project_id INT,state VARCHAR(255),is_sustainable BOOLEAN,start_date DATE); INSERT INTO Projects (project_id,state,is_sustainable,start_date) VALUES (1,'Texas',true,'2022-04-01'),(2,'Texas',true,'2022-05-01');
SELECT COUNT(project_id) FROM Projects WHERE state = 'Texas' AND is_sustainable = true AND QUARTER(start_date) = 2 AND YEAR(start_date) = 2022 GROUP BY state;
What are the total sales and average product price for each product category in Michigan for the year 2021?
CREATE TABLE products (id INT,name TEXT,category TEXT); INSERT INTO products (id,name,category) VALUES (1,'Product X','Category A'); INSERT INTO products (id,name,category) VALUES (2,'Product Y','Category B'); CREATE TABLE sales (product_id INT,year INT,sales INT,price INT); INSERT INTO sales (product_id,year,sales,price) VALUES (1,2021,100,50); INSERT INTO sales (product_id,year,sales,price) VALUES (2,2021,150,75);
SELECT p.category, SUM(s.sales) as total_sales, AVG(s.price) as average_price FROM products p INNER JOIN sales s ON p.id = s.product_id WHERE p.name = 'Michigan' AND s.year = 2021 GROUP BY p.category;
What is the total billing amount for each attorney, broken down by outcome?
CREATE TABLE Attorneys (AttorneyID int,Name varchar(50)); INSERT INTO Attorneys VALUES (1,'Smith'),(2,'Johnson'); CREATE TABLE Billing (BillingID int,CaseID int,Amount decimal(10,2)); INSERT INTO Billing VALUES (1,1,5000.00),(2,1,7000.00),(3,2,3000.00),(4,3,4000.00); CREATE TABLE Cases (CaseID int,AttorneyID int,Outcome varchar(10)); INSERT INTO Cases VALUES (1,1,'Won'),(2,1,'Lost'),(3,2,'Won');
SELECT A.Name, C.Outcome, SUM(B.Amount) as TotalBilling FROM Attorneys A INNER JOIN Billing B ON A.AttorneyID = B.CaseID INNER JOIN Cases C ON B.CaseID = C.CaseID GROUP BY A.Name, C.Outcome;
What is the total CO2 emission per vehicle per day?
create table VehicleEmission (Vehicle varchar(255),CO2 int,Timestamp datetime); insert into VehicleEmission values ('Vehicle1',50,'2022-01-01 00:00:00'),('Vehicle2',70,'2022-01-01 00:00:00'),('Vehicle1',60,'2022-01-02 00:00:00');
select Vehicle, DATE(Timestamp) as Date, SUM(CO2) as TotalCO2 from VehicleEmission group by Vehicle, Date;
Find the number of climate communication campaigns launched in the Pacific Islands every year since 2015, and order them by year.
CREATE TABLE climate_communication (campaign VARCHAR(50),year INT,region VARCHAR(50)); INSERT INTO climate_communication (campaign,year,region) VALUES ('Ocean Conservation',2016,'Pacific Islands'),('Climate Awareness',2017,'Pacific Islands');
SELECT year, COUNT(*) as campaigns_per_year FROM climate_communication WHERE region = 'Pacific Islands' AND year >= 2015 GROUP BY year ORDER BY year;
What is the average CO2 emission for the top 3 highest emitting countries since 2015?
CREATE TABLE emissions (country VARCHAR(50),year INT,co2_emission INT); INSERT INTO emissions (country,year,co2_emission) VALUES ('USA',2015,5373978000); INSERT INTO emissions (country,year,co2_emission) VALUES ('China',2015,10498600000); INSERT INTO emissions (country,year,co2_emission) VALUES ('India',2015,2633830000); INSERT INTO emissions (country,year,co2_emission) VALUES ('USA',2016,5518004000); INSERT INTO emissions (country,year,co2_emission) VALUES ('China',2016,10813000000); INSERT INTO emissions (country,year,co2_emission) VALUES ('India',2016,2799280000);
SELECT AVG(co2_emission) as avg_emission FROM (SELECT country, year, co2_emission, ROW_NUMBER() OVER (ORDER BY co2_emission DESC) as rn FROM emissions WHERE year >= 2015) t WHERE rn <= 3 GROUP BY country;
What is the mortality rate for heart disease in Mexico?
CREATE TABLE Mortality (ID INT,Country VARCHAR(100),CauseOfDeath VARCHAR(50),MortalityRate FLOAT); INSERT INTO Mortality (ID,Country,CauseOfDeath,MortalityRate) VALUES (1,'Mexico','Heart Disease',150);
SELECT MortalityRate FROM Mortality WHERE Country = 'Mexico' AND CauseOfDeath = 'Heart Disease';
What is the total number of hospital beds in each country in the Asia continent?
CREATE TABLE Countries (Country VARCHAR(50),Continent VARCHAR(50),Hospital_Beds INT); INSERT INTO Countries (Country,Continent,Hospital_Beds) VALUES ('India','Asia',500000),('China','Asia',700000),('Japan','Asia',300000);
SELECT Country, SUM(Hospital_Beds) FROM Countries WHERE Continent = 'Asia' GROUP BY Country WITH ROLLUP;
List the number of diversity metrics reported for each gender in 'California'?
CREATE TABLE diversity_metrics (id INT PRIMARY KEY,company_id INT,gender TEXT,minority TEXT,year INT,location TEXT); CREATE VIEW diversity_metrics_summary AS SELECT gender,location,COUNT(*) as count FROM diversity_metrics GROUP BY gender,location;
SELECT s.gender, s.location, s.count FROM diversity_metrics_summary s JOIN company_founding c ON c.location = s.location WHERE s.location = 'California';
What is the average funding amount for companies founded by women in the Consumer Electronics industry?
CREATE TABLE Companies (id INT,name VARCHAR(50),industry VARCHAR(50),country VARCHAR(50),founding_year INT,founder_gender VARCHAR(10)); INSERT INTO Companies (id,name,industry,country,founding_year,founder_gender) VALUES (1,'EarGear','Consumer Electronics','Canada',2017,'Female'); INSERT INTO Companies (id,name,industry,country,founding_year,founder_gender) VALUES (2,'SmartEyewear','Consumer Electronics','UK',2018,'Male');
SELECT AVG(funding_amount) as avg_funding FROM (SELECT funding_amount FROM Funding WHERE company_name IN (SELECT name FROM Companies WHERE industry = 'Consumer Electronics' AND founder_gender = 'Female')) as subquery;
How many regulatory violations have been committed by Coinbase and Huobi combined?
CREATE TABLE regulatory_violations (platform VARCHAR(255),violation_count INT); INSERT INTO regulatory_violations (platform,violation_count) VALUES ('Coinbase',10); INSERT INTO regulatory_violations (platform,violation_count) VALUES ('Huobi',15);
SELECT SUM(violation_count) FROM regulatory_violations WHERE platform IN ('Coinbase', 'Huobi');
Identify the top 3 tree species in terms of carbon sequestration in tropical dry forests
CREATE TABLE forests_carbon_seq (id INT,type VARCHAR(20),species VARCHAR(20),carbon FLOAT); INSERT INTO forests_carbon_seq (id,type,species,carbon) VALUES (1,'Tropical Dry','Oak',150000),(2,'Tropical Dry','Pine',180000);
SELECT species, SUM(carbon) AS total_carbon FROM forests_carbon_seq WHERE type = 'Tropical Dry' GROUP BY species ORDER BY total_carbon DESC LIMIT 3;
What is the average timber volume per record, partitioned by year?
CREATE TABLE forests (id INT,region VARCHAR(255),volume FLOAT,year INT); INSERT INTO forests (id,region,volume,year) VALUES (1,'North',1200,2019),(2,'South',1500,2019),(3,'East',1800,2019),(4,'West',1000,2019),(5,'North',1300,2020),(6,'South',1600,2020),(7,'East',1900,2020),(8,'West',1100,2020);
SELECT year, AVG(volume) as avg_volume FROM forests GROUP BY year;
List all natural nail polishes sold in Germany with a price below 10 euros.
CREATE TABLE nail_polishes(product_name TEXT,price DECIMAL(5,2),natural BOOLEAN,sale_country TEXT); INSERT INTO nail_polishes(product_name,price,natural,sale_country) VALUES ('Nude Polish',8.99,true,'Germany');
SELECT product_name FROM nail_polishes WHERE price < 10 AND natural = true AND sale_country = 'Germany';
Which cosmetic brands have the highest average customer rating?
CREATE TABLE brand (id INT,name VARCHAR(255),avg_rating FLOAT); CREATE TABLE rating (brand_id INT,rating FLOAT); INSERT INTO brand (id,name,avg_rating) VALUES (1,'Lush',4.2),(2,'The Body Shop',4.1),(3,'Sephora',4.3); INSERT INTO rating (brand_id,rating) VALUES (1,4.5),(1,4.0),(2,4.1),(2,4.2),(3,4.4),(3,4.3);
SELECT b.name, AVG(r.rating) as avg_rating FROM brand b JOIN rating r ON b.id = r.brand_id GROUP BY b.name ORDER BY avg_rating DESC;
How many crime incidents were reported in each borough of New York City in the year 2020?
CREATE TABLE crime_incidents (id INT,incident_type VARCHAR(255),borough VARCHAR(255),report_date DATE); INSERT INTO crime_incidents (id,incident_type,borough,report_date) VALUES (1,'Theft','Manhattan','2020-01-01'),(2,'Assault','Brooklyn','2020-01-02');
SELECT borough, YEAR(report_date) AS year, COUNT(*) AS incident_count FROM crime_incidents GROUP BY borough, year;
What is the number of days each community policing program was active?
CREATE TABLE community_policing (id INT PRIMARY KEY,program_name VARCHAR(50),start_date DATE,end_date DATE);
SELECT program_name, DATEDIFF(end_date, start_date) as days_active FROM community_policing;
What is the total value of defense contracts signed by company 'XYZ Inc.'?
CREATE TABLE defense_contracts (value NUMERIC,company VARCHAR(255)); INSERT INTO defense_contracts (value,company) VALUES (1000000,'ABC Inc.'),(2000000,'XYZ Inc.');
SELECT SUM(value) FROM defense_contracts WHERE company = 'XYZ Inc.';
What is the average number of military innovation projects by type (e.g., AI, cybersecurity, drones) in each region, ordered from highest to lowest?
CREATE TABLE military_innovation_3 (id INT,region VARCHAR(255),project_type VARCHAR(255)); INSERT INTO military_innovation_3 (id,region,project_type) VALUES (1,'North America','AI'),(2,'Europe','Cybersecurity'),(3,'Asia','Drones'),(4,'North America','Cybersecurity'),(5,'Europe','AI'),(6,'Asia','Quantum Computing'),(7,'North America','Drones'),(8,'Europe','Quantum Computing'),(9,'Asia','AI'),(10,'North America','Quantum Computing');
SELECT region, AVG(project_type) AS avg_projects FROM military_innovation_3 GROUP BY region ORDER BY avg_projects DESC;