instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Which company has the highest Yttrium production volume?
CREATE TABLE yttrium_production (company VARCHAR(255),production_volume INT);
SELECT company, production_volume FROM yttrium_production ORDER BY production_volume DESC LIMIT 1;
Who was the top donor in Q1 2021?
CREATE TABLE donations (id INT,donor_name TEXT,amount DECIMAL(10,2)); INSERT INTO donations (id,donor_name,amount) VALUES (7,'Grace',500.00),(8,'Hugo',300.00),(9,'Irene',200.00);
SELECT donor_name FROM donations WHERE amount = (SELECT MAX(amount) FROM donations WHERE donation_date BETWEEN '2021-01-01' AND '2021-03-31')
Find the names and positions of employees who earn more than the average salary?
CREATE TABLE employee_salaries (id INT,name VARCHAR(50),position VARCHAR(50),salary INT); CREATE VIEW avg_salary AS SELECT AVG(salary) AS avg_salary FROM employee_salaries;
SELECT name, position FROM employee_salaries WHERE salary > (SELECT avg_salary FROM avg_salary);
What is the most common diagnosis code for each gender?
CREATE TABLE diagnoses (id INT,patient_id INT,code VARCHAR(10),gender VARCHAR(10)); INSERT INTO diagnoses (id,patient_id,code,gender) VALUES (1,1,'A01','Male'),(2,1,'B01','Male'),(3,2,'A01','Female'),(4,3,'C01','Female');
SELECT gender, code, COUNT(*) FROM diagnoses GROUP BY gender, code HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC;
Find investigative journalism projects published by 'CBC' or 'NHK' but not by 'PBS'.
CREATE TABLE cbc (project_id INT,project_name VARCHAR(50),source VARCHAR(10),investigative_journalism BOOLEAN); INSERT INTO cbc (project_id,project_name,source,investigative_journalism) VALUES (1,'Project A','CBC',TRUE),(2,'Project B','CBC',FALSE); CREATE TABLE nhk (project_id INT,project_name VARCHAR(50),source VARCHAR(10),investigative_journalism BOOLEAN); INSERT INTO nhk (project_id,project_name,source,investigative_journalism) VALUES (3,'Project C','NHK',TRUE),(4,'Project D','NHK',FALSE); CREATE TABLE pbs (project_id INT,project_name VARCHAR(50),source VARCHAR(10),investigative_journalism BOOLEAN); INSERT INTO pbs (project_id,project_name,source,investigative_journalism) VALUES (5,'Project E','PBS',TRUE),(6,'Project F','PBS',FALSE);
SELECT project_name, source FROM cbc WHERE investigative_journalism = TRUE UNION ALL SELECT project_name, source FROM nhk WHERE investigative_journalism = TRUE EXCEPT SELECT project_name, source FROM pbs WHERE investigative_journalism = TRUE;
What is the total waste generation for each waste type, in 2021, for urban areas in Asia?
CREATE TABLE waste_generation (waste_type TEXT,amount INTEGER,year INTEGER,area TEXT);
SELECT waste_type, SUM(amount) FROM waste_generation WHERE area = 'Asia' AND year = 2021 GROUP BY waste_type;
List all climate communication projects and their respective funding allocations for the year 2018.
CREATE TABLE climate_communication_projects (project_id INT,project_name TEXT,allocation DECIMAL(10,2),year INT); INSERT INTO climate_communication_projects (project_id,project_name,allocation,year) VALUES (10,'Climate Education J',400000,2018),(11,'Public Awareness K',500000,2018),(12,'Media Campaign L',600000,2018);
SELECT project_name, allocation FROM climate_communication_projects WHERE year = 2018;
Find the number of units produced per country and month, for the year 2022.
CREATE TABLE production_data (country VARCHAR(255),production_date DATE,units_produced INT);
SELECT country, DATE_FORMAT(production_date, '%Y-%m') AS month, SUM(units_produced) FROM production_data WHERE production_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY country, month;
Delete all records of public meetings in the 'Transportation' department from before 2022.
CREATE TABLE meetings (id INT,dept VARCHAR(255),meeting_date DATE); INSERT INTO meetings (id,dept,meeting_date) VALUES (1,'Urban Development','2022-03-01'),(2,'Transportation','2021-05-15'),(3,'Transportation','2022-03-04');
DELETE FROM meetings WHERE dept = 'Transportation' AND meeting_date < '2022-01-01';
List all transactions for customer 'Alice' in the past month
CREATE TABLE customers (id INT,name VARCHAR(50)); CREATE TABLE transactions (id INT,customer_id INT,transaction_date DATE,amount FLOAT); INSERT INTO customers (id,name) VALUES (1,'Alice'),(2,'Bob'); INSERT INTO transactions (id,customer_id,transaction_date,amount) VALUES (1,1,'2022-02-01',100.00),(2,1,'2022-02-15',200.00),(3,2,'2022-01-01',50.00);
SELECT * FROM transactions WHERE customer_id = (SELECT id FROM customers WHERE name = 'Alice') AND transaction_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND CURDATE();
Which suppliers provide more than 50% of the organic produce for our stores in Asia?
CREATE TABLE suppliers (id INT,name VARCHAR(50),organic_produce_percentage DECIMAL(5,2)); INSERT INTO suppliers (id,name,organic_produce_percentage) VALUES (1,'Tropical Farms',0.65),(2,'Green Valley',0.48),(3,'Asian Harvest',0.8); CREATE TABLE stores (id INT,region VARCHAR(50),supplier_id INT); INSERT INTO stores (id,region,supplier_id) VALUES (1,'China',1),(2,'Japan',2),(3,'Korea',3);
SELECT suppliers.name FROM suppliers JOIN stores ON suppliers.id = stores.supplier_id WHERE stores.region LIKE 'Asia%' AND suppliers.organic_produce_percentage > 0.5 GROUP BY suppliers.name HAVING COUNT(DISTINCT stores.id) > 1;
How many female and non-binary individuals attended poetry readings compared to male attendees?
CREATE TABLE poetry_readings (attendee_id INT,gender TEXT);
SELECT CASE WHEN gender IN ('Female', 'Non-binary') THEN 'Female and Non-binary' ELSE 'Male' END AS gender, COUNT(*) FROM poetry_readings GROUP BY gender;
What is the average quantity of 'Pants' sold in 'Asia' for the 'Winter 2022' season?
CREATE TABLE Sales (SaleID INT,ProductID INT,QuantitySold INT,Country VARCHAR(50),SaleDate DATE); INSERT INTO Sales (SaleID,ProductID,QuantitySold,Country,SaleDate) VALUES (1,3,40,'China','2022-12-21'),(2,2,30,'Japan','2022-12-03'),(3,3,60,'India','2023-01-01'); CREATE TABLE Products (ProductID INT,ProductType VARCHAR(20)); INSERT INTO Products (ProductID,ProductType) VALUES (3,'Pants'),(2,'Tops');
SELECT AVG(QuantitySold) as AvgQuantity FROM Sales S JOIN Products P ON S.ProductID = P.ProductID WHERE P.ProductType = 'Pants' AND Country = 'Asia' AND SaleDate BETWEEN '2022-12-01' AND '2023-01-31' AND Country IN ('China', 'Japan', 'India');
What is the minimum claim amount for policyholders in 'Texas'?
CREATE TABLE policyholders (id INT,name TEXT,city TEXT,state TEXT,claim_amount FLOAT); INSERT INTO policyholders (id,name,city,state,claim_amount) VALUES (1,'John Doe','Houston','TX',2500.00); INSERT INTO policyholders (id,name,city,state,claim_amount) VALUES (2,'Jane Doe','Dallas','TX',4000.00);
SELECT MIN(claim_amount) FROM policyholders WHERE state = 'TX';
Delete the record of the employee with ID 3 from the 'Diversity Metrics' table if they are from the 'Technology' department.
CREATE TABLE diversity_metrics (id INT,name VARCHAR(50),department VARCHAR(50),metric VARCHAR(50));
DELETE FROM diversity_metrics WHERE id = 3 AND department = 'Technology';
What is the average duration of songs released in 2020?
CREATE TABLE songs (id INT,title VARCHAR(255),duration INT,release_year INT); INSERT INTO songs (id,title,duration,release_year) VALUES (1,'Song 1',180,2020);
SELECT AVG(duration) FROM songs WHERE release_year = 2020;
Find marine species at risk in specific marine protected areas.
CREATE TABLE marine_species (species_id INT,name VARCHAR(255),status VARCHAR(255)); CREATE TABLE area_species (area_id INT,species_id INT);
SELECT s.name FROM marine_species s JOIN area_species a ON s.species_id = a.species_id WHERE a.area_id IN (1, 3, 5);
What are the total sales for each product category?
CREATE TABLE products (product_id INT,product_name VARCHAR(255),category VARCHAR(255),sales FLOAT); INSERT INTO products (product_id,product_name,category,sales) VALUES (1,'ProductA','CategoryA',5000),(2,'ProductB','CategoryB',7000),(3,'ProductC','CategoryA',6000);
SELECT category, SUM(sales) FROM products GROUP BY category;
Find the number of green buildings in each country.
CREATE TABLE green_buildings (building_id INT,country VARCHAR(50)); INSERT INTO green_buildings (building_id,country) VALUES (1,'USA'),(2,'Canada'),(3,'Mexico'),(4,'USA');
SELECT country, COUNT(*) FROM green_buildings GROUP BY country
Create a view for Health Workers with score less than 85
CREATE TABLE CulturalCompetency (ID INT PRIMARY KEY,HealthWorkerName VARCHAR(100),CulturalCompetencyScore INT);
CREATE VIEW LowScoringHealthWorkers AS SELECT HealthWorkerName FROM CulturalCompetency WHERE CulturalCompetencyScore < 85;
Top 3 Shariah-compliant finance institutions in Australia
CREATE TABLE shariah_compliant_finance_3 (id INT,country VARCHAR(20),institution VARCHAR(30)); INSERT INTO shariah_compliant_finance_3 (id,country,institution) VALUES (1,'Australia','Islamic Bank Australia'),(2,'Australia','Bank of Sydney'),(3,'Australia','CommBank Shariah');
SELECT institution FROM (SELECT institution, ROW_NUMBER() OVER (ORDER BY institution DESC) rn FROM shariah_compliant_finance_3 WHERE country = 'Australia') t WHERE rn <= 3;
Show the names of companies that produced more of Dysprosium than Ytterbium in 2015.
CREATE TABLE Producers (ProducerID INT PRIMARY KEY,Name TEXT,ProductionYear INT,RareEarth TEXT,Quantity INT);
SELECT DISTINCT p1.Name FROM Producers p1, Producers p2 WHERE p1.ProductionYear = 2015 AND p2.ProductionYear = 2015 AND p1.RareEarth = 'Dysprosium' AND p2.RareEarth = 'Ytterbium' AND p1.Quantity > p2.Quantity;
What is the total revenue generated from military equipment sales to South America by Boeing in 2019 and 2020?
CREATE TABLE MilitaryEquipmentSales (EquipmentID INT,Manufacturer VARCHAR(50),DestinationCountry VARCHAR(50),SaleDate DATE,Quantity INT,UnitPrice FLOAT); INSERT INTO MilitaryEquipmentSales (EquipmentID,Manufacturer,DestinationCountry,SaleDate,Quantity,UnitPrice) VALUES (1,'Lockheed Martin','Brazil','2019-01-10',5,1000000.00),(2,'Northrop Grumman','Egypt','2020-02-15',3,1500000.00),(3,'Lockheed Martin','Colombia','2020-03-20',7,800000.00),(4,'Boeing','Argentina','2019-05-12',6,900000.00),(5,'Boeing','Venezuela','2020-07-01',4,1200000.00);
SELECT SUM(Quantity * UnitPrice) FROM MilitaryEquipmentSales WHERE Manufacturer = 'Boeing' AND DestinationCountry LIKE 'South America%' AND YEAR(SaleDate) IN (2019, 2020);
Determine the 3-month sales growth rate for each product category in 2022, with a 3-month trailing average.
CREATE TABLE product_sales (id INT,product_category VARCHAR(255),sale_date DATE,sales_volume INT);
SELECT product_category, sale_date, (sales_volume - LAG(sales_volume, 3) OVER (PARTITION BY product_category ORDER BY sale_date)) * 100.0 / LAG(sales_volume, 3) OVER (PARTITION BY product_category ORDER BY sale_date) as three_month_sales_growth_rate FROM product_sales WHERE sale_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY product_category, sale_date ORDER BY sale_date;
What is the maximum number of crimes committed in a single day for each crime type in the past year?
CREATE TABLE crimes (crime_id INT,crime_type VARCHAR(255),committed_date DATE); INSERT INTO crimes (crime_id,crime_type,committed_date) VALUES (1,'Theft','2022-01-01'),(2,'Assault','2022-01-02'),(3,'Theft','2022-01-03'),(4,'Vandalism','2022-01-04'),(5,'Theft','2022-01-05');
SELECT c.crime_type, MAX(COUNT(c.crime_id)) FROM crimes c WHERE c.committed_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY c.crime_type;
What is the minimum cost of military equipment maintenance for South Korea?
CREATE TABLE military_equipment_maintenance (id INT,country VARCHAR(50),cost FLOAT); INSERT INTO military_equipment_maintenance (id,country,cost) VALUES (1,'South Korea',550000),(2,'South Korea',600000),(3,'South Korea',575000);
SELECT MIN(cost) FROM military_equipment_maintenance WHERE country = 'South Korea';
How many dispensaries are there in the state of Oregon?
CREATE TABLE dispensaries (id INT,city VARCHAR(50),state VARCHAR(50),count INT); INSERT INTO dispensaries (id,city,state,count) VALUES (1,'Denver','Colorado',100),(2,'Los Angeles','California',200),(3,'Portland','Oregon',150);
SELECT SUM(count) FROM dispensaries WHERE state = 'Oregon';
List all volunteers who have not participated in any capacity building activities in the last 6 months.
CREATE TABLE volunteers (id INT,name TEXT); INSERT INTO volunteers (id,name) VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Alice Johnson'),(4,'Bob Williams'); CREATE TABLE capacity_building (volunteer_id INT,activity_date DATE); INSERT INTO capacity_building (volunteer_id,activity_date) VALUES (1,'2021-05-12'),(2,'2022-03-15'),(3,'2021-12-28'),(1,'2020-08-07'),(4,'2021-01-02');
SELECT v.name FROM volunteers v LEFT JOIN capacity_building cb ON v.id = cb.volunteer_id WHERE cb.activity_date IS NULL OR cb.activity_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
What is the total number of animals in the "animal_preservation_programs" view that require habitat restoration?
CREATE VIEW animal_preservation_programs AS SELECT 'Penguin' AS species,'Habitat Restoration' AS preservation_need FROM penguins UNION ALL SELECT 'Turtle' AS species,'Habitat Restoration' AS preservation_need FROM turtles;
SELECT COUNT(*) FROM animal_preservation_programs WHERE preservation_need = 'Habitat Restoration';
Insert a new defense contract for 'ACME Inc.' in 'Q2 2022'
CREATE TABLE defense_contracts (company VARCHAR(255),quarter VARCHAR(10),value DECIMAL(10,2));
INSERT INTO defense_contracts (company, quarter, value) VALUES ('ACME Inc.', 'Q2 2022', 500000.00);
How many units of each sustainable material are sourced by textile suppliers?
CREATE TABLE TextileSuppliers (SupplierID INT,SupplierName VARCHAR(50),SustainableMaterial VARCHAR(50)); CREATE TABLE MaterialSourcing (SupplierID INT,Material VARCHAR(50),Units INT);
SELECT TS.SustainableMaterial, SUM(MS.Units) AS TotalUnitsSourced FROM TextileSuppliers TS INNER JOIN MaterialSourcing MS ON TS.SupplierID = MS.SupplierID WHERE TS.SustainableMaterial IS NOT NULL GROUP BY TS.SustainableMaterial;
What is the total tonnage of all cargos in the 'cargos' table that were shipped to the 'New York' port?
CREATE TABLE cargos (id INT PRIMARY KEY,name VARCHAR(50),tonnage INT,destination VARCHAR(50));
SELECT SUM(tonnage) FROM cargos WHERE destination = 'New York';
What are the total monthly chemical waste quantities produced by each manufacturing plant in the year 2020?
CREATE TABLE manufacturing_plants (plant_id INT,plant_name VARCHAR(255)); INSERT INTO manufacturing_plants (plant_id,plant_name) VALUES (1,'Plant A'),(2,'Plant B'),(3,'Plant C'); CREATE TABLE waste_production (plant_id INT,date DATE,waste_quantity FLOAT); INSERT INTO waste_production (plant_id,date,waste_quantity) VALUES (1,'2020-01-01',120.5),(1,'2020-02-01',150.3),(2,'2020-01-01',80.7),(2,'2020-02-01',95.6),(3,'2020-01-01',175.2),(3,'2020-02-01',200.1);
SELECT plant_name, SUM(waste_quantity) AS total_waste_quantity FROM waste_production wp JOIN manufacturing_plants mp ON wp.plant_id = mp.plant_id WHERE EXTRACT(YEAR FROM wp.date) = 2020 GROUP BY plant_name;
What is the number of employees with at least 5 years of experience in the 'Employees' table?
CREATE TABLE Employees (id INT,name TEXT,experience INT);INSERT INTO Employees (id,name,experience) VALUES (1,'John Smith',7),(2,'Jane Doe',3),(3,'Mary Johnson',6),(4,'James Brown',10);
SELECT COUNT(*) FROM Employees WHERE experience >= 5;
What is the average production rate for a specific chemical in the past week?
CREATE TABLE Chemicals (id INT,name VARCHAR(255),production_rate FLOAT); CREATE TABLE Production (id INT,chemical_id INT,production_date DATE);
SELECT Chemicals.name, AVG(Chemicals.production_rate) as avg_production_rate FROM Chemicals INNER JOIN Production ON Chemicals.id = Production.chemical_id WHERE Chemicals.name = 'Propanol' AND Production.production_date >= DATEADD(week, -1, GETDATE()) GROUP BY Chemicals.name;
What is the number of public works projects completed per state in the last year?
CREATE TABLE projects_by_state (id INT,project_name VARCHAR(255),state VARCHAR(255),completion_year INT); INSERT INTO projects_by_state (id,project_name,state,completion_year) VALUES (1,'Highway Expansion','California',2021),(2,'Water Treatment Plant Upgrade','Texas',2021),(3,'Road Repair','New York',2021);
SELECT state, COUNT(*) as num_projects FROM projects_by_state WHERE completion_year = YEAR(DATEADD(year, -1, GETDATE())) GROUP BY state;
What is the minimum speed of electric vehicles manufactured in South Korea?
CREATE TABLE Vehicles (Id INT,Name VARCHAR(100),Type VARCHAR(50),MinSpeed INT,ManufacturingCountry VARCHAR(100)); INSERT INTO Vehicles (Id,Name,Type,MinSpeed,ManufacturingCountry) VALUES (8,'Hyundai Kona Electric','Electric',167,'South Korea');
SELECT MIN(MinSpeed) FROM Vehicles WHERE Type = 'Electric' AND ManufacturingCountry = 'South Korea';
What is the number of parole hearings and the percentage of parole grants for each racial group?
CREATE TABLE parole_hearings (id INT,race VARCHAR(50),parole_granted BOOLEAN,hearing_date DATE);
SELECT race, COUNT(*) number_of_hearings, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY NULL) AS percentage_granted FROM parole_hearings WHERE parole_granted = TRUE GROUP BY race;
What is the total number of accommodations provided to students who have not completed a support program?
CREATE TABLE accommodation_requests (student_id INT,accommodation_type VARCHAR(50),completed_support_program BOOLEAN); INSERT INTO accommodation_requests (student_id,accommodation_type,completed_support_program) VALUES (1,'Note Taker',FALSE),(2,'Wheelchair Access',FALSE);
SELECT COUNT(*) FROM accommodation_requests WHERE completed_support_program = FALSE;
What is the average monthly data usage for each mobile plan in the 'Telecom' schema?
CREATE TABLE Mobile_Plans (PlanID INT,PlanName VARCHAR(255),DataLimit INT,Price FLOAT); INSERT INTO Mobile_Plans (PlanID,PlanName,DataLimit,Price) VALUES (1,'Basic',2048,35.99),(2,'Premium',5120,59.99),(3,'Family',10240,89.99);
SELECT PlanName, AVG(DataLimit) as AvgDataUsage FROM Telecom.Mobile_Plans GROUP BY PlanName;
What is the total funding amount for biotech startups located in California?
CREATE SCHEMA biotech_startups; CREATE TABLE startup (startup_id INT,name VARCHAR(50),location VARCHAR(50),funding_amount DECIMAL(10,2)); INSERT INTO startup (startup_id,name,location,funding_amount) VALUES (1,'BioGen','California',15000000.00),(2,'GreenTech','Texas',12000000.00);
SELECT SUM(funding_amount) FROM biotech_startups.startup WHERE location = 'California';
What is the average mental health score of students in each school district, grouped by district and displayed in alphabetical order?
CREATE TABLE school_districts (district_id INT,district_name VARCHAR(255)); CREATE TABLE student_mental_health (student_id INT,district_id INT,mental_health_score INT); INSERT INTO school_districts (district_id,district_name) VALUES (1,'Downtown'),(2,'Uptown'); INSERT INTO student_mental_health (student_id,district_id,mental_health_score) VALUES (1,1,80),(2,1,70),(3,2,90),(4,2,60);
SELECT sd.district_name, AVG(smh.mental_health_score) as avg_score FROM school_districts sd JOIN student_mental_health smh ON sd.district_id = smh.district_id GROUP BY sd.district_name ORDER BY sd.district_name;
List the number of infectious disease cases in New York by type.
CREATE TABLE infectious_diseases (id INT,case_type TEXT,location TEXT); INSERT INTO infectious_diseases (id,case_type,location) VALUES (1,'Tuberculosis','New York'); INSERT INTO infectious_diseases (id,case_type,location) VALUES (2,'HIV','New York');
SELECT case_type, COUNT(*) FROM infectious_diseases WHERE location = 'New York' GROUP BY case_type;
Get the maximum number of posts per day in Nigeria in January 2022.
CREATE TABLE if not exists daily_posts (post_id INT,user_id INT,country VARCHAR(50),posts_count INT,day INT,month INT,year INT); INSERT INTO daily_posts (post_id,user_id,country,posts_count,day,month,year) VALUES (1,1,'Nigeria',20,1,1,2022),(2,2,'Nigeria',30,2,1,2022);
SELECT country, MAX(posts_count) FROM daily_posts WHERE country = 'Nigeria' AND month = 1 AND year = 2022 GROUP BY country;
Count the number of unique programs held in 'LA'.
CREATE TABLE programs (id INT,city TEXT,program TEXT); INSERT INTO programs (id,city,program) VALUES (1,'NYC','Green City'); INSERT INTO programs (id,city,program) VALUES (2,'LA','Feeding America'); INSERT INTO programs (id,city,program) VALUES (3,'LA','Climate Action');
SELECT COUNT(DISTINCT program) FROM programs WHERE city = 'LA';
What is the total sales revenue for each drug, ranked by the highest sales revenue first, for the first quarter of 2022?
CREATE TABLE sales_revenue_q1_2022 (sales_revenue_id INT,drug_name VARCHAR(255),quarter_year VARCHAR(255),sales_revenue DECIMAL(10,2)); INSERT INTO sales_revenue_q1_2022 (sales_revenue_id,drug_name,quarter_year,sales_revenue) VALUES (1,'DrugV','Q1 2022',40000),(2,'DrugW','Q1 2022',35000),(3,'DrugX','Q1 2022',45000),(4,'DrugV','Q1 2022',42000),(5,'DrugW','Q1 2022',38000),(6,'DrugX','Q1 2022',48000);
SELECT drug_name, SUM(sales_revenue) as total_sales_revenue FROM sales_revenue_q1_2022 WHERE quarter_year = 'Q1 2022' GROUP BY drug_name ORDER BY total_sales_revenue DESC;
What is the percentage of eco-friendly properties out of the total number of properties?
CREATE TABLE property_counts (id INT PRIMARY KEY,community_type VARCHAR(255),count INT); INSERT INTO property_counts (id,community_type,count) VALUES (1,'eco-friendly',250),(2,'standard',1000);
SELECT 100.0 * eco_friendly_count / (eco_friendly_count + standard_count) AS percentage FROM (SELECT SUM(count) AS eco_friendly_count FROM property_counts WHERE community_type = 'eco-friendly') AS ef JOIN (SELECT SUM(count) AS standard_count FROM property_counts WHERE community_type = 'standard') AS st ON 1=1;
What is the total training cost for employees in the HR department?
CREATE TABLE trainings (id INT,employee_id INT,training_name VARCHAR(50),cost FLOAT,training_year INT); INSERT INTO trainings (id,employee_id,training_name,cost,training_year) VALUES (1,1,'Data Science',2000.00,2021),(2,1,'Cybersecurity',3000.00,2021),(3,6,'IT Fundamentals',1500.00,2021),(4,2,'Diversity Training',1000.00,2021),(5,2,'Inclusion Training',1000.00,2021),(6,3,'HR Onboarding',500.00,2021);
SELECT SUM(cost) FROM trainings WHERE employee_id IN (SELECT id FROM employees WHERE department = 'HR') AND training_year = 2021;
What is the total number of attendees for events held in each city, in the past year, broken down by event type?
CREATE TABLE events (event_id INT,event_location VARCHAR(50),event_date DATE,event_type VARCHAR(20),attendees INT); INSERT INTO events (event_id,event_location,event_date,event_type,attendees) VALUES (1,'New York-Manhattan','2021-06-01','Concert',1500); INSERT INTO events (event_id,event_location,event_date,event_type,attendees) VALUES (2,'Los Angeles-Downtown','2021-10-15','Theater',800); INSERT INTO events (event_id,event_location,event_date,event_type,attendees) VALUES (3,'Paris-Eiffel Tower','2021-02-20','Exhibition',1200);
SELECT SUBSTRING_INDEX(event_location, '-', 1) as city, event_type, SUM(attendees) as total_attendees FROM events WHERE event_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY city, event_type;
Identify the total number of virtual reality (VR) games designed for PC and console platforms, and list the game names.
CREATE TABLE GameDesign (GameID INT,GameName VARCHAR(20),Platform VARCHAR(10),VR BIT);
SELECT Platform, GameName FROM GameDesign WHERE Platform IN ('PC', 'Console') AND VR = 1;
What is the total number of art pieces in the museum collection created by female artists?
CREATE TABLE ArtPieces (ArtPieceID INT,Name TEXT,Artist TEXT,YearAdded INT); INSERT INTO ArtPieces (ArtPieceID,Name,Artist,YearAdded) VALUES (1,'Starry Night','Vincent van Gogh',1889); INSERT INTO ArtPieces (ArtPieceID,Name,Artist,YearAdded) VALUES (2,'The Persistence of Memory','Salvador Dalí',1931); INSERT INTO ArtPieces (ArtPieceID,Name,Artist,YearAdded) VALUES (3,'Guernica','Pablo Picasso',1937); INSERT INTO ArtPieces (ArtPieceID,Name,Artist,YearAdded) VALUES (4,'The Starry Night Over the Rhone','Françoise Nielly',1888); INSERT INTO ArtPieces (ArtPieceID,Name,Artist,YearAdded) VALUES (5,'Girl with a Pearl Earring','Johannes Vermeer',1665);
SELECT COUNT(*) FROM ArtPieces WHERE Artist IN ('Françoise Nielly', 'Georgia O’Keeffe', 'Agnes Martin', 'Yayoi Kusama', 'Marina Abramović', 'Bridget Riley');
Find the total biomass of fish species in Indian aquaculture farms for the year 2020.
CREATE TABLE Indian_Aquaculture_Farms (id INT,biomass FLOAT,year INT,species VARCHAR(20)); INSERT INTO Indian_Aquaculture_Farms (id,biomass,year,species) VALUES (1,150.2,2020,'Catla'); INSERT INTO Indian_Aquaculture_Farms (id,biomass,year,species) VALUES (2,120.5,2020,'Rohu');
SELECT SUM(biomass) FROM Indian_Aquaculture_Farms WHERE year = 2020 AND species IN ('Catla', 'Rohu');
What was the maximum cost of construction projects in the state of Texas in Q2 2021?
CREATE TABLE construction_projects (project_id INT,project_cost FLOAT,state VARCHAR(50),start_date DATE); INSERT INTO construction_projects (project_id,project_cost,state,start_date) VALUES (5,700000,'Texas','2021-04-01'); INSERT INTO construction_projects (project_id,project_cost,state,start_date) VALUES (6,800000,'Texas','2021-05-01');
SELECT MAX(project_cost) FROM construction_projects WHERE state = 'Texas' AND QUARTER(start_date) = 2;
What is the total fare for all bus trips in Berlin with a bike rack?
CREATE TABLE bus_trips (trip_id INT,has_bike_rack BOOLEAN,fare DECIMAL(10,2),city VARCHAR(50)); INSERT INTO bus_trips (trip_id,has_bike_rack,fare,city) VALUES (1,true,2.50,'Berlin'),(2,false,2.00,'Berlin'),(3,true,3.00,'Berlin');
SELECT SUM(fare) FROM bus_trips WHERE has_bike_rack = true AND city = 'Berlin';
What is the daily ridership of metro systems in Seoul and Busan?
CREATE TABLE SKMetroSystems (id INT,date DATE,city VARCHAR(20),ridership INT);
SELECT city, SUM(ridership) FROM SKMetroSystems WHERE date = '2022-03-01' GROUP BY city;
What is the total revenue of products that are ethically sourced and have a circular supply chain?
CREATE TABLE products (product_id INT,is_ethically_sourced BOOLEAN,has_circular_supply_chain BOOLEAN,revenue DECIMAL(10,2));
SELECT SUM(revenue) FROM products WHERE is_ethically_sourced = TRUE AND has_circular_supply_chain = TRUE;
What is the average price of organic cotton products by country?
CREATE TABLE OrganicCottonProducts (product_id INT,product_name VARCHAR(255),price DECIMAL(5,2),country VARCHAR(255)); INSERT INTO OrganicCottonProducts (product_id,product_name,price,country) VALUES (1,'Organic Cotton T-Shirt',20.99,'USA'),(2,'Organic Cotton Pants',45.99,'Canada'),(3,'Organic Cotton Dress',34.99,'Mexico');
SELECT country, AVG(price) as avg_price FROM OrganicCottonProducts GROUP BY country;
What is the total number of articles published per month in a specific language?
CREATE TABLE Dates (id INT PRIMARY KEY,date DATE); INSERT INTO Dates (id,date) VALUES (1,'2022-01-01'),(2,'2022-02-01'),(3,'2022-03-01'); CREATE TABLE Articles (id INT PRIMARY KEY,title TEXT,language_id INT,date_id INT,FOREIGN KEY (language_id) REFERENCES Languages(id),FOREIGN KEY (date_id) REFERENCES Dates(id)); INSERT INTO Articles (id,title,language_id,date_id) VALUES (1,'Article 1',1,1),(2,'Article 2',2,2),(3,'Article 3',1,3);
SELECT l.language, DATE_FORMAT(d.date, '%Y-%m') as month, COUNT(a.id) as num_articles FROM Articles a JOIN Languages l ON a.language_id = l.id JOIN Dates d ON a.date_id = d.id GROUP BY l.language, month;
What is the distribution of financial wellbeing scores for customers in Ontario?
CREATE TABLE customers (customer_id INT,name VARCHAR(255),province VARCHAR(255),financial_wellbeing_score INT);
SELECT province, COUNT(*) as count, MIN(financial_wellbeing_score) as min_score, AVG(financial_wellbeing_score) as avg_score, MAX(financial_wellbeing_score) as max_score FROM customers WHERE province = 'Ontario' GROUP BY province;
What is the average cost of projects in the 'transportation' table in 'Chicago'?
CREATE TABLE transportation (id INT,project_name VARCHAR(50),location VARCHAR(50),cost FLOAT); INSERT INTO transportation (id,project_name,location,cost) VALUES (1,'Bridge','Los Angeles',3000000); INSERT INTO transportation (id,project_name,location,cost) VALUES (2,'Highway','Chicago',12000000);
SELECT AVG(cost) FROM transportation WHERE location = 'Chicago';
What is the number of green infrastructure projects completed in 2022 for each zone?
CREATE TABLE GreenInfrastructure (id INT,zone VARCHAR(20),year INT,completed INT); INSERT INTO GreenInfrastructure (id,zone,year,completed) VALUES (1,'Central',2022,1),(2,'West',2021,1),(3,'East',2022,1);
SELECT zone, COUNT(*) as num_projects FROM GreenInfrastructure WHERE year = 2022 GROUP BY zone;
Create a view 'fan_gender_v' that displays the gender distribution of fans in 'fan_data' table
CREATE TABLE fan_data (fan_id INT,age INT,gender VARCHAR(10),city VARCHAR(50),state VARCHAR(20),country VARCHAR(50)); INSERT INTO fan_data (fan_id,age,gender,city,state,country) VALUES (1,22,'Male','New York','NY','USA'); INSERT INTO fan_data (fan_id,age,gender,city,state,country) VALUES (2,28,'Female','Los Angeles','CA','USA');
CREATE VIEW fan_gender_v AS SELECT gender, COUNT(*) AS fan_count FROM fan_data GROUP BY gender;
Show the number of unique players who played in each game
CREATE TABLE GameEvents (PlayerID INT,GameID INT,EventType VARCHAR(20));
SELECT GameID, COUNT(DISTINCT PlayerID) as UniquePlayers FROM GameEvents GROUP BY GameID;
Find the unique offenses reported in hate crimes in Texas and New York in 2021.
CREATE TABLE hate_crimes_tx (offense VARCHAR(50),year INT); INSERT INTO hate_crimes_tx VALUES ('Assault',2021),('Vandalism',2021),('Harassment',2021); CREATE TABLE hate_crimes_ny (offense VARCHAR(50),year INT); INSERT INTO hate_crimes_ny VALUES ('Assault',2021),('Murder',2021),('Robbery',2021);
SELECT DISTINCT offense FROM hate_crimes_tx WHERE year = 2021 UNION ALL SELECT DISTINCT offense FROM hate_crimes_ny WHERE year = 2021;
What is the total number of tickets sold for baseball games in the 'Central Division'?
CREATE TABLE tickets_sold (ticket_id INT,game_type VARCHAR(50),division VARCHAR(50),tickets_sold INT); INSERT INTO tickets_sold (ticket_id,game_type,division,tickets_sold) VALUES (1,'Basketball','Atlantic Division',500),(2,'Football','Atlantic Division',700),(3,'Basketball','Atlantic Division',600),(4,'Hockey','Central Division',800),(5,'Basketball','Atlantic Division',900),(6,'Soccer','Southern Division',400),(7,'Baseball','Central Division',300),(8,'Baseball','Central Division',500),(9,'Baseball','Central Division',400),(10,'Basketball','Pacific Division',600);
SELECT SUM(tickets_sold) FROM tickets_sold WHERE game_type = 'Baseball' AND division = 'Central Division';
What is the minimum duration of defense projects with a cost less than 3.5 million?
CREATE TABLE defense_projects(project_id INT,project_name VARCHAR(50),duration INT,cost FLOAT); INSERT INTO defense_projects VALUES (1,'Project A',36,5000000),(2,'Project B',24,4000000),(3,'Project C',18,3000000);
SELECT MIN(duration) FROM defense_projects WHERE cost < 3500000;
What is the total funding for AI projects that address accessibility?
CREATE TABLE ai_projects (project_id INT,project_name VARCHAR(20),project_domain VARCHAR(15),funding FLOAT); INSERT INTO ai_projects VALUES (1,'AI for Climate','climate change',100000),(2,'AI for Health','healthcare',200000),(3,'AI for Disaster','disaster management',150000);
SELECT SUM(funding) FROM ai_projects WHERE project_domain = 'accessibility';
List all genetic research studies related to plant genomics.
CREATE SCHEMA if not exists genetics;CREATE TABLE if not exists genetics.research_studies(id INT,study_name TEXT,category TEXT,sub_category TEXT,description TEXT);INSERT INTO genetics.research_studies(id,study_name,category,sub_category,description) VALUES (1,'Genome Sequencing of Rice','Plant Genomics','Rice Genome','Detailed description of the study...'),(2,'Genetic Diversity of Trees','Plant Genomics','Trees Genome','Detailed description of the study...'),(3,'Bacterial Genomics of Plant Rhizospheres','Microbial Genomics','Plant Bacteria','Detailed description of the study...');
SELECT * FROM genetics.research_studies WHERE category = 'Plant Genomics';
List the names of African countries with more than 5 rural hospitals.
CREATE TABLE hospitals (hospital_id INT,country VARCHAR(20),num_beds INT); INSERT INTO hospitals (hospital_id,country,num_beds) VALUES (1,'Kenya',50),(2,'Tanzania',75),(3,'Uganda',60);
SELECT country FROM hospitals WHERE country IN ('Kenya', 'Tanzania', 'Uganda') GROUP BY country HAVING COUNT(*) > 5;
How many public parks are there in urban areas with a population greater than 500000?
CREATE TABLE Parks (Location VARCHAR(25),Type VARCHAR(25),Population INT); INSERT INTO Parks (Location,Type,Population) VALUES ('City A','Urban',700000),('City B','Urban',600000),('City C','Rural',400000);
SELECT COUNT(*) FROM Parks WHERE Type = 'Urban' AND Population > 500000;
Identify the top 5 cosmetic products with the highest sales volume that contain 'lavender' as an ingredient.
CREATE TABLE ingredients (ingredient_id INT,product_id INT,ingredient_name VARCHAR(50)); INSERT INTO ingredients (ingredient_id,product_id,ingredient_name) VALUES (1,1,'aloe vera'),(2,2,'lavender'),(3,3,'tea tree'); CREATE TABLE product_sales (product_id INT,sales INT); INSERT INTO product_sales (product_id,sales) VALUES (1,6000),(2,9000),(3,4000),(4,8000),(5,7000);
SELECT products.product_name, product_sales.sales FROM ingredients JOIN products ON ingredients.product_id = products.product_id JOIN product_sales ON products.product_id = product_sales.product_id WHERE ingredients.ingredient_name = 'lavender' ORDER BY sales DESC LIMIT 5;
Which departments have the highest and lowest number of open data initiatives?
CREATE TABLE dept_open_data (dept_name TEXT,initiative_count INT);
SELECT dept_name, initiative_count FROM (SELECT dept_name, initiative_count, ROW_NUMBER() OVER (ORDER BY initiative_count DESC) AS high_dept, ROW_NUMBER() OVER (ORDER BY initiative_count ASC) AS low_dept FROM dept_open_data) subquery WHERE high_dept = 1 OR low_dept = 1;
What is the maximum number of albums released by an artist in the electronic genre?
CREATE TABLE electronic_artists (id INT,name TEXT,genre TEXT,albums INT); INSERT INTO electronic_artists (id,name,genre,albums) VALUES (1,'Artist1','Electronic',10),(2,'Artist2','Pop',8),(3,'Artist3','Electronic',12);
SELECT MAX(albums) FROM electronic_artists WHERE genre = 'Electronic';
Which mobile subscribers have a higher data usage than their broadband usage?
CREATE TABLE mobile_subscribers(id INT,monthly_data_usage DECIMAL(5,2)); CREATE TABLE broadband_subscribers(id INT,monthly_data_usage DECIMAL(5,2));
SELECT m.id FROM mobile_subscribers m INNER JOIN broadband_subscribers b ON m.id = b.id WHERE m.monthly_data_usage > b.monthly_data_usage;
What is the average mental health score of students, in total?
CREATE TABLE student_mental_health (student_id INT,mental_health_score INT,gender VARCHAR(255)); CREATE TABLE districts (district_id INT,district_name VARCHAR(255));
SELECT AVG(s.mental_health_score) FROM student_mental_health s;
Update the end_date of the 'Pacific Garbage Patch' cleanup project to 2025-01-01
CREATE TABLE cleanup_projects (project_name TEXT,start_date DATE,end_date DATE); INSERT INTO cleanup_projects (project_name,start_date,end_date) VALUES ('Pacific Garbage Patch','2022-01-01','2023-01-01');
UPDATE cleanup_projects SET end_date = '2025-01-01' WHERE project_name = 'Pacific Garbage Patch';
Calculate the percentage change in deforestation rates in the Amazon rainforest from 2000 to 2020, ranked by the greatest change?
CREATE TABLE deforestation (year INT,region VARCHAR(50),deforestation_rate FLOAT); INSERT INTO deforestation (year,region,deforestation_rate) VALUES (2000,'Amazon',0.7),(2001,'Amazon',0.75),(2000,'Atlantic_Forest',1.2),(2001,'Atlantic_Forest',1.25);
SELECT region, (LEAD(deforestation_rate, 1, 0) OVER (ORDER BY year) - deforestation_rate) / ABS(LEAD(deforestation_rate, 1, 0) OVER (ORDER BY year)) * 100 AS pct_change, RANK() OVER (ORDER BY (LEAD(deforestation_rate, 1, 0) OVER (ORDER BY year) - deforestation_rate) DESC) AS rank FROM deforestation WHERE region = 'Amazon' AND year BETWEEN 2000 AND 2020;
What is the average delivery time for orders shipped to Germany?
CREATE TABLE orders (id INT,order_value DECIMAL(10,2),delivery_time INT,country VARCHAR(50)); INSERT INTO orders (id,order_value,delivery_time,country) VALUES (1,150.50,5,'Germany'),(2,75.20,3,'Canada'),(3,225.00,7,'Germany');
SELECT AVG(delivery_time) FROM orders WHERE country = 'Germany';
How many tech startups were founded by individuals from underrepresented communities in the last 5 years?
CREATE TABLE startups (id INT,name TEXT,industry TEXT,founding_date DATE,founders TEXT); INSERT INTO startups (id,name,industry,founding_date,founders) VALUES (1,'TechMates','Technology','2018-01-01','Underrepresented');
SELECT COUNT(*) FROM startups WHERE industry = 'Technology' AND founding_date BETWEEN '2016-01-01' AND '2021-12-31' AND founders = 'Underrepresented';
What is the total quantity of indica strain cannabis sold by each dispensary in the state of Washington?
CREATE TABLE StrainSalesData (DispensaryName VARCHAR(50),State VARCHAR(20),Strain VARCHAR(20),QuantitySold INT); INSERT INTO StrainSalesData (DispensaryName,State,Strain,QuantitySold) VALUES ('Green Earth Dispensary','Washington','Indica',300),('Buds and Beyond','Washington','Indica',400),('The Healing Center','Washington','Indica',500),('Elevated Roots','Colorado','Sativa',600),('Emerald Fields','Washington','Hybrid',700);
SELECT DispensaryName, SUM(QuantitySold) FROM StrainSalesData WHERE State = 'Washington' AND Strain = 'Indica' GROUP BY DispensaryName;
Update the name of the member with member_id 2 to 'Claire Johnson'
CREATE TABLE members (member_id INT,name TEXT,age INT,gender TEXT); INSERT INTO members (member_id,name,age,gender) VALUES (1,'John Doe',30,'Male'),(2,'Jane Doe',28,'Female'),(3,'Alex Brown',33,'Non-binary');
UPDATE members SET name = 'Claire Johnson' WHERE member_id = 2;
Find the number of crimes committed in each neighborhood within a 1-mile radius of city hall.
CREATE TABLE crimes (id SERIAL PRIMARY KEY,crime_type VARCHAR(255),location POINT); CREATE TABLE neighborhoods (id SERIAL PRIMARY KEY,name VARCHAR(255),location POINT,radius INTEGER); INSERT INTO neighborhoods (name,location,radius) VALUES ('Downtown','(40.7128,-74.0060)',1); INSERT INTO crimes (crime_type,location) VALUES ('Larceny','(40.7128,-74.0060)'),('Vandalism','(40.7150,-74.0050)');
SELECT c.crime_type, COUNT(c.id) as total_crimes FROM crimes c, neighborhoods n WHERE ST_DWithin(c.location, n.location, n.radius) GROUP BY c.crime_type;
List all unique cause areas that have never had a donation.
CREATE TABLE donations (id INT,donor_size VARCHAR(10),cause_area VARCHAR(20),amount INT); INSERT INTO donations (id,donor_size,cause_area,amount) VALUES (1,'large','education',5500),(2,'small','health',4000); CREATE TABLE volunteers (id INT,name VARCHAR(30),cause_area VARCHAR(20)); INSERT INTO volunteers (id,name,cause_area) VALUES (1,'Bob','disaster relief'),(2,'Alice','housing'),(3,'Charlie','education');
SELECT cause_area FROM volunteers WHERE cause_area NOT IN (SELECT cause_area FROM donations);
Who are the regulators for the 'Securities and Exchange Commission Act' and 'Digital Asset Business Act'?
CREATE TABLE Regulatory_Frameworks (Framework_Name VARCHAR(100),Country VARCHAR(50),Regulatory_Body VARCHAR(100)); INSERT INTO Regulatory_Frameworks (Framework_Name,Country,Regulatory_Body) VALUES ('Digital Asset Business Act','Bermuda','Bermuda Monetary Authority'); INSERT INTO Regulatory_Frameworks (Framework_Name,Country,Regulatory_Body) VALUES ('Securities and Exchange Commission Act','United States','Securities and Exchange Commission');
SELECT Regulatory_Body FROM Regulatory_Frameworks WHERE Framework_Name IN ('Securities and Exchange Commission Act', 'Digital Asset Business Act')
How many unique streaming platforms distribute music from artists based in Canada?
CREATE TABLE artists (id INT,name TEXT,country TEXT); CREATE TABLE streaming_platforms (id INT,platform TEXT); CREATE TABLE distribution (artist_id INT,platform_id INT); INSERT INTO artists (id,name,country) VALUES (1,'Justin Bieber','Canada'); INSERT INTO streaming_platforms (id,platform) VALUES (1,'Spotify'),(2,'Apple Music'); INSERT INTO distribution (artist_id,platform_id) VALUES (1,1),(1,2);
SELECT COUNT(DISTINCT platform) FROM distribution JOIN artists ON distribution.artist_id = artists.id JOIN streaming_platforms ON distribution.platform_id = streaming_platforms.id WHERE artists.country = 'Canada';
What is the total number of wells, in the Barnett Shale, that were drilled by Operator G and have a production rate of over 1500 barrels per day, for the year 2020?
CREATE TABLE DrillingProduction (WellID INT,Location VARCHAR(20),DrillingOperator VARCHAR(20),ProductionYear INT,ProductionRate INT); INSERT INTO DrillingProduction (WellID,Location,DrillingOperator,ProductionYear,ProductionRate) VALUES (1,'Barnett Shale','Operator G',2020,1600),(2,'Barnett Shale','Operator H',2019,1200),(3,'Eagle Ford Shale','Operator G',2021,1400);
SELECT COUNT(*) FROM DrillingProduction WHERE Location = 'Barnett Shale' AND DrillingOperator = 'Operator G' AND ProductionYear = 2020 AND ProductionRate > 1500;
Insert a new artifact 'Roman Coin' with ArtifactID 4, type 'Coin', quantity 20, and belonging to site 'Pompeii' (SiteID 3).
CREATE TABLE ExcavationSites (SiteID INT,SiteName TEXT,Country TEXT); CREATE TABLE Artifacts (ArtifactID INT,SiteID INT,ArtifactName TEXT,ArtifactType TEXT,Quantity INT);
INSERT INTO Artifacts (ArtifactID, SiteID, ArtifactName, ArtifactType, Quantity) VALUES (4, 3, 'Roman Coin', 'Coin', 20);
What is the average age of male and female astronauts who have participated in space missions?
CREATE TABLE Astronauts (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),nationality VARCHAR(50),mission_id INT); INSERT INTO Astronauts (id,name,age,gender,nationality,mission_id) VALUES (1,'Neil Armstrong',38,'Male','American',1),(2,'Buzz Aldrin',36,'Male','American',1),(3,'Sally Ride',32,'Female','American',2);
SELECT gender, AVG(age) as average_age FROM Astronauts WHERE mission_id IS NOT NULL GROUP BY gender;
What is the average age of female patients diagnosed with diabetes in rural Texas clinics, grouped by county?
CREATE TABLE patients (id INT,name TEXT,age INT,gender TEXT,diagnosis TEXT,clinic_location TEXT); INSERT INTO patients (id,name,age,gender,diagnosis,clinic_location) VALUES (1,'Jane Doe',55,'Female','Diabetes','Rural Texas Clinic 1'); CREATE TABLE clinics (id INT,name TEXT,location TEXT,capacity INT);
SELECT clinic_location, AVG(age) as avg_age FROM patients JOIN clinics ON patients.clinic_location = clinics.name WHERE diagnosis = 'Diabetes' AND gender = 'Female' GROUP BY clinic_location;
What is the total number of NFT transactions for creators from the United States?
CREATE TABLE creators (id INT,name TEXT,country TEXT); INSERT INTO creators (id,name,country) VALUES (1,'Alice','USA'),(2,'Bob','Canada'); CREATE TABLE nft_transactions (id INT,creator_id INT,transaction_type TEXT); INSERT INTO nft_transactions (id,creator_id,transaction_type) VALUES (1,1,'sale'),(2,1,'mint'),(3,2,'sale');
SELECT COUNT(*) FROM nft_transactions nt INNER JOIN creators c ON nt.creator_id = c.id WHERE c.country = 'USA';
What is the average expenditure per month on community development projects in Africa, broken down by project category?
CREATE TABLE community_development (project_id INT,ngo_id INT,start_date DATE,end_date DATE,category VARCHAR(255),expenditure DECIMAL(10,2)); INSERT INTO community_development VALUES (1,1,'2020-01-01','2020-12-31','Agriculture',15000); INSERT INTO community_development VALUES (2,1,'2020-01-01','2020-12-31','Education',20000); INSERT INTO community_development VALUES (3,2,'2020-01-01','2020-12-31','Healthcare',30000);
SELECT category, AVG(expenditure / (DATEDIFF(end_date, start_date) / 30)) as avg_monthly_expenditure FROM community_development WHERE ngo.region = 'Africa' GROUP BY category;
How many times has each dish been ordered in the last week, excluding orders for less than 2 servings?
CREATE TABLE dish_orders (id INT,dish_name TEXT,quantity INT,order_date DATE);
SELECT dish_name, SUM(quantity) FROM dish_orders WHERE order_date >= DATE(NOW()) - INTERVAL 1 WEEK GROUP BY dish_name HAVING SUM(quantity) >= 2;
Update the name of satellite with satellite_id 3 to 'Vanguard 1R'.
CREATE TABLE satellites (satellite_id INT,name VARCHAR(100),launch_date DATE); INSERT INTO satellites (satellite_id,name,launch_date) VALUES (1,'Sputnik 1','1957-10-04'); INSERT INTO satellites (satellite_id,name,launch_date) VALUES (2,'Explorer 1','1958-01-31'); INSERT INTO satellites (satellite_id,name,launch_date) VALUES (3,'Vanguard 1','1958-03-17'); INSERT INTO satellites (satellite_id,name,launch_date) VALUES (4,'Beep 1 (Explorer 3)','1958-03-26'); INSERT INTO satellites (satellite_id,name,launch_date) VALUES (5,'Sputnik 2','1957-11-03');
UPDATE satellites SET name = 'Vanguard 1R' WHERE satellite_id = 3;
Delete products in the products table that have not been manufactured in the last 5 years, based on the manufacturing_date column.
CREATE TABLE products (product_id INT,product_name VARCHAR(50),country_of_manufacture VARCHAR(50),manufacturing_date DATE); INSERT INTO products (product_id,product_name,country_of_manufacture,manufacturing_date) VALUES (1,'Eco Hoodie','China','2018-01-01'),(2,'Sustainable Shoes','Indonesia','2015-05-10'),(3,'Recycled Backpack','Vietnam','2020-08-25');
DELETE FROM products WHERE manufacturing_date < DATE_SUB(CURRENT_DATE(), INTERVAL 5 YEAR);
Which programs received the highest total donation amounts in 2022 from donors aged 18-35?
CREATE TABLE DonorAge (DonorID int,DonorAge int); INSERT INTO DonorAge (DonorID,DonorAge) VALUES (1,18); INSERT INTO DonorAge (DonorID,DonorAge) VALUES (2,35); CREATE TABLE DonationsByAge (DonationID int,DonorID int,DonationAmount int); INSERT INTO DonationsByAge (DonationID,DonorID,DonationAmount) VALUES (1,1,200); INSERT INTO DonationsByAge (DonationID,DonorID,DonationAmount) VALUES (2,2,300);
SELECT ProgramName, SUM(DonationAmount) as TotalDonation FROM DonationsByAge DBA JOIN DonorAge DA ON DBA.DonorID = DA.DonorID WHERE DonationDate BETWEEN '2022-01-01' AND '2022-12-31' AND DonorAge BETWEEN 18 AND 35 GROUP BY ProgramName ORDER BY TotalDonation DESC, ProgramName ASC;
What is the minimum salary in the Logistics department?
CREATE TABLE Employees (id INT,name VARCHAR(50),department VARCHAR(50),salary DECIMAL(10,2));
SELECT MIN(salary) FROM Employees WHERE department = 'Logistics';
What is the average distance (in kilometers) of all satellites from the Earth's surface, grouped by the launch year?
CREATE TABLE space_satellites (id INT,name VARCHAR(50),launch_year INT,avg_distance FLOAT);
SELECT launch_year, AVG(avg_distance) FROM space_satellites GROUP BY launch_year;
Find the number of distinct regions in 'habitat_preservation' table
CREATE TABLE habitat_preservation (id INT,region VARCHAR(50),budget DECIMAL(10,2));
SELECT COUNT(DISTINCT region) FROM habitat_preservation;
What is the number of employees by mine and gender?
CREATE TABLE mine (id INT,name VARCHAR(50),location VARCHAR(50)); CREATE TABLE employee (id INT,mine_id INT,gender VARCHAR(10),role VARCHAR(20),salary INT);
SELECT mine.name, employee.gender, COUNT(employee.id) FROM employee JOIN mine ON employee.mine_id = mine.id GROUP BY mine.name, employee.gender;
What is the average network investment per day for the past year?
CREATE TABLE network_investments (investment_id INT,investment_amount DECIMAL(10,2),investment_date DATE); INSERT INTO network_investments (investment_id,investment_amount,investment_date) VALUES (1,25000.00,'2021-12-25'),(2,30000.00,'2022-01-07'),(3,15000.00,'2022-02-01');
SELECT AVG(investment_amount) FROM network_investments WHERE investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);