instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the average health equity metric score for providers serving linguistically diverse communities?
CREATE TABLE HealthEquityMetrics (ProviderId INT,Score INT,Community VARCHAR(255)); INSERT INTO HealthEquityMetrics (ProviderId,Score,Community) VALUES (1,85,'Miami'); INSERT INTO HealthEquityMetrics (ProviderId,Score,Community) VALUES (2,90,'New York'); INSERT INTO HealthEquityMetrics (ProviderId,Score,Community) VALUES (3,80,'Los Angeles'); INSERT INTO HealthEquityMetrics (ProviderId,Score,Community) VALUES (4,95,'Toronto');
SELECT AVG(Score) FROM HealthEquityMetrics WHERE Community IN ('Miami', 'New York', 'Los Angeles');
What is the maximum number of technology for social good projects completed in a single quarter by organizations in North America?
CREATE TABLE Completed (id INT,name VARCHAR(50),organization VARCHAR(50),quarter INT,year INT,category VARCHAR(50)); INSERT INTO Completed (id,name,organization,quarter,year,category) VALUES (1,'AI for Accessibility','Equal Tech',1,2020,'Social Good'),(2,'Ethical AI Education','Tech Learning',2,2019,'Social Good'),(3,'Digital Divide Research','Global Connect',3,2021,'Social Good');
SELECT MAX(COUNT(*)) FROM Completed WHERE category = 'Social Good' GROUP BY year, quarter;
What is the total number of juvenile offenders in the justice_data schema's juvenile_offenders table who have been referred to restorative justice programs?
CREATE TABLE justice_data.juvenile_offenders (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),offense VARCHAR(50),restorative_justice_program BOOLEAN);
SELECT COUNT(*) FROM justice_data.juvenile_offenders WHERE restorative_justice_program = TRUE;
What are the total sales for each genre of music in the United States?
CREATE TABLE sales (sale_id INT,genre VARCHAR(255),country VARCHAR(255),sales_amount DECIMAL(10,2));
SELECT genre, SUM(sales_amount) FROM sales WHERE country = 'United States' GROUP BY genre;
Identify users who have mentioned 'data privacy' in their posts in the past week, and the number of likes for each post.
CREATE TABLE users (user_id INT,username VARCHAR(255)); CREATE TABLE posts (post_id INT,user_id INT,content TEXT,post_date DATE,likes INT);
SELECT u.username, p.post_id, p.content, p.post_date, p.likes FROM users u INNER JOIN posts p ON u.user_id = p.user_id WHERE p.content LIKE '%data privacy%' AND p.post_date >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK);
What's the average age of employees working in open-pit mines?
CREATE TABLE mine_workers (id INT,name VARCHAR(50),age INT,mine_type VARCHAR(20)); INSERT INTO mine_workers (id,name,age,mine_type) VALUES (1,'John Doe',35,'Open-pit'); INSERT INTO mine_workers (id,name,age,mine_type) VALUES (2,'Jane Smith',28,'Underground');
SELECT AVG(age) FROM mine_workers WHERE mine_type = 'Open-pit';
What is the total calorie intake from organic food items?
CREATE TABLE food_items (item_id INT,name VARCHAR(50),organic BOOLEAN,calories INT); INSERT INTO food_items (item_id,name,organic,calories) VALUES (1,'Apple',true,95),(2,'Broccoli',true,55),(3,'Chips',false,154),(4,'Soda',false,140);
SELECT SUM(calories) FROM food_items WHERE organic = true;
What is the average fare for bus routes that have a weekly maintenance cost above $500?
CREATE TABLE bus_routes (route_id INT,route_name TEXT,fare FLOAT,weekly_maintenance_cost FLOAT); INSERT INTO bus_routes (route_id,route_name,fare,weekly_maintenance_cost) VALUES (1,'Red Line',2.5,400),(2,'Green Line',3.0,600),(3,'Blue Line',2.0,550);
SELECT AVG(fare) FROM bus_routes WHERE weekly_maintenance_cost > 500;
What's the total resources depleted in the 'Coal' category?
CREATE TABLE mining_resources (id INT,name VARCHAR(50),category VARCHAR(50),total_resources_depleted DECIMAL(10,2)); INSERT INTO mining_resources (id,name,category,total_resources_depleted) VALUES (1,'Mining Operation 1','Coal',25000.00),(2,'Mining Operation 2','Coal',30000.00);
SELECT SUM(total_resources_depleted) FROM mining_resources WHERE category = 'Coal';
What is the average size in square feet of properties with co-ownership in Portland, OR?
CREATE TABLE co_ownership (property_id INT,size_sqft INT,city VARCHAR(50),state VARCHAR(50)); INSERT INTO co_ownership (property_id,size_sqft,city,state) VALUES (1,1200,'Portland','OR'); INSERT INTO co_ownership (property_id,size_sqft,city,state) VALUES (2,1500,'Portland','OR');
SELECT AVG(size_sqft) FROM co_ownership WHERE city = 'Portland' AND state = 'OR' AND property_id IN (SELECT property_id FROM co_ownership WHERE city = 'Portland' AND state = 'OR' GROUP BY property_id HAVING COUNT(*) > 1);
What is the average listing price per square foot for each neighborhood in San Francisco?
CREATE TABLE neighborhoods (name VARCHAR(255),city VARCHAR(255),state VARCHAR(255),country VARCHAR(255),PRIMARY KEY (name)); INSERT INTO neighborhoods (name,city,state,country) VALUES ('Bernal Heights','San Francisco','CA','USA');
SELECT name, AVG(listing_price/square_footage) as avg_price_per_sqft FROM real_estate_listings WHERE city = 'San Francisco' GROUP BY name ORDER BY avg_price_per_sqft DESC;
Insert data into ticket_sales table
CREATE TABLE ticket_sales (sale_id INT PRIMARY KEY,team_id INT,sale_date DATE,quantity INT);
INSERT INTO ticket_sales (sale_id, team_id, sale_date, quantity) VALUES (1, 101, '2022-02-15', 500);
What is the maximum safety score of a creative AI model developed by a for-profit organization?
CREATE TABLE model (model_id INT,name VARCHAR(50),organization_id INT,safety_score INT,creativity_score INT); INSERT INTO model VALUES (1,'ModelA',1,85,80),(2,'ModelB',2,90,85),(3,'ModelC',3,80,95),(4,'ModelD',1,92,88),(5,'ModelE',3,88,92); CREATE TABLE organization (organization_id INT,name VARCHAR(50),type VARCHAR(20)); INSERT INTO organization VALUES (1,'TechCo','for-profit'),(2,'AI Inc.','non-profit'),(3,'Alpha Corp.','for-profit');
SELECT MAX(model.safety_score) FROM model JOIN organization ON model.organization_id = organization.organization_id WHERE organization.type = 'for-profit' AND model.creativity_score >= 90;
What is the total number of hospital beds in rural hospitals of Connecticut that were built before 2010?
CREATE TABLE hospitals (id INT,name TEXT,location TEXT,beds INT,rural BOOLEAN,built DATE); INSERT INTO hospitals (id,name,location,beds,rural,built) VALUES (1,'Hospital A','Connecticut',150,true,'2005-01-01'),(2,'Hospital B','Connecticut',200,true,'2008-01-01');
SELECT SUM(beds) FROM hospitals WHERE location = 'Connecticut' AND rural = true AND built < '2010-01-01';
What is the total number of open data initiatives by department in the city of Toronto?
CREATE TABLE department (id INT,name VARCHAR(255)); INSERT INTO department (id,name) VALUES (1,'Parks'); INSERT INTO department (id,name) VALUES (2,'Transportation'); CREATE TABLE initiative (id INT,name VARCHAR(255),department_id INT,status VARCHAR(255)); INSERT INTO initiative (id,name,department_id,status) VALUES (1,'Bike Share',2,'open'); INSERT INTO initiative (id,name,department_id,status) VALUES (2,'Tree Inventory',1,'closed'); INSERT INTO initiative (id,name,department_id,status) VALUES (3,'Park Improvements',1,'open');
SELECT SUM(i.id) FROM initiative i JOIN department d ON i.department_id = d.id WHERE d.name = 'Toronto' AND i.status = 'open';
What is the average time to resolution for cases, by case type, in the last year?
CREATE TABLE case_resolutions (resolution_id INT,case_id INT,resolution_date DATE); INSERT INTO case_resolutions (resolution_id,case_id,resolution_date) VALUES (1,1,'2022-02-01'),(2,2,'2022-04-15'),(3,1,'2022-05-01');
SELECT cases.case_type, AVG(DATEDIFF(case_resolutions.resolution_date, cases.open_date)) as avg_time_to_resolution FROM cases INNER JOIN case_resolutions ON cases.case_id = case_resolutions.case_id WHERE cases.open_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY cases.case_type;
Delete the record for a financially vulnerable individual.
CREATE TABLE clients (id INT,financially_vulnerable BOOLEAN); INSERT INTO clients (id,financially_vulnerable) VALUES (1,true),(2,false),(3,true);
DELETE FROM clients WHERE financially_vulnerable = true;
What is the average home game attendance for each team in the 2020 season?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams (team_id,team_name) VALUES (1,'Bears'),(2,'Bills'); CREATE TABLE games (game_id INT,home_team_id INT,away_team_id INT,home_team_attendance INT); INSERT INTO games (game_id,home_team_id,away_team_id,home_team_attendance) VALUES (1,1,2,45000),(2,2,1,30000);
SELECT t.team_name, AVG(g.home_team_attendance) FROM games g JOIN teams t ON g.home_team_id = t.team_id GROUP BY t.team_name;
What is the average cost of manufacturing spacecrafts in the 'spacecraft_manufacturing' table?
CREATE TABLE spacecraft_manufacturing (id INT,spacecraft_name VARCHAR(50),cost INT); INSERT INTO spacecraft_manufacturing (id,spacecraft_name,cost) VALUES (1,'Aries',5000000),(2,'Atlas',7000000),(3,'Titan',9000000);
SELECT AVG(cost) FROM spacecraft_manufacturing;
What is the minimum water temperature for coldwater fish species in January?
CREATE TABLE fish_species (id INT,name VARCHAR(255),species_type VARCHAR(255)); INSERT INTO fish_species (id,name,species_type) VALUES (1,'Salmon','Coldwater'),(2,'Tilapia','Tropical'); CREATE TABLE temperature_data (id INT,fish_id INT,record_date DATE,water_temp DECIMAL(5,2)); INSERT INTO temperature_data (id,fish_id,record_date,water_temp) VALUES (1,1,'2022-01-01',5.2),(2,1,'2022-01-15',4.9),(3,2,'2022-01-01',25.1),(4,2,'2022-01-15',25.6);
SELECT MIN(water_temp) FROM temperature_data JOIN fish_species ON temperature_data.fish_id = fish_species.id WHERE fish_species.species_type = 'Coldwater' AND MONTH(record_date) = 1;
What is the total volume of timber produced by tree species with a carbon sequestration value greater than 30, grouped by tree type, in the mature_forest table?
CREATE TABLE mature_forest (id INT,tree_type VARCHAR(255),planted_date DATE,volume INT,tree_carbon_seq INT);
SELECT tree_type, SUM(volume) FROM mature_forest WHERE tree_carbon_seq > 30 GROUP BY tree_type;
Insert a new fashion trend 'Pleats' into the 'trends' table
CREATE TABLE trends (id INT PRIMARY KEY,trend_name VARCHAR(50));
INSERT INTO trends (id, trend_name) VALUES (2, 'Pleats');
Delete all records of refrigerator shipments to Mexico in December 2021 from the shipments table.
CREATE TABLE shipments (id INT,item_name VARCHAR(255),quantity INT,shipping_date DATE,origin_country VARCHAR(50),destination_country VARCHAR(50));
DELETE FROM shipments WHERE item_name = 'refrigerator' AND origin_country = 'USA' AND destination_country = 'Mexico' AND shipping_date BETWEEN '2021-12-01' AND '2021-12-31';
How many patients have been treated for depression in Utah?
CREATE TABLE condition_records (patient_id INT,condition VARCHAR(50)); INSERT INTO condition_records (patient_id,condition) VALUES (1,'Anxiety'),(2,'Depression'),(3,'PTSD'),(4,'Depression'),(5,'Depression'),(6,'Bipolar Disorder'),(7,'Anxiety'),(8,'Depression'); CREATE TABLE patient_location (patient_id INT,location VARCHAR(50)); INSERT INTO patient_location (patient_id,location) VALUES (1,'California'),(2,'Utah'),(3,'Texas'),(4,'Utah'),(5,'Utah'),(6,'Florida'),(7,'California'),(8,'Utah');
SELECT COUNT(DISTINCT patient_id) FROM condition_records JOIN patient_location ON condition_records.patient_id = patient_location.patient_id WHERE condition = 'Depression' AND location = 'Utah';
List all deep-sea expeditions and their dates in the Indian Ocean.
CREATE TABLE deep_sea_expeditions (name VARCHAR(255),ocean VARCHAR(255),date DATE); INSERT INTO deep_sea_expeditions (name,ocean,date) VALUES ('Challenger Expedition','Indian Ocean','1872-12-07'),('Galathea Expedition','Indian Ocean','1845-12-24');
SELECT name, date FROM deep_sea_expeditions WHERE ocean = 'Indian Ocean';
How many tourists visited each country in the last year?
CREATE TABLE tourists (tourist_id INT,name TEXT,country TEXT,visit_date DATE); INSERT INTO tourists (tourist_id,name,country,visit_date) VALUES (1,'John Doe','France','2022-01-01'),(2,'Jane Smith','Brazil','2022-02-01'),(3,'Minh Nguyen','Vietnam','2021-12-31'),(4,'Pierre Dupont','France','2022-01-01'),(5,'Emily Chen','Australia','2022-02-01');
SELECT country, COUNT(DISTINCT tourist_id) FROM tourists WHERE visit_date >= DATEADD(year, -1, GETDATE()) GROUP BY country;
Which industries in the United States have the highest workplace safety incident rate in the last quarter?
CREATE TABLE incidents (id INT,report_date DATE,industry TEXT,incident_count INT); INSERT INTO incidents (id,report_date,industry,incident_count) VALUES (1,'2022-03-01','Construction',15); INSERT INTO incidents (id,report_date,industry,incident_count) VALUES (2,'2022-04-01','Manufacturing',20);
SELECT industry, AVG(incident_count) as avg_incidents FROM incidents WHERE report_date >= DATE_TRUNC('quarter', NOW() - INTERVAL '1 quarter') GROUP BY industry ORDER BY avg_incidents DESC LIMIT 1;
Delete expired shipments from the supply_chain table.
CREATE TABLE supply_chain (id INTEGER,product_id VARCHAR(10),shipped_date DATE,expiration_date DATE);
DELETE FROM supply_chain WHERE shipped_date + INTERVAL '30 days' < CURRENT_DATE;
What is the total workout time for yoga workouts in the month of January?
CREATE TABLE Workouts (WorkoutID INT,WorkoutDate DATE,Duration INT,WorkoutType VARCHAR(20)); INSERT INTO Workouts (WorkoutID,WorkoutDate,Duration,WorkoutType) VALUES (1,'2023-01-01',60,'Yoga'),(2,'2023-01-02',90,'Cycling'),(3,'2023-01-03',75,'Yoga');
SELECT SUM(Duration) FROM Workouts WHERE WorkoutType = 'Yoga' AND WorkoutDate >= '2023-01-01' AND WorkoutDate <= '2023-01-31';
Show the total bioprocess engineering information for each region.
CREATE TABLE bioprocess_engineering (id INT,region VARCHAR(50),information FLOAT); INSERT INTO bioprocess_engineering (id,region,information) VALUES (1,'North America',3500); INSERT INTO bioprocess_engineering (id,region,information) VALUES (2,'Europe',2800); INSERT INTO bioprocess_engineering (id,region,information) VALUES (3,'Asia',4200);
SELECT region, SUM(information) FROM bioprocess_engineering GROUP BY region;
How many football matches were held in the 'football_matches' table with a total attendance greater than 50000?
CREATE TABLE football_matches (id INT,home_team VARCHAR(50),away_team VARCHAR(50),location VARCHAR(50),date DATE,attendance INT); INSERT INTO football_matches (id,home_team,away_team,location,date,attendance) VALUES (1,'Real Madrid','Barcelona','Madrid','2022-05-01',65000); INSERT INTO football_matches (id,home_team,away_team,location,date,attendance) VALUES (2,'Manchester United','Liverpool','Manchester','2022-05-05',70000);
SELECT COUNT(*) FROM football_matches WHERE attendance > 50000;
What is the average cost of construction materials per project in Texas?
CREATE TABLE construction_projects (id INT,project_name TEXT,state TEXT,material_cost FLOAT); INSERT INTO construction_projects (id,project_name,state,material_cost) VALUES (1,'Park Plaza','Texas',50000.00),(2,'Downtown Tower','California',150000.00),(3,'Galleria Mall','Texas',80000.00);
SELECT AVG(material_cost) FROM construction_projects WHERE state = 'Texas';
What is the total revenue generated by each product type, sorted by the total revenue in descending order?
CREATE TABLE RevenueByProduct (product VARCHAR(255),revenue DECIMAL(10,2)); INSERT INTO RevenueByProduct (product,revenue) VALUES ('Flower',50000),('Concentrates',35000),('Edibles',40000),('Topicals',25000);
SELECT product, SUM(revenue) as total_revenue FROM RevenueByProduct GROUP BY product ORDER BY total_revenue DESC;
What is the total number of mental health parity violations by region?
CREATE TABLE mental_health_parity_violations (violation_id INT,region VARCHAR(255)); INSERT INTO mental_health_parity_violations (violation_id,region) VALUES (1,'Northeast'),(2,'Southeast'),(3,'Midwest'),(4,'West'),(5,'Northeast'),(6,'Southeast'),(7,'Midwest'),(8,'West');
SELECT region, COUNT(*) as total_violations FROM mental_health_parity_violations GROUP BY region;
What is the maximum funding amount for startups founded in 2019?
CREATE TABLE funding_records (id INT,company_id INT,funding_amount INT,funding_date DATE); INSERT INTO funding_records (id,company_id,funding_amount,funding_date) VALUES (7,3,700000,'2018-01-01'); INSERT INTO funding_records (id,company_id,funding_amount,funding_date) VALUES (8,4,400000,'2017-01-01');
SELECT MAX(funding_amount) FROM funding_records JOIN companies ON funding_records.company_id = companies.id WHERE companies.founding_year = 2019;
Update the timeline of the 'Green Tower' project to reflect a 10% increase in labor cost.
CREATE TABLE Project_Timeline (id INT,project VARCHAR(30),phase VARCHAR(20),start_date DATE,end_date DATE,labor_cost FLOAT); INSERT INTO Project_Timeline (id,project,phase,start_date,end_date,labor_cost) VALUES (1,'Green Tower','Planning','2021-05-01','2021-07-31',50000.00),(2,'Green Tower','Construction','2021-08-01','2022-05-31',750000.00);
UPDATE Project_Timeline SET labor_cost = labor_cost * 1.10 WHERE project = 'Green Tower';
What are the names of customers who have invested in both the technology and healthcare sectors?
CREATE TABLE Customers (CustomerID INT,Name VARCHAR(50));CREATE TABLE Investments (CustomerID INT,InvestmentType VARCHAR(10),Sector VARCHAR(10));INSERT INTO Customers VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Bob Johnson');INSERT INTO Investments VALUES (1,'Stocks','Technology'),(1,'Stocks','Healthcare'),(2,'Stocks','Technology'),(2,'Stocks','Healthcare'),(3,'Stocks','Healthcare');
SELECT DISTINCT c.Name FROM Customers c INNER JOIN Investments i ON c.CustomerID = i.CustomerID WHERE i.Sector IN ('Technology', 'Healthcare') GROUP BY c.CustomerID, c.Name HAVING COUNT(DISTINCT i.Sector) = 2;
Which military equipment was sold to the United States before 2015 and after 2017?
CREATE TABLE MilitaryEquipmentSales (equipment_id INT,customer_country VARCHAR(50),sale_date DATE); INSERT INTO MilitaryEquipmentSales (equipment_id,customer_country,sale_date) VALUES (1,'United States','2014-01-01'),(2,'United States','2018-03-04');
SELECT equipment_id FROM MilitaryEquipmentSales WHERE customer_country = 'United States' AND sale_date < '2015-01-01' UNION SELECT equipment_id FROM MilitaryEquipmentSales WHERE customer_country = 'United States' AND sale_date > '2017-12-31'
What is the percentage of female employees in each department for the mining company?
CREATE TABLE departments (id INT,name VARCHAR(255)); INSERT INTO departments (id,name) VALUES (1,'HR'),(2,'Operations'),(3,'Engineering'); CREATE TABLE employees (id INT,name VARCHAR(255),gender VARCHAR(50),department_id INT); INSERT INTO employees (id,name,gender,department_id) VALUES (1,'John','Male',2),(2,'Jane','Female',3),(3,'Mike','Male',1),(4,'Lucy','Female',2),(5,'Tom','Male',2),(6,'Sara','Female',3),(7,'Emma','Female',1);
SELECT e.department_id, COUNT(CASE WHEN e.gender = 'Female' THEN 1 END) * 100.0 / COUNT(e.id) as female_percentage FROM employees e GROUP BY e.department_id;
Which countries have the lowest average clinical trial success rate in infectious diseases?
CREATE TABLE clinical_trials (country TEXT,trial_success_rate REAL,therapeutic_area TEXT); INSERT INTO clinical_trials (country,trial_success_rate,therapeutic_area) VALUES ('Canada',0.62,'infectious diseases'),('Brazil',0.67,'infectious diseases'),('Russia',0.58,'infectious diseases'),('India',0.64,'infectious diseases'),('South Africa',0.69,'infectious diseases');
SELECT country, AVG(trial_success_rate) as avg_trial_success_rate FROM clinical_trials WHERE therapeutic_area = 'infectious diseases' GROUP BY country ORDER BY avg_trial_success_rate ASC;
What is the distribution of articles published by month in the 'monthly_reports' table?
CREATE TABLE monthly_reports (id INT,title VARCHAR(255),author VARCHAR(255),published_date DATE);
SELECT MONTHNAME(published_date) as month, COUNT(*) as articles_published FROM monthly_reports GROUP BY month;
Determine the number of Shariah-compliant finance customers who joined after the first quarter of the year.
CREATE TABLE shariah_compliant_finance(customer_id INT,join_date DATE); INSERT INTO shariah_compliant_finance VALUES (1,'2022-04-01'),(2,'2022-03-15'),(3,'2022-01-01'),(4,'2022-05-10');
SELECT COUNT(*) FROM shariah_compliant_finance WHERE join_date > (SELECT MIN(join_date) + INTERVAL '3 months' FROM shariah_compliant_finance);
What is the number of students who prefer open pedagogy by gender?
CREATE TABLE students (student_id INT,student_name VARCHAR(50),gender VARCHAR(10),prefers_open_pedagogy BOOLEAN); INSERT INTO students (student_id,student_name,gender,prefers_open_pedagogy) VALUES (1,'John Doe','Male',true),(2,'Jane Smith','Female',true);
SELECT gender, SUM(prefers_open_pedagogy) FROM students GROUP BY gender;
Find the total fare collected from each payment type
CREATE TABLE fare_collection (route_id INT,payment_type VARCHAR(10),fare DECIMAL(5,2)); INSERT INTO fare_collection (route_id,payment_type,fare) VALUES (1,'Cash',2.50),(1,'Card',3.00),(2,'Cash',2.75),(2,'Card',3.25);
SELECT payment_type, SUM(fare) as total_fare FROM fare_collection GROUP BY payment_type;
Add a new safety protocol for chemical LMN to the safety_protocols table.
CREATE TABLE safety_protocols (id INT PRIMARY KEY,chemical_name VARCHAR(100),protocol VARCHAR(500));
INSERT INTO safety_protocols (id, chemical_name, protocol) VALUES (5, 'LMN', 'Use in a well-ventilated area. Keep away from heat and open flames.');
What is the number of hospital beds per 1000 people in Russia?
CREATE TABLE Beds (Country TEXT,BedsPer1000 FLOAT); INSERT INTO Beds VALUES ('Russia',8.1);
SELECT BedsPer1000 FROM Beds WHERE Country = 'Russia';
Update the donation amount for 'GiveWell' to $55,000 in the 'philanthropic_trends' table.
CREATE TABLE philanthropic_trends (organization_name TEXT,donation_amount INTEGER); INSERT INTO philanthropic_trends (organization_name,donation_amount) VALUES ('Effctive Altruism Funds',50000),('GiveWell',40000),('The Life You Can Save',30000),('Schistosomiasis Control Initiative',10000);
UPDATE philanthropic_trends SET donation_amount = 55000 WHERE organization_name = 'GiveWell';
What was the total expenditure of eco-tourists in Costa Rica and Belize in 2020?
CREATE TABLE tourism_stats (country VARCHAR(255),year INT,tourism_type VARCHAR(255),expenditure DECIMAL(10,2)); INSERT INTO tourism_stats (country,year,tourism_type,expenditure) VALUES ('Costa Rica',2020,'Eco-tourism',500000),('Costa Rica',2020,'Eco-tourism',600000),('Belize',2020,'Eco-tourism',400000),('Belize',2020,'Eco-tourism',450000);
SELECT SUM(expenditure) AS total_expenditure FROM tourism_stats WHERE country IN ('Costa Rica', 'Belize') AND tourism_type = 'Eco-tourism' AND year = 2020;
Find the number of goals scored by each team in the 2020 football season
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams VALUES (1,'Barcelona'); INSERT INTO teams VALUES (2,'Real Madrid'); CREATE TABLE goals (team_id INT,goals_scored INT,season VARCHAR(10)); INSERT INTO goals VALUES (1,85,'2020'); INSERT INTO goals VALUES (2,90,'2020');
SELECT teams.team_name, SUM(goals) as goals_scored FROM goals JOIN teams ON goals.team_id = teams.team_id WHERE goals.season = '2020' GROUP BY teams.team_name;
What is the maximum data usage in GB for postpaid mobile customers in each region?
CREATE TABLE customers (id INT,type VARCHAR(10),region VARCHAR(10)); INSERT INTO customers (id,type,region) VALUES (1,'postpaid','North'),(2,'prepaid','North'),(3,'postpaid','South'),(4,'prepaid','South'); CREATE TABLE usage (customer_id INT,data_usage FLOAT); INSERT INTO usage (customer_id,data_usage) VALUES (1,3.5),(2,2.2),(3,4.7),(4,1.8);
SELECT customers.region, MAX(usage.data_usage) FROM usage JOIN customers ON usage.customer_id = customers.id WHERE customers.type = 'postpaid' GROUP BY customers.region;
Update the risk assessment score for policyholder 4 to 600 based on their recent claim activity.
CREATE TABLE Policyholders (PolicyID INT,CoverageLimit DECIMAL(10,2),RiskAssessmentScore INT); INSERT INTO Policyholders (PolicyID,CoverageLimit,RiskAssessmentScore) VALUES (1,750000.00,400),(2,400000.00,350),(4,50000.00,250); CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimAmount DECIMAL(10,2)); INSERT INTO Claims (ClaimID,PolicyID,ClaimAmount) VALUES (1,1,5000.00),(2,4,2500.00);
WITH UpdatedScores AS (UPDATE Policyholders SET RiskAssessmentScore = 600 WHERE PolicyID = 4 RETURNING *) SELECT * FROM UpdatedScores;
Show the total number of fouls committed by each player in the 2021-2022 basketball season
CREATE TABLE players (player_id INT,player_name VARCHAR(255)); INSERT INTO players VALUES (1,'Player 1'); INSERT INTO players VALUES (2,'Player 2'); CREATE TABLE fouls (player_id INT,fouls INT,season VARCHAR(20)); INSERT INTO fouls VALUES (1,3,'2021-2022'); INSERT INTO fouls VALUES (2,4,'2021-2022');
SELECT players.player_name, SUM(fouls.fouls) as total_fouls FROM players JOIN fouls ON players.player_id = fouls.player_id WHERE fouls.season = '2021-2022' GROUP BY players.player_name;
What is the maximum and minimum speed of cargo ships in the Indian Ocean, grouped by their length?
CREATE TABLE ship_speeds (id INT,vessel_name VARCHAR(50),type VARCHAR(50),region VARCHAR(50),length DECIMAL(5,2),speed DECIMAL(5,2));
SELECT type, MIN(speed) AS min_speed, MAX(speed) AS max_speed FROM ship_speeds WHERE region = 'Indian Ocean' AND type = 'Cargo Ship' GROUP BY type, FLOOR(length);
List all astronauts who have participated in space missions, along with the number of missions they've been on, ordered by the number of missions in descending order.
CREATE TABLE Astronauts (ID INT,Astronaut_Name VARCHAR(255),Missions INT); INSERT INTO Astronauts (ID,Astronaut_Name,Missions) VALUES (1,'Jane Smith',3),(2,'Bob Johnson',1);
SELECT Astronaut_Name, Missions FROM Astronauts ORDER BY Missions DESC;
What are the top 3 countries with the highest number of broadband subscribers?
CREATE TABLE subscribers (subscriber_id INT,subscriber_name VARCHAR(50),plan_id INT,country VARCHAR(50)); INSERT INTO subscribers (subscriber_id,subscriber_name,plan_id,country) VALUES (1,'Alice',1,'USA'),(2,'Bob',2,'Canada'),(3,'Charlie',2,'Mexico'),(4,'Diana',3,'USA'),(5,'Eve',1,'Canada'),(6,'Frank',3,'Mexico'); CREATE TABLE plans (plan_id INT,plan_name VARCHAR(50),plan_type VARCHAR(50)); INSERT INTO plans (plan_id,plan_name,plan_type) VALUES (1,'Mobile','Postpaid'),(2,'Broadband','Fiber'),(3,'Broadband','Cable');
SELECT country, COUNT(*) as num_subscribers FROM subscribers s INNER JOIN plans p ON s.plan_id = p.plan_id WHERE p.plan_type = 'Broadband' GROUP BY country ORDER BY num_subscribers DESC LIMIT 3;
How many consumers in the United States have purchased second-hand clothing in the past year?
CREATE TABLE ConsumerPurchases (id INT,consumer_id INT,purchase_date DATE,item_type VARCHAR(20)); INSERT INTO ConsumerPurchases (id,consumer_id,purchase_date,item_type) VALUES (1,1,'2021-06-15','Shirt'),(2,1,'2021-07-22','Shoes'),(3,2,'2021-05-09','Dress'),(4,3,'2020-12-31','Jeans'),(5,3,'2021-08-18','Shirt');
SELECT COUNT(*) FROM ConsumerPurchases WHERE item_type = 'Shirt' OR item_type = 'Shoes' AND YEAR(purchase_date) = YEAR(CURRENT_DATE) - 1 AND consumer_id IN (SELECT DISTINCT consumer_id FROM ConsumerPurchases WHERE location = 'USA');
Delete all artists from the 'Ancient Art' event.
CREATE TABLE artists_events (id INT,artist_id INT,event_id INT); INSERT INTO artists_events (id,artist_id,event_id) VALUES (1,1,'Art of the Americas'),(2,2,'Art of the Americas'),(3,3,'Women in Art'); CREATE TABLE events (id INT,name VARCHAR(50),date DATE); INSERT INTO events (id,name,date) VALUES (1,'Art of the Americas','2022-06-01'),(2,'Women in Art','2022-07-01'),(3,'Ancient Art','2022-08-01');
DELETE FROM artists_events WHERE event_id = (SELECT id FROM events WHERE name = 'Ancient Art');
What is the average donation amount by donor type, excluding the top and bottom 5%?
CREATE SCHEMA if not exists arts_culture;CREATE TABLE if not exists arts_culture.donors (donor_id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),donation DECIMAL(10,2));INSERT INTO arts_culture.donors (donor_id,name,type,donation) VALUES (1,'John Doe','Individual',50.00),(2,'Jane Smith','Individual',100.00),(3,'Google Inc.','Corporation',5000.00);
SELECT type, AVG(donation) as avg_donation FROM (SELECT donation, type, NTILE(100) OVER (ORDER BY donation) as percentile FROM arts_culture.donors) d WHERE percentile NOT IN (1, 2, 99, 100) GROUP BY type;
Find the average production quantity (in metric tons) of Samarium from South American mines.
CREATE TABLE mines (id INT,name TEXT,location TEXT,production_quantity FLOAT); INSERT INTO mines (id,name,location,production_quantity) VALUES (1,'Mina Gerais','Brazil',120); INSERT INTO mines (id,name,location,production_quantity) VALUES (2,'Cerro Matoso','Colombia',240); INSERT INTO mines (id,name,location,production_quantity) VALUES (3,'Pitinga Mine','Brazil',360);
SELECT AVG(production_quantity) FROM mines WHERE location LIKE 'South%' AND element = 'Samarium';
Delete records of policies without a claim in the last 12 months for policy type 'Home'.
CREATE TABLE Policy (PolicyID INT,PolicyType VARCHAR(50)); INSERT INTO Policy VALUES (1,'Auto'),(2,'Home'),(3,'Life'); CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimDate DATE); INSERT INTO Claims VALUES (1,1,'2021-01-01'),(2,1,'2021-02-01'),(3,2,'2021-03-01'),(4,3,'2020-01-01'),(5,1,'2021-04-01'),(6,2,'2020-01-01');
DELETE p FROM Policy p INNER JOIN Claims c ON p.PolicyID = c.PolicyID WHERE p.PolicyType = 'Home' AND c.ClaimDate < DATE_SUB(CURDATE(), INTERVAL 12 MONTH);
What is the maximum investment value in the finance sector?
CREATE TABLE investments (investment_id INT,investor_id INT,sector VARCHAR(20),investment_value DECIMAL(10,2)); INSERT INTO investments (investment_id,investor_id,sector,investment_value) VALUES (1,1,'technology',5000.00),(2,2,'finance',3000.00);
SELECT MAX(investment_value) FROM investments WHERE sector = 'finance';
What is the difference in revenue between consecutive sales for each vendor, partitioned by vendor location, ordered by sale date?
CREATE TABLE Sales (SaleID INT,VendorID INT,Revenue INT,SaleDate DATE); INSERT INTO Sales VALUES (1,1,1000,'2020-01-01'),(2,1,1200,'2020-01-02'),(3,2,800,'2020-01-01');
SELECT SaleID, VendorID, LAG(Revenue) OVER (PARTITION BY VendorID, Location ORDER BY SaleDate) AS PreviousRevenue, Revenue, Revenue - LAG(Revenue) OVER (PARTITION BY VendorID, Location ORDER BY SaleDate) AS RevenueDifference FROM Sales;
What is the minimum and maximum salary for each job role in the company?
CREATE TABLE salaries (id INT,employee_name VARCHAR(50),job_role VARCHAR(50),salary DECIMAL(5,2));INSERT INTO salaries (id,employee_name,job_role,salary) VALUES (1,'John Doe','Data Scientist',80000.00),(2,'Jane Smith','Software Engineer',90000.00),(3,'Alice Johnson','Data Analyst',70000.00);
SELECT job_role, MIN(salary) as min_salary, MAX(salary) as max_salary FROM salaries GROUP BY job_role;
Update the rating of the 'Lipstick' product with ProductID 3 to 4.8.
CREATE TABLE Products (ProductID int,ProductName varchar(50),Category varchar(50),Rating float); INSERT INTO Products (ProductID,ProductName,Category,Rating) VALUES (1,'Foundation A','Foundation',3.5),(2,'Foundation B','Foundation',4.2),(3,'Lipstick C','Lipstick',4.7);
UPDATE Products SET Rating = 4.8 WHERE ProductID = 3 AND Category = 'Lipstick';
Insert new employees into the DiverseEmployees table.
CREATE TABLE DiverseEmployees (id INT,name VARCHAR(100),department VARCHAR(50),country VARCHAR(50));
INSERT INTO DiverseEmployees (id, name, department, country) VALUES (7, 'Hamza Ahmed', 'Finance', 'Pakistan'), (8, 'Xiuying Zhang', 'IT', 'China'), (9, 'Amina Diop', 'Marketing', 'Senegal'), (10, 'Santiago Rodriguez', 'HR', 'Brazil');
List all marine species affected by ocean acidification in descending order by number of occurrences.
CREATE TABLE marine_species (name TEXT,affected_by TEXT); INSERT INTO marine_species (name,affected_by) VALUES ('Coral','ocean_acidification'),('Pacific Oyster','ocean_acidification'),('Pteropods','ocean_acidification'),('Coccolithophores','ocean_acidification'),('Seagrasses','ocean_acidification');
SELECT affected_by, name AS marine_species, COUNT(*) AS occurrences FROM marine_species GROUP BY affected_by ORDER BY occurrences DESC;
Update user notification settings
CREATE TABLE users (id INT,name VARCHAR(50),join_date DATE,total_likes INT,allow_notifications BOOLEAN); INSERT INTO users (id,name,join_date,total_likes,allow_notifications) VALUES (1,'Alice','2020-01-01',100,true),(2,'Bob','2019-05-15',150,false);
UPDATE users SET allow_notifications = CASE WHEN id = 1 THEN false ELSE true END WHERE id IN (1, 2);
What is the percentage of students passing exams by ethnicity?
CREATE TABLE student_exams (id INT,student_name VARCHAR(50),ethnicity VARCHAR(50),passed_exam BOOLEAN); INSERT INTO student_exams (id,student_name,ethnicity,passed_exam) VALUES (1,'John Doe','Asian',true),(2,'Jane Doe','Hispanic',false);
SELECT ethnicity, AVG(CAST(passed_exam AS INT)) * 100 AS percentage FROM student_exams GROUP BY ethnicity;
What is the total volume of timber produced in the last 10 years in Brazil?
CREATE TABLE timber_production (id INT,volume REAL,year INT,country TEXT);
SELECT SUM(volume) FROM timber_production WHERE country = 'Brazil' AND year BETWEEN 2012 AND 2021;
Find the number of products that are part of a circular supply chain in the 'Product' table
CREATE TABLE Product (product_id INT PRIMARY KEY,product_name VARCHAR(50),is_circular_supply_chain BOOLEAN);
SELECT COUNT(*) FROM Product WHERE is_circular_supply_chain = TRUE;
What is the average water usage of rice in the 'water_usage' table?
CREATE TABLE water_usage (id INT,crop VARCHAR(255),year INT,water_usage DECIMAL(5,2)); INSERT INTO water_usage (id,crop,year,water_usage) VALUES (1,'Corn',2020,10.5),(2,'Soybean',2020,8.3),(3,'Rice',2020,12.0);
SELECT crop, AVG(water_usage) as AvgWaterUsage FROM water_usage WHERE crop = 'Rice' GROUP BY crop;
What is the average age of community health workers by city?
CREATE TABLE CommunityHealthWorker (WorkerID INT,Age INT,City VARCHAR(50)); INSERT INTO CommunityHealthWorker (WorkerID,Age,City) VALUES (1,45,'New York'),(2,35,'Los Angeles'),(3,50,'Chicago'),(4,40,'Houston'),(5,55,'Philadelphia');
SELECT City, AVG(Age) as AvgAge FROM CommunityHealthWorker GROUP BY City;
What are the maximum and minimum exploration costs for each country in South America?
CREATE TABLE exploration (exp_id INT,exp_country TEXT,cost INT); INSERT INTO exploration (exp_id,exp_country,cost) VALUES (1,'Country A',10000),(2,'Country B',15000),(3,'Country C',12000);
SELECT exp_country, MAX(cost) AS max_cost, MIN(cost) AS min_cost FROM exploration GROUP BY exp_country;
What is the average animal weight for each farmer in the agriculture database?
CREATE TABLE Farmers (id INT,name VARCHAR,location VARCHAR,years_of_experience INT); INSERT INTO Farmers (id,name,location,years_of_experience) VALUES (1,'Grace Kim','Seoul',12),(2,'Benjamin Smith','New York',9),(3,'Fatima Ahmed','Dubai',18); CREATE TABLE Animals (id INT,farmer_id INT,animal_name VARCHAR,weight INT); INSERT INTO Animals (id,farmer_id,animal_name,weight) VALUES (1,1,'Cattle',700),(2,1,'Goat',30),(3,2,'Horse',500),(4,3,'Camel',800),(5,3,'Sheep',40);
SELECT f.name, AVG(a.weight) as average_animal_weight FROM Farmers f JOIN Animals a ON f.id = a.farmer_id GROUP BY f.name;
Identify the journal that has published the most articles by female authors in the past 5 years.
CREATE TABLE authors (id INT,name VARCHAR(100),gender VARCHAR(10)); INSERT INTO authors (id,name,gender) VALUES (1,'Author Name','Female'); CREATE TABLE publications (id INT,title VARCHAR(100),author VARCHAR(100),journal VARCHAR(100),year INT); INSERT INTO publications (id,title,author,journal,year) VALUES (1,'Publication Title','Author Name','Journal Name',2021);
SELECT journal, COUNT(*) as num_publications FROM publications p JOIN authors a ON p.author = a.name WHERE a.gender = 'Female' AND year BETWEEN YEAR(CURRENT_DATE) - 5 AND YEAR(CURRENT_DATE) GROUP BY journal ORDER BY num_publications DESC LIMIT 1;
What is the total number of artworks in each art category and year combination in the 'Artworks' table?
CREATE TABLE Artworks (id INT,art_category VARCHAR(255),artist_name VARCHAR(255),year INT,art_medium VARCHAR(255),price DECIMAL(10,2));
SELECT art_category, year, COUNT(*) as total FROM Artworks GROUP BY art_category, year;
What is the average ticket price for football games in the Southeast region?
CREATE TABLE football_games(id INT,team VARCHAR(50),location VARCHAR(50),price DECIMAL(5,2)); INSERT INTO football_games(id,team,location,price) VALUES (1,'Atlanta Falcons','Georgia Dome',95.00),(2,'Carolina Panthers','Bank of America Stadium',80.50),(3,'New Orleans Saints','Mercedes-Benz Superdome',110.00);
SELECT AVG(price) FROM football_games WHERE location IN ('Georgia Dome', 'Bank of America Stadium', 'Mercedes-Benz Superdome');
What is the total attendance by age group, for dance events in New York, in 2022?
CREATE TABLE Events (id INT,event_name VARCHAR(100),event_type VARCHAR(50),location VARCHAR(100),start_time TIMESTAMP,end_time TIMESTAMP); CREATE TABLE Attendees (id INT,attendee_age INT,event_id INT);
SELECT attendee_age_group, SUM(attendance) as total_attendance FROM (SELECT attendee_age AS attendee_age_group, COUNT(*) AS attendance FROM Attendees JOIN Events ON Attendees.event_id = Events.id WHERE Events.event_type = 'dance' AND Events.location LIKE '%New York%' AND DATE_TRUNC('year', Events.start_time) = DATE_TRUNC('year', '2022-01-01') GROUP BY attendee_age) AS subquery GROUP BY attendee_age_group;
What is the average ethical rating of manufacturers in France that use sustainable materials?
CREATE TABLE manufacturers (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),ethical_rating FLOAT); INSERT INTO manufacturers (id,name,location,ethical_rating) VALUES (1,'Ethical Co.','France',4.6),(2,'Green Producers','France',4.4); CREATE TABLE materials (id INT PRIMARY KEY,name VARCHAR(255),origin VARCHAR(255),sustainability_rating FLOAT); INSERT INTO materials (id,name,origin,sustainability_rating) VALUES (1,'Sustainable Wood','France',4.8),(2,'Recycled Metal','France',4.7);
SELECT AVG(m.ethical_rating) FROM manufacturers m INNER JOIN materials s ON m.location = s.origin WHERE s.sustainability_rating > 4.6;
Find the total number of posts and users from 'Pinterest' and 'Tumblr' platforms, excluding reposts and bots.
CREATE TABLE Pinterest(id INT,user_id INT,post_time TIMESTAMP,content TEXT,repost BOOLEAN,bot BOOLEAN); CREATE TABLE Tumblr(id INT,user_id INT,post_time TIMESTAMP,content TEXT,repost BOOLEAN,bot BOOLEAN);
SELECT COUNT(DISTINCT user_id) AS total_users, COUNT(*) AS total_posts FROM Pinterest WHERE repost = FALSE AND bot = FALSE UNION ALL SELECT COUNT(DISTINCT user_id) AS total_users, COUNT(*) AS total_posts FROM Tumblr WHERE repost = FALSE AND bot = FALSE;
How many crops are grown in 'indigenous_farms' table for region '05'?
CREATE TABLE indigenous_farms (id INT,region VARCHAR(10),crop VARCHAR(20));
SELECT COUNT(DISTINCT crop) FROM indigenous_farms WHERE region = '05';
What is the monthly sales revenue for each sales representative?
CREATE TABLE Sales (SalesID INT,SalesRep VARCHAR(50),SaleDate DATE,Revenue DECIMAL(10,2)); INSERT INTO Sales VALUES (1,'Salesperson A','2022-01-01',1000.00),(2,'Salesperson B','2022-01-05',1500.00),(3,'Salesperson A','2022-02-03',2000.00);
SELECT SalesRep, DATE_TRUNC('month', SaleDate) as Month, SUM(Revenue) as MonthlyRevenue FROM Sales GROUP BY SalesRep, Month ORDER BY SalesRep, Month;
Identify the top 3 countries with the most volunteers and donors.
CREATE TABLE Volunteers (id INT,name TEXT,country TEXT); INSERT INTO Volunteers (id,name,country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Canada'); CREATE TABLE Donors (id INT,name TEXT,country TEXT); INSERT INTO Donors (id,name,country) VALUES (3,'Mike Johnson','USA'),(4,'Sara Williams','Mexico');
(SELECT country, COUNT(*) as total FROM Volunteers GROUP BY country ORDER BY total DESC LIMIT 3) UNION ALL (SELECT country, COUNT(*) as total FROM Donors GROUP BY country ORDER BY total DESC LIMIT 3);
List the top 5 customers with the highest total transaction amount in the past month.
CREATE TABLE customers (customer_id INT,name VARCHAR(50)); CREATE TABLE transactions (transaction_id INT,customer_id INT,transaction_amount DECIMAL(10,2)); INSERT INTO customers (customer_id,name) VALUES (1,'Alice Davis'); INSERT INTO customers (customer_id,name) VALUES (2,'Bob Thompson'); INSERT INTO transactions (transaction_id,customer_id,transaction_amount) VALUES (1,1,150.00); INSERT INTO transactions (transaction_id,customer_id,transaction_amount) VALUES (2,2,250.00);
SELECT customer_id, name, SUM(transaction_amount) as total_transaction_amount FROM transactions t INNER JOIN customers c ON t.customer_id = c.customer_id WHERE transaction_date BETWEEN DATEADD(month, -1, GETDATE()) AND GETDATE() GROUP BY customer_id, name ORDER BY total_transaction_amount DESC LIMIT 5;
List the top 3 most common causes for volunteering?
CREATE TABLE causes (cause_id INT,name TEXT,description TEXT);CREATE TABLE volunteers (volunteer_id INT,cause_id INT,total_hours DECIMAL);
SELECT causes.name, COUNT(volunteers.cause_id) as total_volunteers FROM causes JOIN volunteers ON causes.cause_id = volunteers.cause_id GROUP BY causes.name ORDER BY total_volunteers DESC LIMIT 3;
What is the total funding received by startups founded by individuals with disabilities in the fintech sector?
CREATE TABLE startups (id INT,name TEXT,industry TEXT,founding_date DATE,founders TEXT,funding FLOAT); INSERT INTO startups (id,name,industry,founding_date,founders,funding) VALUES (1,'FintechForAll','Fintech','2020-01-01','Individuals with disabilities',3000000.0);
SELECT SUM(funding) FROM startups WHERE founders = 'Individuals with disabilities' AND industry = 'Fintech';
How many non-vegetarian items are there on the menu?
CREATE TABLE menus (menu_id INT,menu_name VARCHAR(50),category VARCHAR(50),price DECIMAL(5,2)); INSERT INTO menus (menu_id,menu_name,category,price) VALUES (1,'Quinoa Salad','Vegetarian',9.99),(2,'Margherita Pizza','Non-Vegetarian',12.99),(3,'Chickpea Curry','Vegetarian',10.99),(4,'Tofu Stir Fry','Vegan',11.99),(5,'Steak','Non-Vegetarian',25.99);
SELECT COUNT(*) FROM menus WHERE category = 'Non-Vegetarian';
What is the average duration of peacekeeping operations for each country?
CREATE TABLE Peacekeeping_Operations (Operation_ID INT,Country_Name VARCHAR(50),Start_Date DATE,End_Date DATE); INSERT INTO Peacekeeping_Operations (Operation_ID,Country_Name,Start_Date,End_Date) VALUES (1,'Bangladesh','2005-01-01','2007-12-31');
SELECT Country_Name, AVG(DATEDIFF(End_Date, Start_Date)) as Average_Duration FROM Peacekeeping_Operations GROUP BY Country_Name;
What is the number of climate-related disasters in Southeast Asia between 2000 and 2010, and the total number of people affected by them?
CREATE TABLE ClimateDisastersData (country VARCHAR(50),year INT,disaster_type VARCHAR(50),people_affected INT);
SELECT COUNT(*), SUM(people_affected) FROM ClimateDisastersData WHERE country LIKE 'Southeast Asia%' AND year BETWEEN 2000 AND 2010 AND disaster_type LIKE 'climate%';
What is the maximum number of attendees for any cultural event?
CREATE TABLE events (id INT,name VARCHAR(255),date DATE,attendees INT); INSERT INTO events (id,name,date,attendees) VALUES (1,'Festival','2022-06-01',5000),(2,'Conference','2022-07-01',2000),(3,'Exhibition','2022-08-01',3000);
SELECT MAX(attendees) FROM events;
How many electric buses are there in Tokyo and Seoul combined?
CREATE TABLE electric_buses (bus_id INT,city VARCHAR(20)); INSERT INTO electric_buses (bus_id,city) VALUES (1,'Tokyo'),(2,'Tokyo'),(3,'Seoul'),(4,'Seoul');
SELECT COUNT(*) FROM electric_buses WHERE city IN ('Tokyo', 'Seoul');
Show the average billing amount for each attorney's cases, ordered alphabetically by attorney name.
CREATE TABLE CaseBilling (CaseID INT,AttorneyID INT,Billing FLOAT); INSERT INTO CaseBilling (CaseID,AttorneyID,Billing) VALUES (1,1,1500.00),(2,2,3000.00),(3,3,5000.00),(4,1,2000.00),(5,2,1000.00),(6,3,4000.00);
SELECT a.Name AS AttorneyName, AVG(cb.Billing) AS AvgBilling FROM Attorneys a JOIN CaseBilling cb ON a.AttorneyID = cb.AttorneyID GROUP BY a.Name ORDER BY a.Name;
What is the change in the number of tourists visiting India between Q1 and Q2 in 2023?
CREATE TABLE quarterly_visitors (id INT,country TEXT,quarter INT,year INT,num_visitors INT); INSERT INTO quarterly_visitors (id,country,quarter,year,num_visitors) VALUES (1,'India',1,2023,1000000),(2,'India',2,2023,1100000),(3,'China',1,2023,1200000);
SELECT country, (SUM(CASE WHEN quarter = 2 THEN num_visitors ELSE 0 END) - SUM(CASE WHEN quarter = 1 THEN num_visitors ELSE 0 END)) AS change_in_visitors FROM quarterly_visitors WHERE country = 'India' AND year = 2023 GROUP BY country;
What is the total budget allocated for policies related to the environment?
CREATE TABLE Policy_Budget (Policy_ID INT PRIMARY KEY,Policy_Area VARCHAR(30),Budget INT); INSERT INTO Policy_Budget (Policy_ID,Policy_Area,Budget) VALUES (1,'Transportation',8000000),(2,'Education',7000000),(3,'Environment',5000000),(4,'Housing',9000000);
SELECT SUM(Budget) FROM Policy_Budget WHERE Policy_Area = 'Environment';
Display the number of employees, by ethnicity, in the 'employee_ethnicity' table.
CREATE TABLE employee_ethnicity (id INT,employee_id INT,ethnicity VARCHAR(50)); INSERT INTO employee_ethnicity (id,employee_id,ethnicity) VALUES (1,1,'Hispanic'),(2,2,'Asian'),(3,3,'African American');
SELECT ethnicity, COUNT(*) as num_employees FROM employee_ethnicity GROUP BY ethnicity;
What is the total water usage for each fabric type produced in Egypt?
CREATE TABLE fabric_sustainability (id INT PRIMARY KEY,fabric_type VARCHAR(255),country_origin VARCHAR(255),water_usage FLOAT,co2_emissions FLOAT); INSERT INTO fabric_sustainability (id,fabric_type,country_origin,water_usage,co2_emissions) VALUES (1,'Cotton','Egypt',1500,4.5);
SELECT fabric_sustainability.fabric_type, SUM(fabric_sustainability.water_usage) as total_water_usage FROM fabric_sustainability WHERE fabric_sustainability.country_origin = 'Egypt' GROUP BY fabric_sustainability.fabric_type;
What is the maximum water temperature in Catfish Farms in the African region?
CREATE TABLE Catfish_Farms (Farm_ID INT,Farm_Name TEXT,Region TEXT,Water_Temperature FLOAT); INSERT INTO Catfish_Farms (Farm_ID,Farm_Name,Region,Water_Temperature) VALUES (1,'Farm M','African',30.0); INSERT INTO Catfish_Farms (Farm_ID,Farm_Name,Region,Water_Temperature) VALUES (2,'Farm N','African',31.0); INSERT INTO Catfish_Farms (Farm_ID,Farm_Name,Region,Water_Temperature) VALUES (3,'Farm O','European',29.0);
SELECT MAX(Water_Temperature) FROM Catfish_Farms WHERE Region = 'African';
What is the total revenue generated from textile sourcing in Africa?
CREATE TABLE Suppliers (id INT,supplier_name VARCHAR(255),country VARCHAR(255)); INSERT INTO Suppliers (id,supplier_name,country) VALUES (1,'Supplier A','USA'),(2,'Supplier B','South Africa'),(3,'Supplier C','China'); CREATE TABLE Purchase_Orders (id INT,supplier_id INT,purchase_value DECIMAL(5,2)); INSERT INTO Purchase_Orders (id,supplier_id,purchase_value) VALUES (1,1,1000.00),(2,2,1500.00),(3,3,1200.00);
SELECT SUM(Purchase_Orders.purchase_value) FROM Purchase_Orders INNER JOIN Suppliers ON Purchase_Orders.supplier_id = Suppliers.id WHERE Suppliers.country = 'South Africa';
What is the average carbon price and total carbon emitted in Spain for 2020?
CREATE TABLE country (id INT PRIMARY KEY,name VARCHAR(50));CREATE TABLE carbon_price (id INT PRIMARY KEY,name VARCHAR(50),country_id INT,FOREIGN KEY (country_id) REFERENCES country(id),price DECIMAL(10,2));CREATE TABLE carbon_emission (id INT PRIMARY KEY,date DATE,source_id INT,FOREIGN KEY (source_id) REFERENCES renewable_source(id),carbon_emitted DECIMAL(10,2));CREATE TABLE power_usage (id INT PRIMARY KEY,date DATE,usage_amount INT,country_id INT,FOREIGN KEY (country_id) REFERENCES country(id));
SELECT c.name AS country_name, cp.name AS carbon_price_name, AVG(cp.price) AS average_carbon_price, SUM(ce.carbon_emitted) AS total_carbon_emitted FROM carbon_emission ce JOIN carbon_price cp ON ce.country_id = cp.country_id JOIN power_usage pu ON ce.date = pu.date AND ce.country_id = pu.country_id JOIN country c ON pu.country_id = c.id WHERE c.name = 'Spain' AND pu.date BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY c.name, cp.name;
How many patients were treated with a specific therapy approach in a specific year?
CREATE TABLE TherapyApproaches (TherapyID INT,TherapyName VARCHAR(50)); CREATE TABLE Patients (PatientID INT,Age INT,Gender VARCHAR(10),TherapyStartYear INT); CREATE TABLE TherapySessions (SessionID INT,PatientID INT,TherapyID INT);
SELECT TherapyApproaches.TherapyName, Patients.TherapyStartYear, COUNT(TherapySessions.SessionID) FROM TherapyApproaches INNER JOIN TherapySessions ON TherapyApproaches.TherapyID = TherapySessions.TherapyID INNER JOIN Patients ON TherapySessions.PatientID = Patients.PatientID GROUP BY TherapyApproaches.TherapyName, Patients.TherapyStartYear;