instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the difference in the number of hospitals between rural and urban areas.
CREATE TABLE hospitals (name VARCHAR(255),city_type VARCHAR(255),num_beds INT); INSERT INTO hospitals (name,city_type,num_beds) VALUES ('General Hospital','Urban',500); INSERT INTO hospitals (name,city_type,num_beds) VALUES ('Mount Sinai Hospital','Urban',1200); INSERT INTO hospitals (name,city_type,num_beds) VALUES ('Rural Clinic Hospital','Rural',100);
SELECT (SUM(CASE WHEN city_type = 'Urban' THEN 1 ELSE 0 END) - SUM(CASE WHEN city_type = 'Rural' THEN 1 ELSE 0 END)) FROM hospitals;
What is the average occupancy rate of luxury hotels in Europe?
CREATE TABLE hotels (hotel_id INT,region VARCHAR(50),rating VARCHAR(10),occupancy_rate DECIMAL(5,2)); INSERT INTO hotels (hotel_id,region,rating,occupancy_rate) VALUES (1,'Europe','Luxury',0.85),(2,'Asia','Standard',0.75),(3,'Europe','Luxury',0.90),(4,'America','Eco-Friendly',0.70);
SELECT AVG(occupancy_rate) FROM hotels WHERE region = 'Europe' AND rating = 'Luxury';
What is the most popular genre among users in India?
CREATE TABLE users (id INT,name TEXT,country TEXT);CREATE TABLE user_genre_preferences (user_id INT,genre_id INT);CREATE TABLE genres (id INT,name TEXT); INSERT INTO users (id,name,country) VALUES (1,'User C','India'),(2,'User D','Australia'); INSERT INTO user_genre_preferences (user_id,genre_id) VALUES (1,4),(1,5),(2,6); INSERT INTO genres (id,name) VALUES (4,'Folk'),(5,'Classical'),(6,'Country');
SELECT genres.name, COUNT(user_genre_preferences.user_id) AS popularity FROM genres JOIN user_genre_preferences ON genres.id = user_genre_preferences.genre_id JOIN users ON user_genre_preferences.user_id = users.id WHERE users.country = 'India' GROUP BY genres.name ORDER BY popularity DESC LIMIT 1;
List the top 10 mobile and broadband plans with the highest monthly revenue, including the plan name, plan type, monthly fee, and average data usage.
CREATE TABLE plan_info (plan_name VARCHAR(50),plan_type VARCHAR(20),monthly_fee FLOAT,average_data_usage FLOAT);
SELECT plan_name, plan_type, monthly_fee, average_data_usage FROM plan_info ORDER BY monthly_fee * average_data_usage DESC LIMIT 10;
What is the average salary by mine, gender, and role?
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, employee.role, AVG(employee.salary) FROM employee JOIN mine ON employee.mine_id = mine.id GROUP BY mine.name, employee.gender, employee.role;
Delete wells that have water production less than 2000 in 2021?
CREATE TABLE well (well_id INT,well_name TEXT,water_production_2021 FLOAT); INSERT INTO well (well_id,well_name,water_production_2021) VALUES (1,'Well D',2200),(2,'Well E',1800),(3,'Well F',2500);
DELETE FROM well WHERE water_production_2021 < 2000;
What is the maximum landfill capacity for each region in the past year?
CREATE TABLE LandfillCapacity (region VARCHAR(50),date DATE,capacity INT); INSERT INTO LandfillCapacity VALUES ('North','2021-01-01',50000),('North','2021-01-02',51000),('South','2021-01-01',45000),('South','2021-01-02',46000),('East','2021-01-01',55000),('East','2021-01-02',56000),('West','2021-01-01',40000),('West','2021-01-02',41000);
SELECT region, MAX(capacity) FROM LandfillCapacity WHERE date >= DATEADD(year, -1, GETDATE()) GROUP BY region;
What is the average military innovation budget (in USD) for each organization in the 'military_innovation' table, excluding those with less than 2 projects?
CREATE TABLE military_innovation (id INT,organization VARCHAR(50),budget INT);
SELECT organization, AVG(budget) as avg_budget FROM military_innovation GROUP BY organization HAVING COUNT(*) >= 2;
Calculate the total number of courses offered by 'Stanford U' in each 'Spring' and 'Fall' season.
CREATE TABLE university_courses (course_id INT,university VARCHAR(20),season VARCHAR(10),num_courses INT); INSERT INTO university_courses (course_id,university,season,num_courses) VALUES (1,'Stanford U','Fall',20),(2,'Berkeley U','Spring',30),(3,'Stanford U','Spring',15);
SELECT university, season, SUM(num_courses) FROM university_courses WHERE university = 'Stanford U' AND season IN ('Spring', 'Fall') GROUP BY university, season;
What is the name of the intelligence operative in the 'intelligence_operatives' table with the most successful operations?
CREATE TABLE intelligence_operatives (id INT,name TEXT,number_of_operations INT); INSERT INTO intelligence_operatives (id,name,number_of_operations) VALUES (1,'John Doe',50),(2,'Jane Smith',75),(3,'Alice Johnson',100),(4,'Bob Brown',85);
SELECT name FROM intelligence_operatives ORDER BY number_of_operations DESC LIMIT 1;
What is the number of crimes committed by age group in each city district?
CREATE TABLE city_districts (district_id INT,district_name VARCHAR(50)); CREATE TABLE citizens (citizen_id INT,district_id INT,age INT); CREATE TABLE crimes (crime_id INT,committed_by_id INT,crime_type VARCHAR(50),committed_date DATE); INSERT INTO city_districts (district_id,district_name) VALUES (1,'Downtown'),(2,'Uptown'),(3,'Suburbs'); INSERT INTO citizens (citizen_id,district_id,age) VALUES (1,1,25),(2,2,35),(3,3,45),(4,1,19); INSERT INTO crimes (crime_id,committed_by_id,crime_type,committed_date) VALUES (1,1,'Theft','2021-01-01'),(2,2,'Vandalism','2021-02-01'),(3,3,'Burglary','2021-03-01'),(4,1,'Theft','2021-04-01');
SELECT d.district_name, FLOOR(c.age / 10) * 10 AS age_group, COUNT(crime_id) crime_count FROM crimes c JOIN citizens ON c.committed_by_id = citizens.citizen_id JOIN city_districts d ON citizens.district_id = d.district_id GROUP BY d.district_name, age_group;
Which suppliers have the lowest water usage in their supply chains?
CREATE TABLE suppliers (supplier_id int,supplier_name varchar(255),water_usage_liters int); INSERT INTO suppliers (supplier_id,supplier_name,water_usage_liters) VALUES (1,'Supplier A',10000),(2,'Supplier B',15000),(3,'Supplier C',7000);
SELECT supplier_name, water_usage_liters FROM suppliers ORDER BY water_usage_liters ASC LIMIT 1;
Find policy types with more than two policyholders living in 'MI'.
CREATE TABLE policyholders (id INT,name TEXT,state TEXT,policy_type TEXT,premium FLOAT); INSERT INTO policyholders (id,name,state,policy_type,premium) VALUES (1,'John Doe','MI','Auto',1200.00),(2,'Jane Smith','MI','Auto',1200.00),(3,'Jim Brown','MI','Health',2500.00),(4,'Karen Green','MI','Health',2500.00),(5,'Mark Red','CA','Home',3000.00);
SELECT policy_type, COUNT(DISTINCT name) as num_policyholders FROM policyholders WHERE state = 'MI' GROUP BY policy_type HAVING num_policyholders > 2;
Show the minimum depth of the Southern Ocean
CREATE TABLE ocean_floors (ocean TEXT,trench_name TEXT,minimum_depth INTEGER); INSERT INTO ocean_floors (ocean,trench_name,minimum_depth) VALUES ('Pacific Ocean','Mariana Trench',10994),('Atlantic Ocean','Puerto Rico Trench',8380),('Southern Ocean','Southern Ocean Trench',8200);
SELECT MIN(minimum_depth) FROM ocean_floors WHERE ocean = 'Southern Ocean';
Update the indigenous_communities table to include a new community
CREATE SCHEMA IF NOT EXISTS arctic_db; CREATE TABLE IF NOT EXISTS indigenous_communities (id INT PRIMARY KEY,name TEXT,population INT);
INSERT INTO indigenous_communities (id, name, population) VALUES (1, 'Inuit of Greenland', 50000);
What is the maximum cost of accommodations in the AssistiveTechnology table for each accommodation type?
CREATE TABLE AssistiveTechnology (studentID INT,accommodationType VARCHAR(50),cost DECIMAL(5,2));
SELECT accommodationType, MAX(cost) FROM AssistiveTechnology GROUP BY accommodationType;
List all legal technology initiatives and their respective launch dates in the US, sorted by launch date in descending order.
CREATE TABLE legal_tech_launch (id INT,initiative VARCHAR(255),launch_date DATE); INSERT INTO legal_tech_launch (id,initiative,launch_date) VALUES (1,'Legal AI Platform','2018-05-15'),(2,'Online Dispute Resolution','2016-09-01'),(3,'Smart Contracts','2017-12-21');
SELECT * FROM legal_tech_launch WHERE country = 'US' ORDER BY launch_date DESC;
Show the names of countries offering open pedagogy programs in the 'country_programs' table, without repeating any country names.
CREATE TABLE country_programs (country_name VARCHAR(50),program_type VARCHAR(30));
SELECT DISTINCT country_name FROM country_programs WHERE program_type = 'open_pedagogy';
Delete all records of cultural heritage sites in Africa from the database.
CREATE TABLE sites (id INT,name TEXT,country TEXT,type TEXT); INSERT INTO sites (id,name,country,type) VALUES (1,'Historic Site A','Egypt','cultural'),(2,'Historic Site B','Kenya','cultural');
DELETE FROM sites WHERE type = 'cultural' AND country IN ('Africa');
What is the total duration (in days) of all space missions led by NASA?
CREATE TABLE Missions (MissionID INT,Name VARCHAR(50),Agency VARCHAR(30),StartDate DATETIME,EndDate DATETIME); INSERT INTO Missions (MissionID,Name,Agency,StartDate,EndDate) VALUES (1,'Apollo 11','NASA','1969-07-16','1969-07-24'),(2,'Apollo 13','NASA','1970-04-11','1970-04-17'),(3,'Skylab 4','NASA','1973-11-16','1974-02-08');
SELECT SUM(DATEDIFF(EndDate, StartDate)) FROM Missions WHERE Agency = 'NASA';
What is the total number of cases in 'justice_cases' table, resolved through mediation?
CREATE TABLE justice_cases (id INT,case_type TEXT,resolution_method TEXT); INSERT INTO justice_cases (id,case_type,resolution_method) VALUES (1,'Violent Crime','Restorative Justice'),(2,'Property Crime','Mediation'),(3,'Violent Crime','Mediation');
SELECT COUNT(*) FROM justice_cases WHERE resolution_method = 'Mediation';
What is the percentage of fair trade products in each country?
CREATE TABLE Products (ProductID INT,ProductName VARCHAR(50),Country VARCHAR(50),ProductType VARCHAR(50)); INSERT INTO Products VALUES (1,'Product 1','USA','Fair Trade'),(2,'Product 2','Canada','Fair Trade'),(3,'Product 3','USA','Regular'),(4,'Product 4','Mexico','Fair Trade');
SELECT Country, 100.0 * COUNT(CASE WHEN ProductType = 'Fair Trade' THEN 1 END) / COUNT(*) as FairTradePercentage FROM Products GROUP BY Country;
What is the average number of students with disabilities per department in each university?
CREATE TABLE Universities (UniversityID INT PRIMARY KEY,UniversityName VARCHAR(50)); CREATE TABLE Departments (DepartmentID INT PRIMARY KEY,DepartmentName VARCHAR(50)); CREATE TABLE UniversityDepartments (UniversityDepartmentID INT PRIMARY KEY,UniversityID INT,DepartmentID INT,NumberOfStudentsWithDisabilities INT,FOREIGN KEY (UniversityID) REFERENCES Universities(UniversityID),FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID));
SELECT u.UniversityName, d.DepartmentName, AVG(NumberOfStudentsWithDisabilities) as AvgStudentsWithDisabilities FROM Universities u JOIN UniversityDepartments ud ON u.UniversityID = ud.UniversityID JOIN Departments d ON ud.DepartmentID = d.DepartmentID GROUP BY u.UniversityName, d.DepartmentName;
What is the total waste generation in the commercial sector in the city of Houston in 2022?
CREATE TABLE waste_generation_commercial (city varchar(255),sector varchar(255),year int,total_waste float); INSERT INTO waste_generation_commercial (city,sector,year,total_waste) VALUES ('Houston','Commercial',2022,3000000);
SELECT total_waste FROM waste_generation_commercial WHERE city = 'Houston' AND sector = 'Commercial' AND year = 2022
What is the average number of daily posts per user?
CREATE TABLE users (id INT,user_id INT); INSERT INTO users (id,user_id) VALUES (1,1),(2,2),(3,3),(4,4),(5,5); CREATE TABLE posts (id INT,user_id INT,post_date DATE); INSERT INTO posts (id,user_id,post_date) VALUES (1,1,'2022-01-01'),(2,2,'2022-01-02'),(3,1,'2022-01-03'),(4,2,'2022-01-04'),(5,3,'2022-01-05'),(6,3,'2022-01-05'),(7,1,'2022-01-06'),(8,2,'2022-01-07'),(9,4,'2022-01-08'),(10,5,'2022-01-09');
SELECT AVG(post_count) FROM (SELECT user_id, COUNT(*) AS post_count FROM posts GROUP BY user_id) AS t;
Identify regions with no marine research stations
CREATE TABLE regions_with_stations (region_id INT); INSERT INTO regions_with_stations (region_id) VALUES (1),(2),(3);
SELECT region_id FROM regions WHERE region_id NOT IN (SELECT region_id FROM research_stations);
What is the total value of cybersecurity threat intelligence metrics reported for the Asia-Pacific region?
CREATE TABLE Cyber_Threats (ID INT,Location TEXT,Metric_Value INT); INSERT INTO Cyber_Threats (ID,Location,Metric_Value) VALUES (1,'China',70); INSERT INTO Cyber_Threats (ID,Location,Metric_Value) VALUES (2,'Japan',80); INSERT INTO Cyber_Threats (ID,Location,Metric_Value) VALUES (3,'South Korea',90);
SELECT SUM(Metric_Value) FROM Cyber_Threats WHERE Location LIKE '%Asia-Pacific%';
Add a new mental health campaign in Canada focused on anxiety disorders
CREATE TABLE mental_health.campaigns (campaign_id INT,campaign_name VARCHAR(50),focus_area VARCHAR(50),country VARCHAR(50));
INSERT INTO mental_health.campaigns (campaign_id, campaign_name, focus_area, country) VALUES (6, 'Mind Matters', 'Anxiety Disorders', 'Canada');
What is the number of defense contracts awarded in H1 2020 to companies in Texas?
CREATE TABLE DefenseContracts (ContractID INT,CompanyName TEXT,State TEXT,ContractDate DATE); INSERT INTO DefenseContracts (ContractID,CompanyName,State,ContractDate) VALUES (1,'ABC Corporation','Texas','2020-01-10'),(2,'XYZ Incorporated','California','2020-02-15'),(3,'DEF Enterprises','Texas','2020-03-20'),(4,'LMN Industries','New York','2020-04-25');
SELECT ContractID FROM DefenseContracts WHERE State = 'Texas' AND ContractDate BETWEEN '2020-01-01' AND '2020-06-30';
What is the percentage of the population that is fully vaccinated against COVID-19 in each region?
CREATE TABLE Regions (Region VARCHAR(50),Population INT,Vaccinated INT); INSERT INTO Regions (Region,Population,Vaccinated) VALUES ('North',100000,65000),('South',120000,72000),('East',110000,68000),('West',90000,55000);
SELECT Region, (SUM(Vaccinated) / SUM(Population)) * 100 AS VaccinationPercentage FROM Regions GROUP BY Region;
What is the average budget required for ethical AI projects in North America and Europe?
CREATE TABLE ethical_ai_2 (project_id INT,region VARCHAR(20),budget DECIMAL(10,2)); INSERT INTO ethical_ai_2 (project_id,region,budget) VALUES (1,'North America',60000.00),(2,'Europe',40000.00),(3,'North America',70000.00),(4,'Europe',50000.00);
SELECT AVG(budget) FROM ethical_ai_2 WHERE region IN ('North America', 'Europe');
Update the artist name 'Eminem' to 'Marshall Mathers' in the MusicArtists table.
CREATE TABLE MusicArtists (artist_id INT,artist_name VARCHAR(50),genre VARCHAR(20));
UPDATE MusicArtists SET artist_name = 'Marshall Mathers' WHERE artist_name = 'Eminem';
Find the total number of registered users and the sum of their ages who signed up for the 'Toronto Raptors' newsletter in the 'Eastern' conference from the cities 'Toronto' and 'Montreal'. Assume the 'fan_registration' table has columns 'team_name', 'conference', 'city', 'registration_date' and 'age'.
CREATE TABLE TEAMS (team_name VARCHAR(50),conference VARCHAR(50)); INSERT INTO TEAMS (team_name,conference) VALUES ('Toronto Raptors','Eastern'); CREATE TABLE fan_registration (team_name VARCHAR(50),conference VARCHAR(50),city VARCHAR(50),registration_date DATE,age INT); INSERT INTO fan_registration (team_name,conference,city,registration_date,age) VALUES ('Toronto Raptors','Eastern','Toronto','2022-01-01',30),('Toronto Raptors','Eastern','Montreal','2022-01-02',35);
SELECT SUM(age), COUNT(*) FROM fan_registration WHERE team_name = 'Toronto Raptors' AND conference = 'Eastern' AND city IN ('Toronto', 'Montreal');
What is the total number of employees hired in the Latin America region in 2021, grouped by country?
CREATE TABLE employees (id INT,first_name VARCHAR(50),last_name VARCHAR(50),hire_date DATE,country VARCHAR(50)); INSERT INTO employees (id,first_name,last_name,hire_date,country) VALUES (6,'Carlos','Rodriguez','2021-06-15','Mexico');
SELECT e.country, COUNT(e.id) as total_hired FROM employees e WHERE e.hire_date >= '2021-01-01' AND e.hire_date < '2022-01-01' AND e.country IN (SELECT region FROM regions WHERE region_name = 'Latin America') GROUP BY e.country;
What is the average transportation cost for sustainable textiles imported from Europe?
CREATE TABLE SustainableTextiles (id INT,textile VARCHAR(50),origin VARCHAR(50),transportation_cost DECIMAL(5,2)); INSERT INTO SustainableTextiles (id,textile,origin,transportation_cost) VALUES (1,'Organic Cotton Fabric','Germany',12.50),(2,'Hemp Yarn','France',8.75),(3,'Tencel Fiber','Austria',15.00);
SELECT AVG(transportation_cost) FROM SustainableTextiles WHERE origin = 'Europe';
Which brands use the most natural ingredients?
CREATE TABLE Brand (BrandID INT,BrandName VARCHAR(50)); CREATE TABLE Product (ProductID INT,ProductName VARCHAR(50),BrandID INT,HasNaturalIngredients BOOLEAN); INSERT INTO Brand (BrandID,BrandName) VALUES (1,'Organic Beauty'),(2,'Natural Essence'),(3,'Green Glow'); INSERT INTO Product (ProductID,ProductName,BrandID,HasNaturalIngredients) VALUES (101,'Organic Lipstick',1,TRUE),(102,'Natural Mascara',2,TRUE),(103,'Vegan Foundation',2,FALSE),(104,'Eco-Friendly Blush',3,TRUE);
SELECT b.BrandName, COUNT(p.ProductID) as TotalProducts, SUM(p.HasNaturalIngredients) as NaturalIngredients FROM Brand b JOIN Product p ON b.BrandID = p.BrandID GROUP BY b.BrandName ORDER BY NaturalIngredients DESC;
Get the number of completed inclusion efforts in the InclusionEfforts table by location.
CREATE TABLE InclusionEfforts (effortID INT,effortType VARCHAR(50),location VARCHAR(50),effortStatus VARCHAR(50));
SELECT location, COUNT(*) FROM InclusionEfforts WHERE effortStatus = 'Completed' GROUP BY location;
What is the average age of mental health providers by county and race?
CREATE TABLE mental_health_providers (provider_id INT,age INT,county VARCHAR(255),race VARCHAR(255)); INSERT INTO mental_health_providers (provider_id,age,county,race) VALUES (1,45,'Orange County','Asian'); INSERT INTO mental_health_providers (provider_id,age,county,race) VALUES (2,50,'Los Angeles County','African American'); INSERT INTO mental_health_providers (provider_id,age,county,race) VALUES (3,35,'Orange County','Hispanic');
SELECT county, race, AVG(age) as avg_age FROM mental_health_providers GROUP BY county, race;
How many marine species are there in each ocean?
CREATE TABLE marine_species (id INT,name TEXT,ocean TEXT); INSERT INTO marine_species (id,name,ocean) VALUES (1,'Polar Bear','Arctic'); INSERT INTO marine_species (id,name,ocean) VALUES (2,'Krill','Southern'); INSERT INTO marine_species (id,name,ocean) VALUES (3,'Beluga Whale','Arctic'); INSERT INTO marine_species (id,name,ocean) VALUES (4,'Orca','Southern'); INSERT INTO marine_species (id,name,ocean) VALUES (5,'Tuna','Pacific');
SELECT ocean, COUNT(*) FROM marine_species GROUP BY ocean;
What is the difference in the number of visitors between the two exhibitions?
CREATE TABLE Exhibition1 (visitor_id INT,primary key(visitor_id)); INSERT INTO Exhibition1 VALUES (1),(2),(3); CREATE TABLE Exhibition2 (visitor_id INT,primary key(visitor_id)); INSERT INTO Exhibition2 VALUES (4),(5),(6),(7);
SELECT COUNT(Exhibition1.visitor_id) - COUNT(Exhibition2.visitor_id) AS difference FROM Exhibition1 LEFT JOIN Exhibition2 ON Exhibition1.visitor_id = Exhibition2.visitor_id;
How many digital interactions occurred in the museum's mobile app for visitors aged 18-35?
CREATE TABLE Visitors (VisitorID INT,Age INT,HasDownloadedApp BOOLEAN); INSERT INTO Visitors (VisitorID,Age,HasDownloadedApp) VALUES (1,22,true); INSERT INTO Visitors (VisitorID,Age,HasDownloadedApp) VALUES (2,30,true); INSERT INTO Visitors (VisitorID,Age,HasDownloadedApp) VALUES (3,40,false); CREATE TABLE DigitalInteractions (InteractionID INT,VisitorID INT,InteractionType VARCHAR(255)); INSERT INTO DigitalInteractions (InteractionID,VisitorID,InteractionType) VALUES (1,1,'ViewedExhibit'); INSERT INTO DigitalInteractions (InteractionID,VisitorID,InteractionType) VALUES (2,2,'DownloadedBrochure');
SELECT COUNT(DI.InteractionID) as TotalInteractions FROM DigitalInteractions DI INNER JOIN Visitors V ON DI.VisitorID = V.VisitorID WHERE V.Age BETWEEN 18 AND 35 AND V.HasDownloadedApp = true;
What is the average number of research grants awarded per year to the Department of Chemistry in the College of Science?
CREATE TABLE department (id INT,name VARCHAR(255),college VARCHAR(255));CREATE TABLE grant (id INT,department_id INT,title VARCHAR(255),amount DECIMAL(10,2),year INT);
SELECT AVG(amount) FROM grant g JOIN department d ON g.department_id = d.id WHERE d.name = 'Department of Chemistry' AND d.college = 'College of Science' GROUP BY g.year;
List all exhibitions and the number of unique visitors who engaged with digital installations in each
CREATE TABLE Exhibitions (id INT,name VARCHAR(100),location VARCHAR(50)); CREATE TABLE Visitor_Demographics (visitor_id INT,age INT,gender VARCHAR(10)); CREATE TABLE Digital_Interactions (visitor_id INT,interaction_date DATE,exhibition_id INT); INSERT INTO Exhibitions (id,name,location) VALUES (3,'Modern Art','France'); INSERT INTO Exhibitions (id,name,location) VALUES (4,'Science & Technology','Germany'); INSERT INTO Digital_Interactions (visitor_id,interaction_date,exhibition_id) VALUES (13,'2022-02-15',3); INSERT INTO Digital_Interactions (visitor_id,interaction_date,exhibition_id) VALUES (14,'2022-02-16',4);
SELECT Exhibitions.name, COUNT(DISTINCT Digital_Interactions.visitor_id) FROM Exhibitions JOIN Visits ON Exhibitions.id = Visits.exhibition_id JOIN Digital_Interactions ON Visits.visitor_id = Digital_Interactions.visitor_id GROUP BY Exhibitions.name;
How many OTA bookings were made for US hotels in Q1 2022?
CREATE TABLE otas (id INT PRIMARY KEY,hotel_id INT,bookings INT,booking_date DATE);
SELECT SUM(bookings) FROM otas WHERE country = 'USA' AND EXTRACT(QUARTER FROM booking_date) = 1 AND EXTRACT(YEAR FROM booking_date) = 2022;
What is the market share of vegan haircare brands in the Northeast?
CREATE TABLE haircare_brands(brand VARCHAR(255),type VARCHAR(255),region VARCHAR(255)); INSERT INTO haircare_brands(brand,type,region) VALUES('Brand X','vegan','Northeast'),('Brand Y','vegan','Southeast'),('Brand Z','cruelty-free','Northeast');
SELECT brand, (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM haircare_brands WHERE region = 'Northeast')) AS market_share FROM haircare_brands WHERE type = 'vegan' AND region = 'Northeast' GROUP BY brand;
Which menu items have been 86'd (removed) in the last week and their respective category?
CREATE TABLE eighty_six (menu_item_id INT,category VARCHAR(255),date DATE); INSERT INTO eighty_six VALUES (1,'Appetizers','2022-01-01'),(2,'Entrees','2022-02-01'),(3,'Drinks','2022-01-01');
SELECT e1.menu_item_id, e1.category FROM eighty_six e1 INNER JOIN (SELECT menu_item_id, category FROM menu_items EXCEPT SELECT menu_item_id, category FROM menu_items WHERE date > DATEADD(day, -7, GETDATE())) e2 ON e1.menu_item_id = e2.menu_item_id AND e1.category = e2.category;
Determine the difference in revenue between the first and last sale for each product.
CREATE TABLE sales (sale_id INT,product_name VARCHAR(255),sale_date DATE,revenue DECIMAL(10,2)); INSERT INTO sales VALUES (1,'ProductA','2022-01-01',100),(2,'ProductA','2022-01-05',120),(3,'ProductB','2022-01-03',150);
SELECT product_name, MAX(sale_date) - MIN(sale_date) as days_between, SUM(revenue) FILTER (WHERE sale_date = MAX(sale_date)) - SUM(revenue) FILTER (WHERE sale_date = MIN(sale_date)) as revenue_difference FROM sales GROUP BY product_name;
How many vulnerabilities have been discovered in the last year, categorized by their severity level?
CREATE TABLE vulnerabilities(id INT,severity VARCHAR(50),discovered_date DATE);
SELECT severity, COUNT(*) as total_vulnerabilities FROM vulnerabilities WHERE discovered_date > DATE(NOW()) - INTERVAL 365 DAY GROUP BY severity;
Find the number of soil samples and corresponding satellite image acquisition dates for 'Field15' and 'Field16' where image_date > '2021-07-01'?
CREATE TABLE Field15 (soil_sample_id INT,image_date DATETIME); INSERT INTO Field15 (soil_sample_id,image_date) VALUES (1,'2021-07-02 14:30:00'),(2,'2021-07-03 09:15:00'); CREATE TABLE Field16 (soil_sample_id INT,image_date DATETIME); INSERT INTO Field16 (soil_sample_id,image_date) VALUES (3,'2021-07-04 10:00:00'),(4,'2021-07-05 11:00:00');
SELECT COUNT(*) FROM (SELECT soil_sample_id FROM Field15 WHERE image_date > '2021-07-01' UNION SELECT soil_sample_id FROM Field16 WHERE image_date > '2021-07-01');
Find the intersection of mitigation and adaptation actions taken by countries in South America and Oceania
CREATE TABLE mitigation (id INT PRIMARY KEY,country VARCHAR(50),action VARCHAR(255)); INSERT INTO mitigation (id,country,action) VALUES (1,'Brazil','Reforestation'),(2,'Australia','Coastal Protection'); CREATE TABLE adaptation (id INT PRIMARY KEY,country VARCHAR(50),action VARCHAR(255)); INSERT INTO adaptation (id,country,action) VALUES (1,'Argentina','Water Management'),(2,'New Zealand','Disaster Risk Reduction');
SELECT m.action FROM mitigation m, adaptation a WHERE m.country = a.country AND m.action = a.action AND m.country IN ('Brazil', 'Australia', 'Argentina', 'New Zealand');
What was the change in hotel occupancy from 2020 to 2021, broken down by month?
CREATE TABLE monthly_occupancy(occupancy_id INT,year INT,month INT,occupancy DECIMAL);
SELECT EXTRACT(MONTH FROM date) AS month, (occupancy_2021 - occupancy_2020) / occupancy_2020 * 100 AS pct_change FROM (SELECT EXTRACT(MONTH FROM date) AS month, occupancy AS occupancy_2020 FROM monthly_occupancy WHERE year = 2020) subquery1 CROSS JOIN (SELECT EXTRACT(MONTH FROM date) AS month, occupancy AS occupancy_2021 FROM monthly_occupancy WHERE year = 2021) subquery2;
What is the total number of students enrolled in open pedagogy courses, by school district?
CREATE TABLE districts (district_id INT,district_name VARCHAR(255)); CREATE TABLE courses (course_id INT,district_id INT,course_type VARCHAR(255)); INSERT INTO districts (district_id,district_name) VALUES (1,'Downtown'),(2,'Uptown'); INSERT INTO courses (course_id,district_id,course_type) VALUES (1,1,'Traditional'),(2,1,'Open Pedagogy'),(3,2,'Traditional'),(4,2,'Open Pedagogy');
SELECT sd.district_name, COUNT(sc.course_id) as num_students FROM districts sd JOIN courses sc ON sd.district_id = sc.district_id WHERE sc.course_type = 'Open Pedagogy' GROUP BY sd.district_name;
What is the average salary of workers in the 'Manufacturing' industry who are part of a union?
CREATE TABLE workers (id INT,industry VARCHAR(255),salary FLOAT,union_member BOOLEAN); INSERT INTO workers (id,industry,salary,union_member) VALUES (1,'Manufacturing',50000.0,true),(2,'Manufacturing',55000.0,false),(3,'Retail',30000.0,true);
SELECT AVG(salary) FROM workers WHERE industry = 'Manufacturing' AND union_member = true;
Find countries with no satellites launched by 2022?
CREATE TABLE countries (country_id INT,country_name VARCHAR(100));CREATE TABLE satellites (satellite_id INT,country_id INT,launch_date DATE);
SELECT countries.country_name FROM countries LEFT JOIN satellites ON countries.country_id = satellites.country_id WHERE satellites.country_id IS NULL AND satellites.launch_date <= '2022-01-01';
What is the maximum number of vulnerabilities for a single software product?
CREATE TABLE vulnerabilities (id INT,product VARCHAR(255),severity INT); INSERT INTO vulnerabilities (id,product,severity) VALUES (1,'ProductA',5),(2,'ProductB',9),(3,'ProductA',3),(4,'ProductB',2),(5,'ProductC',1);
SELECT MAX(vulnerability_count) as max_vulnerabilities FROM (SELECT product, COUNT(*) as vulnerability_count FROM vulnerabilities GROUP BY product) as subquery;
What are the top 3 most common threat actors in the retail sector in the last 3 months?
CREATE TABLE threat_actors (threat_actor_id INT,threat_actor_name VARCHAR(255),sector VARCHAR(255)); INSERT INTO threat_actors (threat_actor_id,threat_actor_name,sector) VALUES (1,'APT28','Financial'),(2,'Lazarus Group','Healthcare'),(3,'Cozy Bear','Government'),(4,'Fancy Bear','Retail'),(5,'WannaCry','Retail');
SELECT threat_actor_name, COUNT(*) as incident_count FROM incidents INNER JOIN threat_actors ON incidents.sector = threat_actors.sector WHERE incidents.incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY threat_actor_name ORDER BY incident_count DESC LIMIT 3;
What is the distribution of lifelong learning program participants by gender?
CREATE TABLE lifelong_learning (participant_id INT,participant_gender VARCHAR(10),program_title VARCHAR(50)); INSERT INTO lifelong_learning (participant_id,participant_gender,program_title) VALUES (1,'Female','Coding for Beginners'),(2,'Male','Data Science Fundamentals'),(3,'Non-binary','Graphic Design for Professionals'),(4,'Female','Exploring World Cultures'),(5,'Male','Coding for Beginners'),(6,'Female','Data Science Fundamentals');
SELECT participant_gender, COUNT(participant_id) FROM lifelong_learning GROUP BY participant_gender;
What is the number of marine protected areas in the Atlantic Ocean and Indian Ocean?
CREATE TABLE marine_protected_areas (name TEXT,avg_depth REAL,ocean TEXT); INSERT INTO marine_protected_areas (name,avg_depth,ocean) VALUES ('Bermuda Atlantic National Marine Sanctuary',182.9,'Atlantic'),('Saba National Marine Park',20.0,'Atlantic'),('St. Eustatius National Marine Park',30.0,'Atlantic'),('Maldives Protected Areas',45.0,'Indian'),('Chagos Marine Protected Area',1000.0,'Indian');
SELECT ocean, COUNT(*) FROM marine_protected_areas WHERE ocean IN ('Atlantic', 'Indian') GROUP BY ocean;
What is the maximum revenue of restaurants in Tokyo?
CREATE TABLE Restaurants (id INT,name VARCHAR(50),city VARCHAR(20),revenue DECIMAL(10,2)); INSERT INTO Restaurants (id,name,city,revenue) VALUES (1,'SushiSensei','Tokyo',180000.00); INSERT INTO Restaurants (id,name,city,revenue) VALUES (2,'RamenRoyale','Tokyo',150000.00);
SELECT MAX(revenue) FROM Restaurants WHERE city = 'Tokyo';
What is the total number of network infrastructure investments made in the first half of 2021?
CREATE TABLE network_investments (investment_id INT,investment_date DATE); INSERT INTO network_investments (investment_id,investment_date) VALUES (1,'2021-01-15'),(2,'2021-03-01'),(3,'2020-12-01');
SELECT COUNT(*) FROM network_investments WHERE investment_date BETWEEN '2021-01-01' AND '2021-06-30';
What are the names of biotech startups from India that have not received funding in the last 2 years?
CREATE TABLE biotech_startups (startup_name VARCHAR(255),last_funding_date DATE,country VARCHAR(255)); INSERT INTO biotech_startups (startup_name,last_funding_date,country) VALUES ('StartupB','2022-01-01','India');
SELECT startup_name FROM biotech_startups WHERE last_funding_date < DATEADD(YEAR, -2, GETDATE()) AND country = 'India';
Summarize the national security budget for each department and the percentage of the total budget it represents.
CREATE TABLE national_security_budget (department VARCHAR(255),budget INT);
SELECT department, budget, budget * 100.0 / SUM(budget) OVER () as percentage_of_total FROM national_security_budget;
What are the total annual waste generation amounts for each location, grouped by material type?
CREATE TABLE waste_generation_by_material (location VARCHAR(50),material VARCHAR(50),amount INT,date DATE);INSERT INTO waste_generation_by_material (location,material,amount,date) VALUES ('Toronto','Glass',250,'2021-01-01');
SELECT location, material, SUM(amount) FROM waste_generation_by_material WHERE date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY location, material;
What was the average revenue for concerts in New York?
CREATE TABLE Concerts (city VARCHAR(20),revenue DECIMAL(5,2)); INSERT INTO Concerts (city,revenue) VALUES ('Los Angeles',50000.00),('New York',75000.00);
SELECT AVG(revenue) FROM Concerts WHERE city = 'New York';
How many workplaces are there in total in the state of Texas?
CREATE TABLE workplaces (id INT,name TEXT,state TEXT); INSERT INTO workplaces (id,name,state) VALUES (1,'LMN Company','Texas');
SELECT COUNT(*) FROM workplaces WHERE state = 'Texas';
How much was invested in 'solar_farm' projects in Q1 2022?
CREATE TABLE investments (id INT,investor VARCHAR(255),project_type VARCHAR(255),amount INT,date DATE); INSERT INTO investments (id,investor,project_type,amount,date) VALUES (6,'GreenCapital','solar_farm',400000,'2022-01-19'); INSERT INTO investments (id,investor,project_type,amount,date) VALUES (7,'SustainableFund','solar_farm',250000,'2022-03-15'); INSERT INTO investments (id,investor,project_type,amount,date) VALUES (8,'ImpactFirst','solar_farm',300000,'2021-11-29');
SELECT SUM(amount) FROM investments WHERE project_type = 'solar_farm' AND date BETWEEN '2022-01-01' AND '2022-03-31';
What is the difference in the total value of military equipment sales between 2019 and 2020, excluding sales to the US?
CREATE TABLE Military_Equipment_Sales(id INT,country VARCHAR(255),year INT,value FLOAT); INSERT INTO Military_Equipment_Sales(id,country,year,value) VALUES (1,'India',2020,50000000),(2,'India',2019,45000000),(3,'US',2020,80000000),(4,'India',2018,40000000),(5,'US',2019,75000000);
SELECT (SUM(CASE WHEN year = 2020 THEN value ELSE 0 END) - SUM(CASE WHEN year = 2019 THEN value ELSE 0 END)) - (SELECT SUM(value) FROM Military_Equipment_Sales WHERE country = 'US' AND year IN (2019, 2020)) as Difference FROM Military_Equipment_Sales WHERE country != 'US';
What is the total number of public works projects in the state of California, USA?
CREATE TABLE Projects (ProjectID INT,Name TEXT,Type TEXT,State TEXT,Country TEXT); INSERT INTO Projects (ProjectID,Name,Type,State,Country) VALUES (1,'Project1','Public Works','California','USA'); INSERT INTO Projects (ProjectID,Name,Type,State,Country) VALUES (2,'Project2','Transportation','California','USA'); INSERT INTO Projects (ProjectID,Name,Type,State,Country) VALUES (3,'Project3','Utilities','California','USA');
SELECT COUNT(*) FROM Projects WHERE State = 'California' AND Type = 'Public Works';
Identify the protected areas with lowest carbon sequestration in 2019.
CREATE TABLE protected_carbon_sequestration (id INT,name VARCHAR(255),year INT,sequestration FLOAT); INSERT INTO protected_carbon_sequestration (id,name,year,sequestration) VALUES (1,'Area A',2019,500.0),(2,'Area B',2019,400.0),(3,'Area C',2019,450.0);
SELECT name FROM protected_carbon_sequestration WHERE sequestration = (SELECT MIN(sequestration) FROM protected_carbon_sequestration WHERE year = 2019);
How many individuals have been served by access to justice initiatives in Europe since 2017?
CREATE TABLE initiatives (initiative_id INT,year INT,individuals_served INT); INSERT INTO initiatives (initiative_id,year,individuals_served) VALUES (1,2017,2000),(2,2018,3000); CREATE TABLE locations (initiative_id INT,region VARCHAR(20)); INSERT INTO locations (initiative_id,region) VALUES (1,'Europe'),(2,'North America');
SELECT SUM(initiatives.individuals_served) FROM initiatives INNER JOIN locations ON initiatives.initiative_id = locations.initiative_id WHERE locations.region = 'Europe' AND initiatives.year >= 2017;
Calculate the maximum dissolved oxygen level in each region for the month of June.
CREATE TABLE oxygen_levels (id INT,region VARCHAR(255),date DATE,dissolved_oxygen FLOAT); INSERT INTO oxygen_levels (id,region,date,dissolved_oxygen) VALUES (1,'North','2022-06-01',8.5),(2,'South','2022-06-15',7.8),(3,'East','2022-06-30',8.2);
SELECT region, MAX(dissolved_oxygen) FROM oxygen_levels WHERE date BETWEEN '2022-06-01' AND '2022-06-30' GROUP BY region;
Add a new transaction to the 'transactions' table
CREATE TABLE transactions (tx_id INT PRIMARY KEY,contract_address VARCHAR(42),sender VARCHAR(42),receiver VARCHAR(42),amount FLOAT,tx_time TIMESTAMP);
INSERT INTO transactions (tx_id, contract_address, sender, receiver, amount, tx_time) VALUES (1, '0xghi789', 'Alice', 'Bob', 100, '2023-04-10 14:20:30');
List all the positions in the 'crew' table
CREATE TABLE crew (id INT PRIMARY KEY,name VARCHAR(50),position VARCHAR(50),vessels_id INT,FOREIGN KEY (vessels_id) REFERENCES vessels(id));
SELECT DISTINCT position FROM crew;
List all sustainable fashion metrics for brands with a high customer satisfaction score (4 or above)?
CREATE TABLE BrandSustainability (brand VARCHAR(30),water_usage DECIMAL(4,2),energy_efficiency DECIMAL(4,2),customer_satisfaction INT); INSERT INTO BrandSustainability VALUES ('EcoFashions',1.25,0.85,4),('GreenThreads',1.10,0.90,5);
SELECT brand, water_usage, energy_efficiency FROM BrandSustainability WHERE customer_satisfaction >= 4;
What is the total biomass of fish for each species in the Arctic Ocean?
CREATE TABLE fish_species (species VARCHAR(255),biomass FLOAT,region VARCHAR(255)); INSERT INTO fish_species (species,biomass,region) VALUES ('Salmon',5000,'Arctic Ocean'),('Cod',7000,'Arctic Ocean'),('Halibut',8000,'Arctic Ocean');
SELECT species, SUM(biomass) as total_biomass FROM fish_species WHERE region = 'Arctic Ocean' GROUP BY species;
Which athlete wellbeing program had the highest access count in each region?
CREATE TABLE AthleteWellbeing (id INT,name VARCHAR(255),region VARCHAR(255),access_count INT); INSERT INTO AthleteWellbeing (id,name,region,access_count) VALUES (1,'Yoga','Pacific',40),(2,'Meditation','Pacific',60),(3,'Nutrition','Atlantic',30),(4,'Yoga','Atlantic',50),(5,'Meditation','Atlantic',80); CREATE TABLE FanDemographics (id INT,name VARCHAR(255),gender VARCHAR(50),region VARCHAR(50)); INSERT INTO FanDemographics (id,name,gender,region) VALUES (1,'FanA','Female','Pacific'),(2,'FanB','Male','Pacific'),(3,'FanC','Female','Atlantic');
SELECT region, name, access_count FROM (SELECT region, name, access_count, DENSE_RANK() OVER (PARTITION BY region ORDER BY access_count DESC) as rank FROM AthleteWellbeing) subquery WHERE rank = 1;
What is the rank of military equipment sales by country in the last 6 months?
CREATE TABLE military_sales_by_country (id INT,country VARCHAR(50),year INT,month INT,equipment_type VARCHAR(30),revenue DECIMAL(10,2));
SELECT country, ROW_NUMBER() OVER (ORDER BY SUM(revenue) DESC) as rank FROM military_sales_by_country WHERE sale_date >= DATEADD(month, -6, GETDATE()) GROUP BY country ORDER BY rank;
How many unique stops are there for each type of public transportation, excluding ferry stops?
CREATE TABLE stops_ext (id INT,name VARCHAR(50),type VARCHAR(10)); INSERT INTO stops_ext (id,name,type) VALUES (1,'Union Square','Subway'),(2,'Market St','Bus'),(3,'Ferry Building','Ferry'),(4,'Pier 39','Ferry'),(5,'Financial District','Bus'); CREATE TABLE ferry_routes_ext (id INT,name VARCHAR(50),type VARCHAR(10)); INSERT INTO ferry_routes_ext (id,name,type) VALUES (3,'Alcatraz Tour','Ferry'),(4,'Golden Gate Bay Cruise','Ferry'),(5,'Ferry to Sausalito','Ferry');
SELECT type, COUNT(DISTINCT name) FROM stops_ext WHERE type NOT IN (SELECT type FROM ferry_routes_ext) GROUP BY type;
Identify suppliers with a sustainability score below 70, and their average score.
CREATE TABLE suppliers (id INT,name VARCHAR(255),sustainability_score INT); INSERT INTO suppliers (id,name,sustainability_score) VALUES (1,'Supplier A',85),(2,'Supplier B',65),(3,'Supplier C',90),(4,'Supplier D',70);
SELECT AVG(sustainability_score) as avg_score, name FROM suppliers WHERE sustainability_score < 70 GROUP BY name;
Update the donation amount to $60 for donation ID 1
CREATE TABLE donations (donation_id INT,donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO donations (donation_id,donation_amount,donation_date) VALUES (1,50.00,'2021-01-01'),(2,100.00,'2021-02-14'),(3,250.00,'2021-12-31');
UPDATE donations SET donation_amount = 60.00 WHERE donation_id = 1;
Update the Amount for Pakistan in the 'ForeignMilitaryAid' table to 7000000 for the year 2010.
CREATE TABLE ForeignMilitaryAid (Year INT,Country VARCHAR(50),Amount DECIMAL(10,2)); INSERT INTO ForeignMilitaryAid (Year,Country,Amount) VALUES (2005,'Afghanistan',5000000),(2006,'Iraq',7000000),(2010,'Pakistan',6000000);
UPDATE ForeignMilitaryAid SET Amount = 7000000 WHERE Year = 2010 AND Country = 'Pakistan';
What is the total production of agroecological crops by country?
CREATE TABLE Country (id INT,name VARCHAR(255)); INSERT INTO Country (id,name) VALUES (1,'Bolivia'),(2,'Ecuador'),(3,'Peru'); CREATE TABLE Crop (id INT,name VARCHAR(255),country_id INT,production INT); INSERT INTO Crop (id,name,country_id,production) VALUES (1,'Quinoa',1,500),(2,'Potato',2,800),(3,'Corn',3,600),(4,'Quinoa',1,700);
SELECT Country.name, SUM(Crop.production) FROM Country INNER JOIN Crop ON Country.id = Crop.country_id WHERE Crop.name IN ('Quinoa', 'Potato', 'Corn') GROUP BY Country.name;
What was the total number of volunteer hours per program category in Q2 2023?
CREATE TABLE VolunteerHours (volunteer_id INT,program_category VARCHAR(255),volunteer_hours DECIMAL(10,2),volunteer_date DATE); INSERT INTO VolunteerHours (volunteer_id,program_category,volunteer_hours,volunteer_date) VALUES (8,'Arts',10,'2023-04-02'),(9,'Education',15,'2023-04-03'),(10,'Environment',20,'2023-04-04'),(11,'Education',12,'2023-05-05'),(12,'Arts',25,'2023-05-06');
SELECT program_category, SUM(volunteer_hours) as total_hours FROM VolunteerHours WHERE volunteer_date BETWEEN '2023-04-01' AND '2023-06-30' GROUP BY program_category;
What is the total pro-bono work hours for cases won by attorneys who joined the firm in 2017 or earlier?
CREATE TABLE Attorneys (AttorneyID INT,JoinYear INT,ProBonoHours INT); INSERT INTO Attorneys (AttorneyID,JoinYear,ProBonoHours) VALUES (1,2015,200),(2,2017,300),(3,2019,150); CREATE TABLE Cases (CaseID INT,AttorneyID INT,CaseOutcome VARCHAR(10)); INSERT INTO Cases (CaseID,AttorneyID,CaseOutcome) VALUES (101,1,'Won'),(102,2,'Lost'),(103,3,'Won');
SELECT SUM(ProBonoHours) FROM Attorneys JOIN Cases ON Attorneys.AttorneyID = Cases.AttorneyID WHERE CaseOutcome = 'Won' AND JoinYear <= 2017;
List all policies for policyholders who are 30 or younger.
CREATE TABLE Policyholders (PolicyholderID INT,Age INT,Region VARCHAR(10)); CREATE TABLE Claims (ClaimID INT,PolicyID INT,Amount INT,Region VARCHAR(10)); INSERT INTO Policyholders (PolicyholderID,Age,Region) VALUES (1,35,'West'); INSERT INTO Policyholders (PolicyholderID,Age,Region) VALUES (2,19,'East'); INSERT INTO Claims (ClaimID,PolicyID,Amount,Region) VALUES (101,1,500,'North'); INSERT INTO Claims (ClaimID,PolicyID,Amount,Region) VALUES (102,2,750,'South');
SELECT * FROM Claims INNER JOIN Policyholders ON Claims.PolicyholderID = Policyholders.PolicyholderID WHERE Policyholders.Age <= 30;
Show the percentage of accessible and non-accessible vehicles in the fleet
CREATE TABLE accessibility_stats (vehicle_id INT,vehicle_type VARCHAR(10),accessible BOOLEAN); INSERT INTO accessibility_stats (vehicle_id,vehicle_type,accessible) VALUES (1,'Bus',true),(2,'Train',true),(3,'Bus',false),(4,'Tram',true);
SELECT vehicle_type, ROUND(100.0 * SUM(accessible) / COUNT(*)) as accessible_percentage, ROUND(100.0 * SUM(NOT accessible) / COUNT(*)) as non_accessible_percentage FROM accessibility_stats GROUP BY vehicle_type;
Who is the most popular artist in Canada based on concert ticket sales?
CREATE TABLE concerts (id INT,artist VARCHAR(50),city VARCHAR(50),revenue FLOAT); INSERT INTO concerts (id,artist,city,revenue) VALUES (1,'The Beatles','Vancouver',10000.0),(2,'Queen','Toronto',15000.0);
SELECT artist, MAX(revenue) FROM concerts WHERE city = 'Canada';
What is the total number of eco-certified destinations in Oceania?
CREATE TABLE destinations (destination_id INT,name VARCHAR(50),country_id INT,is_eco_certified BOOLEAN); INSERT INTO destinations (destination_id,name,country_id,is_eco_certified) VALUES (11,'Great Barrier Reef',14,true); INSERT INTO destinations (destination_id,name,country_id,is_eco_certified) VALUES (12,'Fiordland National Park',15,true);
SELECT COUNT(*) FROM destinations d WHERE d.is_eco_certified = true AND d.country_id IN (SELECT country_id FROM countries WHERE continent = 'Oceania');
How many traditional artists are engaged in each cultural preservation program?
CREATE TABLE traditional_artists (id INT,name VARCHAR(50),program VARCHAR(50),location VARCHAR(50)); INSERT INTO traditional_artists (id,name,program,location) VALUES (1,'John Doe','Weaving','Peru'),(2,'Jane Smith','Pottery','Bolivia');
SELECT program, COUNT(*) FROM traditional_artists GROUP BY program;
Identify the ocean floor mapping project sites with no species observed.
CREATE SCHEMA MarineLife;CREATE TABLE SpeciesObservation(site_id INT,species_id INT);CREATE TABLE OceanFloorMapping(site_id INT,site_name TEXT);INSERT INTO SpeciesObservation(site_id,species_id) VALUES (1,1),(1,2),(2,1),(3,3);INSERT INTO OceanFloorMapping(site_id,site_name) VALUES (1,'Site1'),(2,'Site2'),(3,'Site3'),(4,'Site4');
SELECT f.site_id, f.site_name FROM MarineLife.OceanFloorMapping f LEFT JOIN MarineLife.SpeciesObservation s ON f.site_id = s.site_id WHERE s.site_id IS NULL;
What is the total revenue generated from sustainable materials in the last quarter?
CREATE TABLE Sales (id INT,date DATE,revenue DECIMAL,sustainable BOOLEAN); CREATE VIEW LastQuarter AS SELECT DATEADD(quarter,-1,GETDATE()) as start_date,GETDATE() as end_date;
SELECT SUM(revenue) FROM Sales WHERE sustainable = 1 AND date BETWEEN (SELECT start_date FROM LastQuarter) AND (SELECT end_date FROM LastQuarter);
What is the minimum budget for any climate adaptation project in Asia?
CREATE TABLE project_budget (project_id INT,budget DECIMAL); INSERT INTO project_budget (project_id,budget) VALUES (1,5000000.00);
SELECT MIN(budget) FROM project_budget JOIN climate_project ON project_budget.project_id = climate_project.project_id WHERE climate_project.project_type = 'Adaptation' AND climate_project.project_region = 'Asia';
What is the minimum temperature for each crop in the 'crop_temperatures' view?
CREATE VIEW crop_temperatures AS SELECT crops.crop_name,field_sensors.temperature,field_sensors.measurement_date FROM crops JOIN field_sensors ON crops.field_id = field_sensors.field_id;
SELECT crop_name, MIN(temperature) as min_temp FROM crop_temperatures GROUP BY crop_name;
What is the ID of the genetic research related to 'Gene Therapy' that uses equipment with a cost above the average?
CREATE TABLE genetic_research (research_id INT,topic VARCHAR(255),equipment_cost FLOAT); INSERT INTO genetic_research (research_id,topic,equipment_cost) VALUES (1,'Gene Therapy',150000),(2,'Genetic Engineering',200000),(3,'CRISPR',300000); CREATE TABLE equipment (equipment_id INT,research_id INT,cost FLOAT); INSERT INTO equipment (equipment_id,research_id,cost) VALUES (1,1,120000),(2,2,220000),(3,3,350000);
SELECT research_id FROM genetic_research WHERE topic = 'Gene Therapy' AND equipment_cost > (SELECT AVG(cost) FROM equipment) INTERSECT SELECT research_id FROM equipment;
Find the average response time for 'emergency' incidents
CREATE TABLE incidents (incident_id INT,incident_type VARCHAR(50),location VARCHAR(50),date_time DATETIME); CREATE TABLE response_times (incident_id INT,incident_type VARCHAR(50),response_time INT);
SELECT AVG(response_time) FROM incidents JOIN response_times ON incidents.incident_id = response_times.incident_id WHERE incidents.incident_type = 'emergency';
What is the distribution of community health workers by training type?
CREATE TABLE CommunityHealthWorkerTrainings (WorkerID INT,Training VARCHAR(50)); INSERT INTO CommunityHealthWorkerTrainings (WorkerID,Training) VALUES (1,'Cultural Competency'),(2,'Mental Health First Aid'),(3,'Crisis Prevention'),(4,'Cultural Competency'),(5,'Motivational Interviewing');
SELECT Training, COUNT(*) as NumWorkers FROM CommunityHealthWorkerTrainings GROUP BY Training;
What is the average carbon sequestration in 'Boreal Forests' over the past 5 years?
CREATE TABLE BorealForests (region VARCHAR(20),year INT,carbon_sequestration FLOAT); INSERT INTO BorealForests (region,year,carbon_sequestration) VALUES ('Boreal Forests',2017,55.66),('Boreal Forests',2018,56.77),('Boreal Forests',2019,57.88),('Boreal Forests',2020,58.99),('Boreal Forests',2021,60.11);
SELECT AVG(carbon_sequestration) FROM BorealForests WHERE region = 'Boreal Forests' AND year BETWEEN 2017 AND 2021;
What is the total number of certified sustainable tourism operators in Southeast Asia?
CREATE TABLE tourism_operators (id INT,operator_name VARCHAR(30),location VARCHAR(20),certified BOOLEAN); INSERT INTO tourism_operators (id,operator_name,location,certified) VALUES (1,'Asian Eco Tours','Thailand',TRUE),(2,'Green Travel Indonesia','Indonesia',TRUE),(3,'Eco Adventures','Malaysia',FALSE);
SELECT COUNT(*) FROM tourism_operators WHERE certified = TRUE AND location IN ('Thailand', 'Indonesia', 'Malaysia', 'Vietnam', 'Cambodia', 'Philippines', 'Myanmar', 'Laos', 'Singapore', 'Brunei');
List the top 3 countries with the highest number of models developed by underrepresented communities.
CREATE TABLE models_underrepresented (model_id INT,country TEXT,community TEXT); INSERT INTO models_underrepresented (model_id,country,community) VALUES (101,'USA','African American'),(102,'USA','Hispanic'),(103,'Canada','First Nations'),(104,'USA','Asian American'),(105,'India','Dalit');
SELECT country, COUNT(*) as num_models FROM models_underrepresented WHERE community IS NOT NULL GROUP BY country ORDER BY num_models DESC LIMIT 3;
What languages do healthcare providers who have an East Asian background speak?
CREATE TABLE CulturalCompetency (id INT,healthcareProvider VARCHAR(50),languageSpoken VARCHAR(50),culturalBackground VARCHAR(50)); INSERT INTO CulturalCompetency (id,healthcareProvider,languageSpoken,culturalBackground) VALUES (1,'Dr. Meera Patel','English,Hindi','South Asian'),(2,'Dr. Sung Lee','Korean,English','East Asian');
SELECT healthcareProvider, languageSpoken FROM CulturalCompetency WHERE culturalBackground = 'East Asian';