instruction
stringlengths 0
1.06k
| input
stringlengths 11
5.3k
| response
stringlengths 2
4.44k
|
---|---|---|
Calculate the percentage of financially capable individuals in each region and display the region and percentage.
|
CREATE TABLE individuals (individual_id INT,region VARCHAR(50),financial_capability_score DECIMAL(5,2)); INSERT INTO individuals (individual_id,region,financial_capability_score) VALUES (1,'North',75.50),(2,'South',80.25),(3,'East',68.75),(4,'West',90.00),(5,'North',72.25),(6,'South',85.00),(7,'East',65.00),(8,'West',92.50);
|
SELECT region, AVG(financial_capability_score) AS avg_score, AVG(financial_capability_score) OVER (PARTITION BY region) * 100.0 AS percentage FROM individuals;
|
Update the initiative_name for the record with an id of 3 in the 'community_development' table to 'microfinance_program'.
|
CREATE TABLE community_development (id INT,initiative_name VARCHAR(255),budget INT);
|
UPDATE community_development SET initiative_name = 'microfinance_program' WHERE id = 3;
|
What was the capacity of all landfills in the city of Los Angeles in the year 2017?
|
CREATE TABLE LandfillCapacity (ID INT PRIMARY KEY,Landfill VARCHAR(50),City VARCHAR(50),Year INT,Capacity INT); INSERT INTO LandfillCapacity (ID,Landfill,City,Year,Capacity) VALUES (1,'North Disposal Site','Los Angeles',2017,1000000),(2,'South Disposal Site','Los Angeles',2017,1500000);
|
SELECT Landfill, Capacity FROM LandfillCapacity WHERE City = 'Los Angeles' AND Year = 2017;
|
Insert a new customer 'Alex Thompson' with customer ID 3.
|
CREATE TABLE customers (customer_id INT,name TEXT); INSERT INTO customers (customer_id,name) VALUES (1,'John Doe'); INSERT INTO customers (customer_id,name) VALUES (2,'Jane Smith');
|
INSERT INTO customers (customer_id, name) VALUES (3, 'Alex Thompson');
|
What is the percentage of fair trade certified factories in each country?
|
CREATE TABLE FairTradeCertified (id INT,country VARCHAR,certified BOOLEAN);
|
SELECT country, 100.0 * AVG(CAST(certified AS FLOAT)) as percentage_certified FROM FairTradeCertified GROUP BY country;
|
What was the total sales for each drug in 2021?
|
CREATE TABLE sales (sale_id INT,drug_id INT,region VARCHAR(255),sales_amount DECIMAL(10,2),quarter INT,year INT);
|
SELECT d.drug_name, SUM(s.sales_amount) as total_sales FROM sales s JOIN drugs d ON s.drug_id = d.drug_id WHERE s.year = 2021 GROUP BY d.drug_name;
|
List mobile subscribers who joined after the latest broadband subscribers.
|
CREATE TABLE subscribers(id INT,technology VARCHAR(20),type VARCHAR(10),joined DATE); INSERT INTO subscribers(id,technology,type,joined) VALUES (1,'4G','mobile','2021-01-01'),(2,'5G','mobile','2022-01-01'),(3,'ADSL','broadband','2022-02-01'),(4,'FTTH','broadband','2022-03-01');
|
SELECT * FROM subscribers WHERE technology = 'mobile' AND joined > (SELECT MAX(joined) FROM subscribers WHERE type = 'broadband');
|
What is the maximum speed of vessels that have a classification society of 'ABS'?
|
CREATE TABLE Vessel_Specs (ID INT,Vessel_Name VARCHAR(50),Classification_Society VARCHAR(10),Max_Speed DECIMAL(5,2)); INSERT INTO Vessel_Specs (ID,Vessel_Name,Classification_Society,Max_Speed) VALUES (1,'Vessel1','ABS',25.6); INSERT INTO Vessel_Specs (ID,Vessel_Name,Classification_Society,Max_Speed) VALUES (2,'Vessel2','DNV',28.3); INSERT INTO Vessel_Specs (ID,Vessel_Name,Classification_Society,Max_Speed) VALUES (3,'Vessel3','ABS',29.1);
|
SELECT MAX(Max_Speed) FROM Vessel_Specs WHERE Classification_Society = 'ABS';
|
Calculate the average cost of agricultural innovation projects per country and rank them in ascending order.
|
CREATE TABLE agricultural_innovation_projects (id INT,project_name VARCHAR(255),location VARCHAR(255),sector VARCHAR(255),cost FLOAT); INSERT INTO agricultural_innovation_projects (id,project_name,location,sector,cost) VALUES (1,'Precision Agriculture','Country 1','Agriculture',35000.00),(2,'Drip Irrigation','Country 2','Agriculture',28000.00),(3,'Solar Powered Cold Storage','Country 3','Agriculture',52000.00);
|
SELECT location, AVG(cost) AS avg_cost, RANK() OVER (ORDER BY AVG(cost)) AS location_rank FROM agricultural_innovation_projects GROUP BY location ORDER BY avg_cost ASC;
|
Display the number of unique donors and total donation amounts for each cause, joining the donors, donations, and causes tables.
|
CREATE TABLE causes (id INT,name VARCHAR(255)); INSERT INTO causes (id,name) VALUES (1,'Climate Change'),(2,'Human Rights'),(3,'Poverty Reduction'); CREATE TABLE donors (id INT,name VARCHAR(255)); INSERT INTO donors (id,name) VALUES (1,'Laura Gonzalez'),(2,'Jose Luis Rodriguez'),(3,'Maria Garcia'),(4,'Carlos Hernandez'); CREATE TABLE donations (id INT,donor_id INT,cause_id INT,amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,cause_id,amount) VALUES (1,1,1,500),(2,1,2,250),(3,2,2,750),(4,3,3,1000),(5,4,1,500),(6,4,3,250);
|
SELECT c.name, COUNT(DISTINCT d.donor_id) as donor_count, SUM(donations.amount) as total_donation FROM causes c JOIN donations ON c.id = donations.cause_id JOIN donors ON donations.donor_id = donors.id GROUP BY c.name;
|
What is the number of cases handled by legal aid organizations in each city?
|
CREATE TABLE legal_aid_organizations (org_id INT,org_name TEXT,city TEXT,cases_handled INT); INSERT INTO legal_aid_organizations VALUES (1,'LegalAid1','San Francisco',250),(2,'LegalAid2','Dallas',300),(3,'LegalAid3','New York',200);
|
SELECT city, SUM(cases_handled) FROM legal_aid_organizations GROUP BY city;
|
What is the total number of inclusive housing policies in the state of California?
|
CREATE TABLE inclusive_housing (id INT,state VARCHAR,policy_count INT); INSERT INTO inclusive_housing (id,state,policy_count) VALUES (1,'California',50),(2,'New York',40),(3,'Texas',30),(4,'Florida',20);
|
SELECT SUM(policy_count) FROM inclusive_housing WHERE state = 'California';
|
How many visitors attended exhibitions in each city in the last month?
|
CREATE TABLE Exhibitions (id INT,city VARCHAR(20),exhibition_date DATE,visitor_count INT);
|
SELECT city, SUM(visitor_count) FROM Exhibitions WHERE exhibition_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY city;
|
What is the production tonnage for the 'Katanga' mine?
|
CREATE TABLE Mining_Operations(Mine_Name TEXT,Production_Tonnes INT,Location TEXT); INSERT INTO Mining_Operations(Mine_Name,Production_Tonnes,Location) VALUES('Katanga',500000,'DRC');
|
SELECT Production_Tonnes FROM Mining_Operations WHERE Mine_Name = 'Katanga';
|
What is the total quantity of vegan eyeshadows sold by region?
|
CREATE TABLE regions (region_id INT,region_name VARCHAR(255)); INSERT INTO regions (region_id,region_name) VALUES (1,'Northeast'),(2,'Southeast'),(3,'Midwest'),(4,'Southwest'),(5,'West'); CREATE TABLE products (product_id INT,product_name VARCHAR(255),is_vegan BOOLEAN,quantity_sold INT,region_id INT);
|
SELECT r.region_name, SUM(p.quantity_sold) as total_quantity_sold FROM regions r INNER JOIN products p ON r.region_id = p.region_id WHERE p.is_vegan = TRUE GROUP BY r.region_name;
|
List all astronauts who have a medical condition and the missions they have participated in.
|
CREATE TABLE astronauts (astronaut_id INT,name TEXT,age INT,medical_condition TEXT); INSERT INTO astronauts (astronaut_id,name,age,medical_condition) VALUES (1,'Alexei Leonov',85,'Asthma'),(2,'Buzz Aldrin',92,NULL),(3,'Neil Armstrong',82,NULL),(4,'Valentina Tereshkova',83,'Claustrophobia'); CREATE TABLE astronaut_missions (astronaut_id INT,mission_id INT); INSERT INTO astronaut_missions (astronaut_id,mission_id) VALUES (1,1),(1,2),(2,1),(3,1),(4,2); CREATE TABLE space_missions (mission_id INT,name TEXT); INSERT INTO space_missions (mission_id,name) VALUES (1,'Apollo 11'),(2,'Soyuz 1'),(3,'Gemini 1'),(4,'Vostok 1');
|
SELECT a.name AS astronaut_name, s.name AS mission_name FROM astronauts a JOIN astronaut_missions am ON a.astronaut_id = am.astronaut_id JOIN space_missions s ON am.mission_id = s.mission_id WHERE a.medical_condition IS NOT NULL;
|
Determine the number of community engagement events held in North America from 2010 to 2020, and calculate the percentage change in the number of events from 2010 to 2020.
|
CREATE TABLE north_america_community_events (id INT,event_name TEXT,year INT,num_attendees INT); INSERT INTO north_america_community_events (id,event_name,year,num_attendees) VALUES (1,'Dance festival',2010,500),(2,'Art exhibition',2011,400),(3,'Music festival',2012,300),(4,'Language preservation workshop',2013,200),(5,'Cultural heritage tour',2014,150),(6,'Community art project',2015,100),(7,'Film festival',2016,75),(8,'Theater performance',2017,50),(9,'Literature reading',2018,30),(10,'Education workshop',2019,20),(11,'Youth engagement event',2020,15);
|
SELECT (COUNT(*) - (SELECT COUNT(*) FROM north_america_community_events WHERE year = 2010)) * 100.0 / (SELECT COUNT(*) FROM north_america_community_events WHERE year = 2010) as pct_change FROM north_america_community_events WHERE year = 2020;
|
Find the number of customers who have made a transaction over 10000 in the last 3 months for each month.
|
CREATE TABLE customers (id INT,name VARCHAR(50),age INT); CREATE TABLE transactions (id INT,customer_id INT,transaction_amount DECIMAL(10,2),transaction_date DATE); INSERT INTO transactions (id,customer_id,transaction_amount,transaction_date) VALUES (1,1,12000.00,'2022-01-01'),(2,1,8000.00,'2022-02-01');
|
SELECT EXTRACT(MONTH FROM transaction_date) as month, COUNT(DISTINCT customer_id) as num_customers FROM transactions WHERE transaction_amount > 10000 AND transaction_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY month;
|
Find mining equipment that is older than 15 years and has a maintenance record
|
CREATE TABLE maintenance_records (equipment_id INT,maintenance_date DATE);
|
SELECT * FROM Mining_Equipment WHERE purchase_date < DATE_SUB(CURRENT_DATE, INTERVAL 15 YEAR) AND equipment_id IN (SELECT equipment_id FROM maintenance_records);
|
Delete all content in the 'Blog' content type
|
CREATE TABLE Content (ContentID int,ContentType varchar(50),LanguageID int); INSERT INTO Content (ContentID,ContentType,LanguageID) VALUES (1,'Movie',1),(2,'Podcast',2),(3,'Blog',3);
|
DELETE FROM Content WHERE ContentType = 'Blog';
|
Update the ocean_name for species_id 1 to 'Indian Ocean'.
|
CREATE TABLE marine_species (species_id INT,species_name VARCHAR(50),ocean_name VARCHAR(50));
|
UPDATE marine_species SET ocean_name = 'Indian Ocean' WHERE species_id = 1;
|
What is the percentage of electric vehicles sold in each region?
|
CREATE TABLE VehicleSales (Region VARCHAR(50),VehicleType VARCHAR(50),Sales INT); INSERT INTO VehicleSales (Region,VehicleType,Sales) VALUES ('North America','Electric',50000),('North America','Gasoline',100000),('Europe','Electric',75000),('Europe','Gasoline',125000),('Asia','Electric',100000),('Asia','Gasoline',50000);
|
SELECT Region, (SUM(CASE WHEN VehicleType = 'Electric' THEN Sales ELSE 0 END) / SUM(Sales)) * 100 as Percentage FROM VehicleSales GROUP BY Region;
|
How many financial capability training sessions were held in each month of 2022?
|
CREATE TABLE financial_capability_months (session_id INT,month INT,year INT); INSERT INTO financial_capability_months (session_id,month,year) VALUES (1,1,2022),(2,2,2022),(3,3,2022),(4,4,2022),(5,5,2022),(6,6,2022);
|
SELECT CONCAT(month, '/', year) AS month_year, COUNT(*) FROM financial_capability_months GROUP BY month_year;
|
What is the average number of hours played per day for VR games?
|
CREATE TABLE vr_game_data (id INT,player_id INT,game VARCHAR(20),playtime_hours INT); INSERT INTO vr_game_data (id,player_id,game,playtime_hours) VALUES (1,1,'VR Game1',2),(2,2,'VR Game2',3),(3,1,'VR Game1',4);
|
SELECT AVG(playtime_hours / 24) FROM vr_game_data WHERE game LIKE 'VR%';
|
Update the 'capacity_mw' value to 40 in the 'renewable_energy' table where the 'source' is 'Wind'
|
CREATE TABLE renewable_energy (id INT PRIMARY KEY,source VARCHAR(255),capacity_mw FLOAT,country VARCHAR(255));
|
UPDATE renewable_energy SET capacity_mw = 40 WHERE source = 'Wind';
|
List all autonomous vehicle (AV) types and their average prices
|
CREATE TABLE av_types (av_id INT,av_type VARCHAR(50));CREATE TABLE av_prices (price_id INT,av_id INT,price DECIMAL(5,2));INSERT INTO av_types (av_id,av_type) VALUES (1,'Wayve'),(2,'NVIDIA'),(3,'Zoox');INSERT INTO av_prices (price_id,av_id,price) VALUES (1,1,300000),(2,2,400000),(3,3,500000);
|
SELECT av.av_type, AVG(ap.price) as avg_price FROM av_types av JOIN av_prices ap ON av.av_id = ap.av_id GROUP BY av.av_type;
|
Find the total number of hotels in each city and the number of bookings for those hotels
|
CREATE TABLE hotels (hotel_id INT,hotel_name VARCHAR(50),city VARCHAR(50)); CREATE TABLE bookings (booking_id INT,hotel_id INT,guest_name VARCHAR(50),checkin_date DATE,checkout_date DATE,price DECIMAL(10,2));
|
SELECT h.city, COUNT(DISTINCT h.hotel_id) AS hotel_count, SUM(b.booking_id) AS booking_count FROM hotels h LEFT JOIN bookings b ON h.hotel_id = b.hotel_id GROUP BY h.city;
|
Which vessels are near the coast of Argentina?
|
CREATE TABLE vessels(id INT,name TEXT,longitude FLOAT,latitude FLOAT); INSERT INTO vessels VALUES (1,'VesselA',-58.5034,-34.6037),(7,'VesselG',-65.0178,-37.8140);
|
SELECT DISTINCT name FROM vessels WHERE longitude BETWEEN -74.0356 AND -54.8258 AND latitude BETWEEN -55.0216 AND -33.4294;
|
Calculate the average CO2 emission for silver mines with more than 1200 units extracted in 2018.
|
CREATE TABLE environmental_impact (id INT PRIMARY KEY,mine_site_id INT,pollution_level INT,CO2_emission INT,FOREIGN KEY (mine_site_id) REFERENCES mine_sites(id)); CREATE TABLE minerals_extracted (id INT PRIMARY KEY,mine_site_id INT,mineral VARCHAR(255),quantity INT,extraction_year INT,FOREIGN KEY (mine_site_id) REFERENCES mine_sites(id));
|
SELECT AVG(e.CO2_emission) as avg_co2 FROM environmental_impact e JOIN minerals_extracted m ON e.mine_site_id = m.mine_site_id WHERE m.mineral = 'silver' AND m.quantity > 1200 AND m.extraction_year = 2018;
|
What is the total spending on military innovation by different countries in Q2 2022?
|
CREATE TABLE military_innovation (country VARCHAR(255),amount NUMERIC,quarter INT,year INT); INSERT INTO military_innovation (country,amount,quarter,year) VALUES ('USA',1200000,2,2022),('China',900000,2,2022),('Russia',700000,2,2022);
|
SELECT country, SUM(amount) FROM military_innovation WHERE quarter = 2 AND year = 2022 GROUP BY country;
|
How many military innovation projects were initiated by each organization in the 'military_innovation' table, with a budget greater than $10 million?
|
CREATE TABLE military_innovation (id INT,organization VARCHAR(50),budget INT);
|
SELECT organization, COUNT(*) as num_projects FROM military_innovation WHERE budget > 10000000 GROUP BY organization;
|
What is the maximum ticket price for music concerts in the Americas in Q2 2021?
|
CREATE TABLE TicketPrices (id INT,region VARCHAR(20),quarter INT,year INT,category VARCHAR(20),price FLOAT); INSERT INTO TicketPrices (id,region,quarter,year,category,price) VALUES (7,'Americas',2,2021,'Music',150); INSERT INTO TicketPrices (id,region,quarter,year,category,price) VALUES (8,'Americas',2,2021,'Theater',200);
|
SELECT MAX(price) FROM TicketPrices WHERE region = 'Americas' AND quarter = 2 AND year = 2021 AND category = 'Music';
|
Which tunnels cost more than any bridge in California?
|
CREATE TABLE Bridges (name TEXT,cost FLOAT,location TEXT);
|
CREATE TABLE Tunnels (name TEXT, cost FLOAT, location TEXT);
|
What is the success rate of the 'Suicide Prevention Campaign'?
|
CREATE TABLE campaigns (campaign_name VARCHAR(30),reach INT,conversions INT); INSERT INTO campaigns (campaign_name,reach,conversions) VALUES ('Mental Health Awareness Campaign',10000,1500); INSERT INTO campaigns (campaign_name,reach,conversions) VALUES ('Suicide Prevention Campaign',8000,1200); INSERT INTO campaigns (campaign_name,reach,conversions) VALUES ('Depression Screening Campaign',6000,800);
|
SELECT (CONVERT(FLOAT, conversions) / reach) * 100.0 FROM campaigns WHERE campaign_name = 'Suicide Prevention Campaign';
|
How many genetic research projects were completed in Africa in 2018?
|
CREATE TABLE genetic_research (id INT,project_name VARCHAR(50),completion_year INT,region VARCHAR(50)); INSERT INTO genetic_research (id,project_name,completion_year,region) VALUES (1,'Genome Mapping',2019,'North America'); INSERT INTO genetic_research (id,project_name,completion_year,region) VALUES (2,'DNA Sequencing',2020,'South America'); INSERT INTO genetic_research (id,project_name,completion_year,region) VALUES (3,'CRISPR Therapy',2018,'Africa');
|
SELECT COUNT(*) FROM genetic_research WHERE completion_year = 2018 AND region = 'Africa';
|
How many mental health campaigns were launched per year, ordered by launch date?
|
CREATE TABLE campaigns (campaign_id INT,launch_date DATE); INSERT INTO campaigns VALUES (1,'2018-05-12'),(2,'2019-02-28'),(3,'2020-11-15'),(4,'2021-07-08');
|
SELECT COUNT(campaign_id) as campaigns_per_year, YEAR(launch_date) as launch_year FROM campaigns GROUP BY launch_year ORDER BY launch_year;
|
How many marine species are there in the Mediterranean Sea with a conservation status of 'Critically Endangered'?
|
CREATE TABLE marine_species (id INT,name TEXT,region TEXT); CREATE TABLE conservation_status (id INT,species_id INT,status TEXT); INSERT INTO marine_species (id,name,region) VALUES (1,'Mediterranean Monk Seal','Mediterranean Sea'); INSERT INTO conservation_status (id,species_id,status) VALUES (1,1,'Critically Endangered'); INSERT INTO marine_species (id,name,region) VALUES (2,'Bluefin Tuna','Mediterranean Sea');
|
SELECT COUNT(marine_species.id) FROM marine_species INNER JOIN conservation_status ON marine_species.id = conservation_status.species_id WHERE marine_species.region = 'Mediterranean Sea' AND conservation_status.status = 'Critically Endangered';
|
What is the total revenue generated from mobile and broadband subscribers for each ISP, and what is the percentage contribution of mobile and broadband revenue to the total revenue?
|
CREATE TABLE isps (id INT,name VARCHAR(255));CREATE TABLE mobile_subscribers (id INT,isp_id INT,monthly_revenue DECIMAL(10,2));CREATE TABLE broadband_subscribers (id INT,isp_id INT,monthly_revenue DECIMAL(10,2));
|
SELECT isp.name, SUM(mobile_subscribers.monthly_revenue) as mobile_revenue, SUM(broadband_subscribers.monthly_revenue) as broadband_revenue, (SUM(mobile_subscribers.monthly_revenue) + SUM(broadband_subscribers.monthly_revenue)) as total_revenue, (SUM(mobile_subscribers.monthly_revenue) / (SUM(mobile_subscribers.monthly_revenue) + SUM(broadband_subscribers.monthly_revenue))) as mobile_contribution, (SUM(broadband_subscribers.monthly_revenue) / (SUM(mobile_subscribers.monthly_revenue) + SUM(broadband_subscribers.monthly_revenue))) as broadband_contribution FROM isps isp INNER JOIN mobile_subscribers ON isp.id = mobile_subscribers.isp_id INNER JOIN broadband_subscribers ON isp.id = broadband_subscribers.isp_id GROUP BY isp.name;
|
What are the suppliers located in 'Paris' with a sustainability rating greater than 85?
|
CREATE TABLE suppliers (id INT,name VARCHAR(255),location VARCHAR(255),sustainability_rating INT); INSERT INTO suppliers (id,name,location,sustainability_rating) VALUES (1,'Supplier A','Paris',86);
|
SELECT name FROM suppliers WHERE location = 'Paris' AND sustainability_rating > 85;
|
What is the total quantity of 'Europium' produced by all countries in 2020 and 2021?
|
CREATE TABLE production (element VARCHAR(10),country VARCHAR(20),quantity INT,year INT); INSERT INTO production (element,country,quantity,year) VALUES ('Europium','China',1200,2020),('Europium','China',1300,2021),('Europium','USA',1100,2020),('Europium','USA',1200,2021);
|
SELECT SUM(quantity) FROM production WHERE element = 'Europium' AND (year = 2020 OR year = 2021);
|
What is the total funding received by startups founded by underrepresented minorities in the biotech industry?
|
CREATE TABLE startup (id INT,name TEXT,industry TEXT,founder_race TEXT); INSERT INTO startup VALUES (1,'StartupA','Biotech','African American'); INSERT INTO startup VALUES (2,'StartupB','Tech','Asian');
|
SELECT SUM(funding_amount) FROM investment_round ir JOIN startup s ON ir.startup_id = s.id WHERE s.industry = 'Biotech' AND s.founder_race = 'African American';
|
Find companies founded by women that have not raised any funds.
|
CREATE TABLE company (id INT,name TEXT,founder_gender TEXT); INSERT INTO company (id,name,founder_gender) VALUES (1,'Acme Inc','Female'),(2,'Beta Corp','Male');
|
SELECT * FROM company WHERE founder_gender = 'Female' AND id NOT IN (SELECT company_id FROM investment)
|
What is the number of employees in each department in the mining industry?
|
CREATE TABLE workforce (id INT,name VARCHAR(50),gender VARCHAR(50),position VARCHAR(50),department VARCHAR(50)); INSERT INTO workforce (id,name,gender,position,department) VALUES (1,'John Doe','Male','Engineer','Mining'),(2,'Jane Smith','Female','Technician','Environment'),(3,'Alice Johnson','Female','Manager','Operations');
|
SELECT department, COUNT(*) as num_employees FROM workforce GROUP BY department;
|
What is the average adoption score for smart cities in the 'smart_cities' table, by country?
|
CREATE TABLE if not exists smart_cities (city_id INT,city_name VARCHAR(255),country VARCHAR(255),adoption_score FLOAT);
|
SELECT country, AVG(adoption_score) as avg_score FROM smart_cities WHERE adoption_score IS NOT NULL GROUP BY country;
|
Calculate the total oil and gas production (in BOE) for each well in the Eagle Ford formation
|
CREATE TABLE if not exists well_production (well_id INT,well_name TEXT,location TEXT,production_year INT,oil_production FLOAT,gas_production FLOAT); INSERT INTO well_production (well_id,well_name,location,production_year,oil_production,gas_production) VALUES (1,'Well L','Eagle Ford',2021,1234.56,987.65),(2,'Well M','Eagle Ford',2021,2345.67,1234.56),(3,'Well N','Bakken',2021,3456.78,1567.89);
|
SELECT well_name, (AVG(oil_production) + (AVG(gas_production) / 6)) AS avg_total_production FROM well_production WHERE location = 'Eagle Ford' GROUP BY well_name;
|
Identify dishes with high food waste and their average waste percentages.
|
CREATE TABLE dishes (dish_name VARCHAR(255),daily_sales INT,daily_waste INT); CREATE TABLE inventory_adjustments (adjustment_type VARCHAR(255),item_name VARCHAR(255),quantity_adjusted INT);
|
SELECT d.dish_name, AVG(d.daily_waste * 100.0 / d.daily_sales) as avg_waste_percentage FROM dishes d INNER JOIN inventory_adjustments ia ON d.dish_name = ia.item_name WHERE ia.adjustment_type = 'food_waste' GROUP BY d.dish_name HAVING COUNT(ia.adjustment_type) > 30 ORDER BY avg_waste_percentage DESC;
|
What is the total number of members from FitnessMembers and OnlineMembers tables?
|
CREATE TABLE FitnessMembers (member_id INT,name VARCHAR(50),age INT,gender VARCHAR(10)); INSERT INTO FitnessMembers (member_id,name,age,gender) VALUES (1,'John Doe',25,'Male'); INSERT INTO FitnessMembers (member_id,name,age,gender) VALUES (2,'Jane Smith',30,'Female'); CREATE TABLE OnlineMembers (member_id INT,name VARCHAR(50),age INT,subscription_date DATE); INSERT INTO OnlineMembers (member_id,name,age,subscription_date) VALUES (3,'Alice Johnson',35,'2021-01-01'); INSERT INTO OnlineMembers (member_id,name,age,subscription_date) VALUES (4,'Bob Brown',40,'2021-02-01');
|
SELECT COUNT(*) FROM FitnessMembers UNION ALL SELECT COUNT(*) FROM OnlineMembers;
|
What is the total number of traditional art pieces by type, region, and continent?
|
CREATE TABLE Art (ArtID INT,Type VARCHAR(255),Region VARCHAR(255),Continent VARCHAR(255),Quantity INT); INSERT INTO Art (ArtID,Type,Region,Continent,Quantity) VALUES (1,'Painting','Asia','Asia',25),(2,'Sculpture','Africa','Africa',18),(3,'Textile','South America','South America',30),(4,'Pottery','Europe','Europe',20),(5,'Jewelry','North America','North America',12);
|
SELECT Type, Region, Continent, SUM(Quantity) as Total_Quantity FROM Art GROUP BY Type, Region, Continent;
|
What is the average water usage per day, per mine, for the past month?
|
CREATE TABLE water_usage (water_usage_id INT,mine_id INT,date DATE,water_used FLOAT); INSERT INTO water_usage (water_usage_id,mine_id,date,water_used) VALUES (1,1,'2021-01-01',5000),(2,1,'2021-01-02',5500),(3,2,'2021-01-01',6000),(4,2,'2021-01-02',6500),(5,3,'2021-01-01',7000),(6,3,'2021-01-02',7500);
|
SELECT mine_id, AVG(water_used) as avg_daily_water_usage FROM water_usage WHERE date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND CURRENT_DATE GROUP BY mine_id;
|
What were the national security budget allocations for the last 2 years?
|
CREATE TABLE national_security_budget (budget_id INT PRIMARY KEY,year INT,allocation DECIMAL(10,2)); INSERT INTO national_security_budget (budget_id,year,allocation) VALUES (1,2020,700.50),(2,2021,750.25),(3,2022,800.00),(4,2023,850.75);
|
SELECT year, allocation FROM national_security_budget WHERE year IN (2021, 2022);
|
What is the maximum years of experience for geologists in the 'geologists' table?
|
CREATE TABLE geologists (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),years_of_experience INT);
|
SELECT MAX(years_of_experience) FROM geologists;
|
Increase the nitrogen levels for all soy fields by 10%.
|
CREATE TABLE field (id INT,type VARCHAR(20)); CREATE TABLE nutrients (id INT,field_id INT,nitrogen INT,phosphorus INT);
|
UPDATE nutrients SET nitrogen = nutrients.nitrogen * 1.10 FROM field WHERE field.type = 'soy';
|
What is the total cargo weight transported by each shipping line in the first quarter of 2022, and what is the percentage of the total weight each shipping line transported during that time?
|
CREATE TABLE shipping_lines (shipping_line_id INT,shipping_line_name VARCHAR(100)); CREATE TABLE containers (container_id INT,container_weight INT,shipping_line_id INT,shipped_date DATE); INSERT INTO shipping_lines VALUES (1,'Maersk Line'); INSERT INTO shipping_lines VALUES (2,'MSC Mediterranean Shipping Company'); INSERT INTO containers VALUES (1,10,1,'2022-03-01'); INSERT INTO containers VALUES (2,15,2,'2022-02-15'); INSERT INTO containers VALUES (3,20,1,'2022-01-10');
|
SELECT shipping_lines.shipping_line_name, SUM(containers.container_weight) as total_weight, (SUM(containers.container_weight) / (SELECT SUM(container_weight) FROM containers WHERE shipped_date BETWEEN '2022-01-01' AND '2022-03-31')) * 100 as percentage_of_total FROM shipping_lines INNER JOIN containers ON shipping_lines.shipping_line_id = containers.shipping_line_id WHERE containers.shipped_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY shipping_lines.shipping_line_name;
|
Calculate the average number of reviews for hotels in South America
|
CREATE TABLE hotels (id INT,name TEXT,country TEXT,reviews INT); INSERT INTO hotels (id,name,country,reviews) VALUES (1,'Hotel A','South America',120),(2,'Hotel B','South America',80),(3,'Hotel C','North America',150);
|
SELECT AVG(reviews) FROM hotels WHERE country = 'South America';
|
Show athlete names and their age from the athlete_demographics table for athletes that play basketball.
|
CREATE TABLE athlete_demographics (id INT,name VARCHAR(50),age INT,sport VARCHAR(50));
|
SELECT name, age FROM athlete_demographics WHERE sport = 'basketball';
|
What is the maximum depth of the Indian Ocean?"
|
CREATE TABLE oceans (id INT,name TEXT,avg_depth FLOAT,max_depth FLOAT); INSERT INTO oceans (id,name,avg_depth,max_depth) VALUES (1,'Indian',3962,7258);
|
SELECT max_depth FROM oceans WHERE name = 'Indian Ocean';
|
What is the average ESG score of organizations in the technology sector?
|
CREATE TABLE organizations (org_id INT,org_name TEXT,industry TEXT,esg_score DECIMAL(3,2)); INSERT INTO organizations (org_id,org_name,industry,esg_score) VALUES (1,'Tech Org 1','Technology',75.2),(2,'Tech Org 2','Technology',82.5),(3,'Non-Tech Org 1','Manufacturing',68.1);
|
SELECT AVG(esg_score) FROM organizations WHERE industry = 'Technology';
|
Add a new vegan certification awarded by the 'CCF' organization to the cosmetics."certifications" table
|
CREATE TABLE cosmetics.certifications (certification_id INT,certification_name VARCHAR(255),awarded_by VARCHAR(255)); INSERT INTO cosmetics.certifications (certification_id,certification_name,awarded_by) VALUES (1,'Leaping Bunny','CCIC'),(2,'Cruelty Free','CCIC'),(3,'Vegan','PETA');
|
INSERT INTO cosmetics.certifications (certification_id, certification_name, awarded_by) VALUES (4, '100% Vegan', 'CCF');
|
What are the names of all astronauts who have flown on a SpaceTech Inc. spacecraft?
|
CREATE TABLE Astronauts (astronaut_id INT,name VARCHAR(50),flights INT); CREATE TABLE Flights (flight_id INT,spacecraft VARCHAR(50),manufacturer VARCHAR(50)); INSERT INTO Astronauts (astronaut_id,name,flights) VALUES (1,'Astronaut1',3),(2,'Astronaut2',1); INSERT INTO Flights (flight_id,spacecraft,manufacturer) VALUES (1,'Spacecraft1','SpaceTech Inc.'),(2,'Spacecraft2','SpaceTech Inc.');
|
SELECT DISTINCT a.name FROM Astronauts a JOIN Flights f ON a.flights = f.flight_id WHERE f.manufacturer = 'SpaceTech Inc.';
|
What is the survival rate of fish in the 'fish_health' table?
|
CREATE TABLE fish_health (id INT,farm_id INT,survival_rate FLOAT); INSERT INTO fish_health (id,farm_id,survival_rate) VALUES (1,1,0.9); INSERT INTO fish_health (id,farm_id,survival_rate) VALUES (2,2,0.85); INSERT INTO fish_health (id,farm_id,survival_rate) VALUES (3,3,0.95);
|
SELECT survival_rate FROM fish_health WHERE farm_id = (SELECT id FROM farms ORDER BY RAND() LIMIT 1);
|
What is the average water temperature in the Pacific Ocean for January, for the past 5 years, from the temperature_data table?
|
CREATE TABLE temperature_data (date DATE,ocean TEXT,temperature FLOAT); INSERT INTO temperature_data (date,ocean,temperature) VALUES ('2018-01-01','Pacific',12.5); INSERT INTO temperature_data (date,ocean,temperature) VALUES ('2019-01-01','Pacific',13.0); INSERT INTO temperature_data (date,ocean,temperature) VALUES ('2020-01-01','Pacific',11.8); INSERT INTO temperature_data (date,ocean,temperature) VALUES ('2021-01-01','Pacific',12.3); INSERT INTO temperature_data (date,ocean,temperature) VALUES ('2022-01-01','Pacific',12.9);
|
SELECT AVG(temperature) FROM temperature_data WHERE ocean = 'Pacific' AND MONTH(date) = 1 AND YEAR(date) BETWEEN 2018 AND 2022;
|
What is the total water consumption by city in 2020, considering domestic, commercial, and agricultural consumption?
|
CREATE TABLE water_usage (city VARCHAR(255),year INT,domestic_consumption INT,commercial_consumption INT,agricultural_consumption INT); INSERT INTO water_usage (city,year,domestic_consumption,commercial_consumption,agricultural_consumption) VALUES ('CityA',2020,350,250,550),('CityB',2020,450,350,650),('CityC',2020,500,400,700),('CityD',2020,400,300,600);
|
SELECT city, (domestic_consumption + commercial_consumption + agricultural_consumption) as total_consumption FROM water_usage WHERE year = 2020 GROUP BY city;
|
Count the number of esports events held in Asia in 2022.
|
CREATE TABLE EsportsEvents (EventID INT,EventName VARCHAR(50),Location VARCHAR(50),Year INT); INSERT INTO EsportsEvents (EventID,EventName,Location,Year) VALUES (1,'Event1','USA',2022); INSERT INTO EsportsEvents (EventID,EventName,Location,Year) VALUES (2,'Event2','Canada',2021); INSERT INTO EsportsEvents (EventID,EventName,Location,Year) VALUES (3,'Event3','China',2022);
|
SELECT COUNT(*) FROM EsportsEvents WHERE Location = 'China' AND Year = 2022;
|
How many workers are employed in factories that use eco-friendly materials?
|
CREATE TABLE factories_eco_friendly(factory_id INT,workers INT,material VARCHAR(20)); INSERT INTO factories_eco_friendly(factory_id,workers,material) VALUES(1,100,'organic cotton'),(2,150,'recycled polyester'),(3,200,'hemp');
|
SELECT SUM(workers) FROM factories_eco_friendly WHERE material IN ('organic cotton', 'recycled polyester', 'hemp');
|
What is the maximum number of HIV tests performed in a single day in the city of San Francisco in 2021?
|
CREATE TABLE hiv_tests (test_id INT,patient_id INT,city TEXT,date DATE,tests INT); INSERT INTO hiv_tests (test_id,patient_id,city,date,tests) VALUES (1,1,'San Francisco','2021-01-01',50);
|
SELECT MAX(tests) FROM hiv_tests WHERE city = 'San Francisco' AND date LIKE '2021-%';
|
Find the number of users who have not completed any workout in the last 7 days.
|
CREATE TABLE workout_attendance (user_id INT,date DATE); INSERT INTO workout_attendance (user_id,date) VALUES (1,'2022-03-01'),(1,'2022-03-03'),(2,'2022-02-15'),(1,'2022-03-05'),(3,'2022-02-28'),(1,'2022-03-07'),(4,'2022-03-05');
|
SELECT COUNT(DISTINCT user_id) FROM workout_attendance WHERE user_id NOT IN (SELECT user_id FROM workout_attendance WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY));
|
What are the total CO2 emissions for the power sector in each country?
|
CREATE TABLE co2_emissions (id INT,country VARCHAR(255),year INT,sector VARCHAR(255),emissions FLOAT);
|
SELECT country, SUM(emissions) FROM co2_emissions WHERE sector = 'Power' GROUP BY country;
|
What is the maximum package weight shipped between France and Germany in the last week?
|
CREATE TABLE package_weights (id INT,package_weight FLOAT,shipped_from VARCHAR(20),shipped_to VARCHAR(20),shipped_date DATE); INSERT INTO package_weights (id,package_weight,shipped_from,shipped_to,shipped_date) VALUES (1,5.0,'France','Germany','2022-02-01');
|
SELECT MAX(package_weight) FROM package_weights WHERE shipped_from = 'France' AND shipped_to = 'Germany' AND shipped_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK);
|
What is the minimum price of sustainable clothing items, grouped by brand?
|
CREATE TABLE Clothing (id INT,brand VARCHAR(255),price DECIMAL(5,2),sustainable VARCHAR(10)); INSERT INTO Clothing (id,brand,price,sustainable) VALUES (1,'BrandA',25.99,'yes'),(2,'BrandB',150.00,'yes'),(3,'BrandC',79.99,'no'),(4,'BrandD',19.99,'yes');
|
SELECT brand, MIN(price) FROM Clothing WHERE sustainable = 'yes' GROUP BY brand;
|
What is the total number of virtual tour engagements in Oceania?
|
CREATE TABLE otas (ota_id INT,ota_name TEXT,region TEXT); CREATE TABLE virtual_tours (vt_id INT,ota_id INT,engagements INT); INSERT INTO otas (ota_id,ota_name,region) VALUES (1,'OTA 1','Oceania'),(2,'OTA 2','Europe'),(3,'OTA 3','Asia'); INSERT INTO virtual_tours (vt_id,ota_id,engagements) VALUES (1,1,500),(2,2,300),(3,3,700),(4,1,800);
|
SELECT SUM(engagements) FROM virtual_tours JOIN otas ON virtual_tours.ota_id = otas.ota_id WHERE region = 'Oceania';
|
Get the average depth of marine life research sites in the Caribbean sea
|
CREATE TABLE caribbean_sites (site_id INT,site_name VARCHAR(255),longitude DECIMAL(9,6),latitude DECIMAL(9,6),depth DECIMAL(5,2)); CREATE VIEW caribbean_sites_view AS SELECT * FROM caribbean_sites WHERE latitude BETWEEN 10 AND 25 AND longitude BETWEEN -80 AND -60;
|
SELECT AVG(depth) FROM caribbean_sites_view;
|
What are the top 3 countries with the highest number of unique vulnerabilities in the vulnerabilities table?
|
CREATE TABLE vulnerabilities (id INT,vulnerability VARCHAR(50),country VARCHAR(50)); INSERT INTO vulnerabilities (id,vulnerability,country) VALUES (1,'SQL Injection','USA'),(2,'Cross-Site Scripting','Canada'),(3,'Privilege Escalation','Brazil'),(4,'SQL Injection','Mexico'),(5,'SQL Injection','Brazil'),(6,'Cross-Site Scripting','USA');
|
SELECT country, COUNT(DISTINCT vulnerability) AS num_vulnerabilities FROM vulnerabilities GROUP BY country ORDER BY num_vulnerabilities DESC LIMIT 3;
|
Which cosmetic products have had safety recalls in Canada?
|
CREATE TABLE Product_Safety (ProductID INT,Recall BOOLEAN,Country VARCHAR(50)); INSERT INTO Product_Safety (ProductID,Recall,Country) VALUES (2001,TRUE,'Canada'),(2002,FALSE,'Canada'),(2003,TRUE,'Canada'),(2004,FALSE,'Canada'),(2005,TRUE,'Canada');
|
SELECT ProductID FROM Product_Safety WHERE Recall = TRUE AND Country = 'Canada';
|
Which autonomous driving research papers were published in the last 3 years?
|
CREATE TABLE research_papers (title VARCHAR(50),publication_year INT,is_autonomous BOOLEAN);
|
SELECT * FROM research_papers WHERE is_autonomous = TRUE AND publication_year BETWEEN (SELECT MAX(publication_year) - 3) AND MAX(publication_year);
|
What is the number of hospital admissions by age group in California?
|
CREATE TABLE hospital_admissions (id INT,age_group TEXT,state TEXT,num_admissions INT); INSERT INTO hospital_admissions (id,age_group,state,num_admissions) VALUES (1,'0-17','California',250),(2,'18-34','California',750),(3,'35-49','California',900),(4,'50+','California',1200);
|
SELECT age_group, SUM(num_admissions) FROM hospital_admissions WHERE state = 'California' GROUP BY age_group;
|
What is the total number of research grants awarded to students with a 'Master of Arts' degree?
|
CREATE TABLE research_grants (grant_id INT,title VARCHAR(50),amount DECIMAL(10,2),year INT,student_id INT,degree VARCHAR(50)); INSERT INTO research_grants VALUES (1,'Grant1',50000,2019,789,'Master of Arts'); CREATE TABLE students (student_id INT,name VARCHAR(50),degree VARCHAR(50)); INSERT INTO students VALUES (789,'Jasmine Lee','Master of Arts');
|
SELECT COUNT(*) FROM research_grants rg JOIN students s ON rg.student_id = s.student_id WHERE degree = 'Master of Arts';
|
What is the total number of medals won by athletes from Japan in Swimming?
|
CREATE TABLE JapaneseSwimmers (SwimmerID INT,Name VARCHAR(50),Age INT,Medals INT,Sport VARCHAR(20),Country VARCHAR(50)); INSERT INTO JapaneseSwimmers (SwimmerID,Name,Age,Medals,Sport,Country) VALUES (1,'Daiya Seto',27,15,'Swimming','Japan'); INSERT INTO JapaneseSwimmers (SwimmerID,Name,Age,Medals,Sport,Country) VALUES (2,'Rikako Ikee',22,8,'Swimming','Japan');
|
SELECT SUM(Medals) FROM JapaneseSwimmers WHERE Sport = 'Swimming' AND Country = 'Japan';
|
What is the earliest launch date for each aircraft model?
|
CREATE TABLE aircrafts (aircraft_id INT,model VARCHAR(50),launch_date DATE); INSERT INTO aircrafts (aircraft_id,model,launch_date) VALUES (1,'Boeing 747','2000-01-01'),(2,'Airbus A320','2010-01-01'),(3,'Boeing 737','1995-01-01'); CREATE TABLE accidents (accident_id INT,aircraft_id INT,date DATE); INSERT INTO accidents (accident_id,aircraft_id) VALUES (1,1),(2,1),(3,3),(4,2),(5,2);
|
SELECT model, MIN(launch_date) as earliest_launch_date FROM aircrafts WHERE aircraft_id NOT IN (SELECT aircraft_id FROM accidents) GROUP BY model;
|
What is the total number of entries for all metro stations in Tokyo on January 1, 2022?
|
CREATE TABLE tokyo_metro_entries (id INT,station_name VARCHAR(255),entries INT,entry_date DATE); INSERT INTO tokyo_metro_entries (id,station_name,entries,entry_date) VALUES (1,'Station 1',12000,'2022-01-01'),(2,'Station 2',8000,'2022-01-01');
|
SELECT SUM(entries) FROM tokyo_metro_entries WHERE entry_date = '2022-01-01';
|
What is the maximum number of crimes and the corresponding crime type in each city?
|
CREATE TABLE CrimeStatistics (Id INT,Crime VARCHAR(20),Location VARCHAR(20),Date TIMESTAMP,Population INT);
|
SELECT c.Location, MAX(cc.CrimeCount) as MaxCrimes, cc.CrimeType FROM CrimeStatistics cc JOIN (SELECT Location, COUNT(*) as CrimeCount, Crime as CrimeType FROM CrimeStatistics GROUP BY Location, Crime) c ON cc.Location = c.Location AND cc.Crime = c.CrimeType GROUP BY c.Location;
|
Display the number of pollution incidents in the Southern Ocean.
|
CREATE TABLE pollution_incidents (id INT,incident_type VARCHAR(50),location_latitude FLOAT,location_longitude FLOAT,ocean VARCHAR(50)); INSERT INTO pollution_incidents (id,incident_type,location_latitude,location_longitude,ocean) VALUES (1,'Oil Spill',-60.6667,148.9667,'Southern Ocean'),(2,'Garbage Patch',-46.6333,81.1833,'Southern Ocean');
|
SELECT COUNT(*) FROM pollution_incidents WHERE ocean = 'Southern Ocean';
|
List all clinical trials, including those without any reported adverse events, for a specific drug in the 'clinical_trials' and 'adverse_events' tables in the USA?
|
CREATE TABLE clinical_trials (clinical_trial_id INT,drug_id INT,trial_name TEXT,country TEXT); CREATE TABLE adverse_events (adverse_event_id INT,clinical_trial_id INT,event_description TEXT); INSERT INTO clinical_trials (clinical_trial_id,drug_id,trial_name,country) VALUES (1,1,'TrialX','USA'),(2,2,'TrialY','Canada');
|
SELECT ct.trial_name, COALESCE(COUNT(ae.adverse_event_id), 0) AS event_count FROM clinical_trials ct LEFT JOIN adverse_events ae ON ct.clinical_trial_id = ae.clinical_trial_id WHERE ct.country = 'USA' AND ct.drug_id = 1 GROUP BY ct.trial_name;
|
Insert a new record for DonorC from India with an amount of 2500.00
|
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT,Amount DECIMAL(10,2)); INSERT INTO Donors (DonorID,DonorName,Country,Amount) VALUES (1,'DonorA','USA',1500.00),(2,'DonorB','Canada',2000.00);
|
INSERT INTO Donors (DonorName, Country, Amount) VALUES ('DonorC', 'India', 2500.00);
|
What is the average quantity of sustainable material orders?
|
CREATE TABLE orders(id INT,product_id INT,quantity INT,order_date DATE,is_sustainable BOOLEAN); INSERT INTO orders (id,product_id,quantity,order_date,is_sustainable) VALUES (1,1,2,'2022-01-01',true);
|
SELECT AVG(quantity) FROM orders WHERE is_sustainable = true;
|
What is the average delivery time per shipment in Australia?
|
CREATE TABLE Warehouses (WarehouseID INT,WarehouseName VARCHAR(50),Country VARCHAR(50)); INSERT INTO Warehouses (WarehouseID,WarehouseName,Country) VALUES (1,'Australia Warehouse','Australia'); CREATE TABLE Shipments (ShipmentID INT,WarehouseID INT,DeliveryTime INT);
|
SELECT AVG(DeliveryTime) / COUNT(*) FROM Shipments WHERE WarehouseID = (SELECT WarehouseID FROM Warehouses WHERE Country = 'Australia');
|
What is the average rating of movies directed by 'Director1'?
|
CREATE TABLE movies (id INT,title TEXT,rating FLOAT,director TEXT); INSERT INTO movies (id,title,rating,director) VALUES (1,'Movie1',4.5,'Director1'),(2,'Movie2',3.2,'Director2'),(3,'Movie3',4.7,'Director1');
|
SELECT AVG(rating) FROM movies WHERE director = 'Director1';
|
What is the total budget allocated for each category, and what is the percentage of the total budget allocated to each category for each city?
|
CREATE TABLE BudgetAllocation (Id INT,CityId INT,Category VARCHAR(50),Amount DECIMAL(10,2)); INSERT INTO BudgetAllocation (Id,CityId,Category,Amount) VALUES (1,1,'Transportation',5000000),(2,1,'Infrastructure',3000000),(3,2,'Transportation',7000000),(4,2,'Infrastructure',6000000);
|
SELECT CityId, Category, SUM(Amount) AS TotalBudget, SUM(Amount) OVER (PARTITION BY CityId) AS CityTotal, (SUM(Amount) OVER (PARTITION BY CityId)) * 100.0 / SUM(Amount) OVER () AS CategoryPercentage FROM BudgetAllocation GROUP BY CityId, Category;
|
What was the total amount spent on food aid in 2019?
|
CREATE TABLE expenses (id INT,category TEXT,year INT,amount_spent DECIMAL(10,2)); INSERT INTO expenses
|
SELECT SUM(amount_spent) FROM expenses WHERE category = 'food aid' AND year = 2019;
|
Pivot policy region and sum of claim amounts
|
CREATE TABLE policy (policy_id INT,policy_region VARCHAR(20)); INSERT INTO policy (policy_id,policy_region) VALUES (1001,'Northeast'),(1002,'Southeast'),(1003,'Northeast'),(1004,'Southwest'); CREATE TABLE claims (claim_id INT,policy_id INT,claim_amount INT); INSERT INTO claims (claim_id,policy_id,claim_amount) VALUES (1,1001,500),(2,1002,1200),(3,1003,2500),(4,1004,3000);
|
SELECT policy_region, SUM(CASE WHEN policy_region = 'Northeast' THEN claim_amount ELSE 0 END) AS northeast_claim_amount, SUM(CASE WHEN policy_region = 'Southeast' THEN claim_amount ELSE 0 END) AS southeast_claim_amount, SUM(CASE WHEN policy_region = 'Southwest' THEN claim_amount ELSE 0 END) AS southwest_claim_amount FROM policy p JOIN claims c ON p.policy_id = c.policy_id GROUP BY policy_region WITH ROLLUP;
|
Update subscribers' data usage who have '3G' network type and are from 'Asia' region.
|
CREATE TABLE subscribers (subscriber_id INT,network_type VARCHAR(10),data_usage FLOAT,region VARCHAR(20)); INSERT INTO subscribers (subscriber_id,network_type,data_usage,region) VALUES (1,'3G',15.5,'Asia'),(2,'4G',20.0,'Asia'),(3,'3G',30.0,'Europe'),(4,'5G',10.0,'Asia');
|
UPDATE subscribers SET data_usage = 22.5 WHERE network_type = '3G' AND region = 'Asia';
|
What is the average cost of rural infrastructure projects in Vietnam in 2020?
|
CREATE TABLE rural_infrastructure (id INT,country VARCHAR(50),year INT,cost FLOAT); INSERT INTO rural_infrastructure (id,country,year,cost) VALUES (1,'Vietnam',2020,50000),(2,'Vietnam',2020,60000),(3,'Vietnam',2020,70000);
|
SELECT AVG(cost) FROM rural_infrastructure WHERE country = 'Vietnam' AND year = 2020;
|
What is the average launch cost (in USD) of SpaceX missions?
|
CREATE TABLE launch_costs (id INT,mission VARCHAR(50),launch_date DATE,company VARCHAR(50),cost FLOAT);
|
SELECT AVG(cost) FROM launch_costs WHERE company = 'SpaceX';
|
Find the total number of donations and their sum, grouped by payment method
|
CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL,payment_method VARCHAR);
|
SELECT payment_method, COUNT(*) as total_donations, SUM(amount) as total_amount FROM donations GROUP BY payment_method;
|
Delete all records from the 'field_4' table where crop_type is 'corn'
|
CREATE TABLE field_4 (id INT PRIMARY KEY,x_coordinate INT,y_coordinate INT,crop_type TEXT,area_hectares FLOAT); INSERT INTO field_4 (id,x_coordinate,y_coordinate,crop_type,area_hectares) VALUES (1,650,750,'corn',7.2),(2,700,800,'sunflowers',9.1),(3,750,850,'rice',4.6);
|
DELETE FROM field_4 WHERE crop_type = 'corn';
|
What is the minimum budget allocation for any service in CityZ?
|
CREATE TABLE cities (id INT,name VARCHAR(20)); INSERT INTO cities VALUES (1,'CityZ'); CREATE TABLE budget_allocation (service VARCHAR(20),city_id INT,amount INT); INSERT INTO budget_allocation VALUES ('Healthcare',1,500000),('Education',1,800000),('Education',1,300000),('Public Service',1,200000);
|
SELECT MIN(amount) FROM budget_allocation WHERE city_id = (SELECT id FROM cities WHERE name = 'CityZ');
|
Find the total number of public participation data sets in 'province' and 'territory' schemas.
|
CREATE SCHEMA province; CREATE SCHEMA territory; CREATE TABLE province.participation_data (id INT,name VARCHAR(255),is_public BOOLEAN); CREATE TABLE territory.participation_data (id INT,name VARCHAR(255),is_public BOOLEAN); INSERT INTO province.participation_data (id,name,is_public) VALUES (1,'consultations',true),(2,'surveys',false); INSERT INTO territory.participation_data (id,name,is_public) VALUES (1,'consultations',true),(2,'hearings',true);
|
SELECT COUNT(*) FROM ( (SELECT * FROM province.participation_data WHERE is_public = true) UNION (SELECT * FROM territory.participation_data WHERE is_public = true) ) AS combined_participation_data;
|
What is the average quantity of items in the inventory for the top 3 countries with the most inventory?
|
CREATE TABLE Inventory (InventoryId INT,WarehouseId INT,ProductId INT,Quantity INT,Country VARCHAR(50)); INSERT INTO Inventory (InventoryId,WarehouseId,ProductId,Quantity,Country) VALUES (1,1,1,100,'USA'); INSERT INTO Inventory (InventoryId,WarehouseId,ProductId,Quantity,Country) VALUES (2,1,2,200,'USA'); INSERT INTO Inventory (InventoryId,WarehouseId,ProductId,Quantity,Country) VALUES (3,2,1,300,'Canada'); INSERT INTO Inventory (InventoryId,WarehouseId,ProductId,Quantity,Country) VALUES (4,2,2,400,'Canada'); INSERT INTO Inventory (InventoryId,WarehouseId,ProductId,Quantity,Country) VALUES (5,3,1,500,'Mexico');
|
SELECT AVG(Quantity) AS AvgQuantity FROM Inventory GROUP BY Country ORDER BY SUM(Quantity) DESC LIMIT 3;
|
Get all products shipped after their expiration date.
|
CREATE TABLE supply_chain (id INTEGER,product_id VARCHAR(10),shipped_date DATE,expiration_date DATE);
|
SELECT supply_chain.* FROM supply_chain JOIN (SELECT product_id, MIN(shipped_date) AS min_shipped_date FROM supply_chain GROUP BY product_id) AS min_shipped_dates ON supply_chain.product_id = min_shipped_dates.product_id WHERE min_shipped_dates.min_shipped_date > supply_chain.expiration_date;
|
What is the average contract negotiation duration for each sales representative, ranked by duration?
|
CREATE TABLE Contract_Negotiations (negotiation_id INT,sales_rep VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO Contract_Negotiations (negotiation_id,sales_rep,start_date,end_date) VALUES (1,'John Doe','2020-01-01','2020-01-15'),(2,'Jane Smith','2020-02-01','2020-02-20'),(3,'John Doe','2020-03-01','2020-03-10'),(4,'Jane Smith','2020-04-01','2020-04-15');
|
SELECT sales_rep, AVG(DATEDIFF(end_date, start_date)) AS avg_duration, RANK() OVER (ORDER BY AVG(DATEDIFF(end_date, start_date)) DESC) AS duration_rank FROM Contract_Negotiations GROUP BY sales_rep;
|
Get the total number of volunteers and total donation amount per country.
|
CREATE TABLE volunteer_data (id INT,volunteer_country VARCHAR,donation_country VARCHAR,num_volunteers INT,total_donation_amount DECIMAL);
|
SELECT volunteer_country, SUM(total_donation_amount) as total_donation_amount, SUM(num_volunteers) as total_num_volunteers FROM volunteer_data GROUP BY volunteer_country;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.