instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Identify the gallery in Vienna with the highest total revenue and display the gallery name and total revenue.
CREATE TABLE Exhibitions (id INT,gallery_id INT,city VARCHAR(20),revenue FLOAT); INSERT INTO Exhibitions (id,gallery_id,city,revenue) VALUES (1,1,'Vienna',15000),(2,2,'Vienna',12000),(3,3,'Vienna',20000);
SELECT g.name, SUM(e.revenue) as total_revenue FROM Exhibitions e JOIN Galleries g ON e.gallery_id = g.id WHERE g.city = 'Vienna' GROUP BY g.name ORDER BY total_revenue DESC LIMIT 1;
What is the average temperature recorded in the 'arctic_weather' table for each month?
CREATE TABLE arctic_weather (id INT,date DATE,temperature FLOAT); INSERT INTO arctic_weather (id,date,temperature) VALUES (1,'2021-01-01',10),(2,'2021-02-01',12),(3,'2021-03-01',15);
SELECT MONTH(date) AS month, AVG(temperature) AS avg_temperature FROM arctic_weather GROUP BY month;
What is the maximum number of years a traditional music form has been preserved in each province of India?
CREATE TABLE provinces (id INT,name TEXT); INSERT INTO provinces (id,name) VALUES (1,'Uttar Pradesh'),(2,'Maharashtra'),(3,'Andhra Pradesh'); CREATE TABLE music_forms (id INT,province_id INT,name TEXT,year_preserved INT); INSERT INTO music_forms (id,province_id,name,year_preserved) VALUES (1,1,'Hindustani',1000),(2,1,'Qawwali',800),(3,2,'Marathi',700),(4,2,'Bharud',500),(5,3,'Carnatic',1200),(6,3,'Harikatha',900);
SELECT p.name, MAX(mf.year_preserved) FROM provinces p JOIN music_forms mf ON p.id = mf.province_id GROUP BY p.id;
Calculate the total cost and average CO2 emissions for projects in the 'sustainability' schema where the name contains the word 'green'
CREATE SCHEMA IF NOT EXISTS sustainability; CREATE TABLE sustainability.projects (id INT,name VARCHAR(100),cost FLOAT,co2_emissions FLOAT); INSERT INTO sustainability.projects (id,name,cost,co2_emissions) VALUES (1,'Green Roof Installation',250000,10),(2,'Solar Panel Installation',1000000,20),(3,'Wind Turbine Installation',1500000,30);
SELECT SUM(cost), AVG(co2_emissions) FROM sustainability.projects WHERE name LIKE '%green%';
List all projects that were completed before their scheduled completion date
CREATE TABLE Project (id INT,name VARCHAR(255),scheduled_completion_date DATE,actual_completion_date DATE); INSERT INTO Project (id,name,scheduled_completion_date,actual_completion_date) VALUES (1,'Project A','2020-12-31','2020-12-15'),(2,'Project B','2021-03-31','2022-04-15'),(3,'Project C','2022-06-30','2022-06-30');
SELECT * FROM Project WHERE actual_completion_date < scheduled_completion_date;
How many countries in Antarctica have been promoting sustainable tourism since 2019?
CREATE TABLE Sustainable_Practices (id INT PRIMARY KEY,country_id INT,certification_date DATE,FOREIGN KEY (country_id) REFERENCES Countries(id)); INSERT INTO Sustainable_Practices (id,country_id,certification_date) VALUES (1,14,'2019-07-01');
SELECT COUNT(DISTINCT c.id) as country_count FROM Countries c INNER JOIN Sustainable_Practices sp ON c.id = sp.country_id WHERE c.continent = 'Antarctica' AND sp.certification_date >= '2019-01-01';
How many sustainable accommodations are there in North America with a rating of 4 or higher?
CREATE TABLE Accommodations (accommodation_id INT,name VARCHAR(50),country VARCHAR(50),sustainability_rating INT); INSERT INTO Accommodations (accommodation_id,name,country,sustainability_rating) VALUES (1,'Eco Resort','Canada',5); INSERT INTO Accommodations (accommodation_id,name,country,sustainability_rating) VALUES (2,'Green Hotel','USA',4);
SELECT COUNT(*) FROM Accommodations WHERE country IN ('North America') AND sustainability_rating >= 4;
What is the maximum depth in the 'Trenches' table?
CREATE TABLE Trenches (TrenchID INT PRIMARY KEY,TrenchName TEXT,MaxDepth FLOAT);
SELECT MAX(MaxDepth) FROM Trenches;
What is the minimum number of views of videos in the 'music' category?
CREATE TABLE videos_3 (id INT,title TEXT,views INT,category TEXT); INSERT INTO videos_3 (id,title,views,category) VALUES (1,'Video1',5000,'music'),(2,'Video2',7000,'music');
SELECT MIN(views) FROM videos_3 WHERE category = 'music';
What is the total media representation score for each region?
CREATE TABLE media_representation (id INT,user_id INT,country VARCHAR(50),region VARCHAR(50),score INT); INSERT INTO media_representation (id,user_id,country,region,score) VALUES (1,1,'China','Asia',80),(2,2,'Japan','Asia',85),(3,3,'India','Asia',75),(4,4,'Indonesia','Asia',70),(5,5,'Australia','Australia',82),(6,6,'New Zealand','Australia',80),(7,7,'United States','North America',78),(8,8,'Canada','North America',75),(9,9,'Mexico','North America',73),(10,10,'Brazil','South America',71),(11,11,'Argentina','South America',69),(12,12,'South Africa','Africa',77),(13,13,'Egypt','Africa',74),(14,14,'Nigeria','Africa',72);
SELECT region, SUM(score) as total_score FROM media_representation GROUP BY region;
What is the total runtime (in minutes) of all shows produced in the US?
CREATE TABLE shows (id INT,title VARCHAR(100),genre VARCHAR(50),country VARCHAR(50),release_year INT,runtime INT);
SELECT SUM(runtime) FROM shows WHERE country = 'US';
What is the daily revenue from each category in the last month?
CREATE TABLE orders (order_id INT,order_date DATETIME,menu_id INT,quantity INT,price FLOAT);
SELECT DATE(order_date) as order_date, category, SUM(price * quantity) as daily_revenue FROM orders JOIN menus ON orders.menu_id = menus.menu_id GROUP BY DATE(order_date), category ORDER BY order_date, daily_revenue DESC;
What is the total waste generated by each menu item category in the past year?
CREATE TABLE Waste (waste_id INT PRIMARY KEY,menu_item_category VARCHAR(50),waste_quantity DECIMAL(5,2),waste_date DATE);
SELECT menu_item_category, SUM(waste_quantity) FROM Waste WHERE waste_date >= DATEADD(year, -1, GETDATE()) GROUP BY menu_item_category;
What is the total value of military equipment sales by country for 2021?
CREATE TABLE CountrySales (id INT PRIMARY KEY,year INT,country VARCHAR(50),sale_value FLOAT); INSERT INTO CountrySales (id,year,country,sale_value) VALUES (1,2021,'USA',10000000); INSERT INTO CountrySales (id,year,country,sale_value) VALUES (2,2021,'Germany',8000000);
SELECT year, country, SUM(sale_value) FROM CountrySales GROUP BY year, country;
Get the total production of each product by quarter in 2021
mining_production(mine_id,product,production_quantity,production_date)
SELECT product, DATE_TRUNC('quarter', production_date) AS production_quarter, SUM(production_quantity) AS total_production FROM mining_production WHERE production_date >= '2021-01-01' AND production_date < '2022-01-01' GROUP BY product, production_quarter;
What is the total gold production by country in the last 3 years?
CREATE TABLE yearly_gold_production (id INT,country VARCHAR(255),year INT,quantity INT); INSERT INTO yearly_gold_production (id,country,year,quantity) VALUES (1,'Australia',2019,300),(2,'China',2019,400),(3,'Russia',2019,250),(4,'Australia',2020,320),(5,'China',2020,420),(6,'Russia',2020,260),(7,'Australia',2021,350),(8,'China',2021,450),(9,'Russia',2021,270);
SELECT country, SUM(quantity) as total_gold_production FROM yearly_gold_production WHERE year BETWEEN 2019 AND 2021 GROUP BY country;
How many female engineers are there in 'australian_mines'?
CREATE SCHEMA if not exists australia_schema;CREATE TABLE australia_schema.australian_mines (id INT,name VARCHAR,gender VARCHAR,role VARCHAR);INSERT INTO australia_schema.australian_mines (id,name,gender,role) VALUES (1,'S worker','Female','Engineer'),(2,'T engineer','Male','Engineer');
SELECT COUNT(*) FROM australia_schema.australian_mines WHERE gender = 'Female' AND role = 'Engineer';
What is the average monthly data usage for mobile subscribers in Africa?
CREATE TABLE mobile_subscribers (id INT,region VARCHAR(20),data_usage INT,usage_date DATE);
SELECT region, AVG(data_usage) FROM mobile_subscribers WHERE region = 'Africa' GROUP BY region;
What is the minimum subscription fee for 'LTE' technology in the 'subscriber_tech' table?
CREATE TABLE subscriber_tech (subscriber_id INT,subscription_start_date DATE,technology VARCHAR(50),subscription_fee DECIMAL(10,2)); INSERT INTO subscriber_tech (subscriber_id,subscription_start_date,technology,subscription_fee) VALUES (1,'2020-01-01','Fiber',50.00),(2,'2019-06-15','Cable',40.00),(5,'2021-02-20','LTE',30.00),(6,'2022-03-15','LTE',25.00);
SELECT MIN(subscription_fee) as min_fee FROM subscriber_tech WHERE technology = 'LTE';
What is the most popular genre among users?
CREATE TABLE users (id INT,name VARCHAR(50),favorite_genre VARCHAR(50)); INSERT INTO users (id,name,favorite_genre) VALUES (1,'Alice','Pop'),(2,'Bob','Rock'),(3,'Charlie','Rock'),(4,'David','Jazz'),(5,'Eve','Pop');
SELECT favorite_genre, COUNT(*) as genre_count FROM users GROUP BY favorite_genre ORDER BY genre_count DESC LIMIT 1;
What is the total number of concert ticket sales for artists who released their first album between 2015 and 2017?
CREATE TABLE ConcertTicketSales (id INT,year INT,artist_id INT); CREATE TABLE ArtistAlbums (id INT,artist_id INT,year INT);
SELECT COUNT(DISTINCT cts.artist_id) FROM ConcertTicketSales cts JOIN ArtistAlbums a ON cts.artist_id = a.artist_id WHERE a.year BETWEEN 2015 AND 2017;
What is the total amount donated by each organization in Q1 2021, and what percentage of the total does each organization represent?
CREATE TABLE organizations (id INT,name TEXT,donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO organizations (id,name,donation_amount,donation_date) VALUES (1,'ABC Corp',1500.00,'2021-01-05'); INSERT INTO organizations (id,name,donation_amount,donation_date) VALUES (2,'XYZ Inc',2500.00,'2021-03-12');
SELECT o.name, SUM(o.donation_amount) AS total_donation, ROUND(100 * SUM(o.donation_amount) / (SELECT SUM(donation_amount) FROM organizations WHERE donation_date BETWEEN '2021-01-01' AND '2021-03-31'), 2) AS percentage FROM organizations o WHERE donation_date BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY o.name;
How many deep-sea exploration missions were conducted in the Indian Ocean by each country in 2018?
CREATE TABLE deep_sea_exploration_missions (mission_id INT,mission_name VARCHAR(255),mission_date DATE,ocean_name VARCHAR(255),country VARCHAR(255)); INSERT INTO deep_sea_exploration_missions (mission_id,mission_name,mission_date,ocean_name,country) VALUES (1,'Mariana Trench Exploration','2018-01-01','Pacific Ocean','USA'),(2,'Indian Ocean Ridges Study','2018-07-01','Indian Ocean','India'),(3,'Atlantic Ocean Floor Mapping','2018-10-01','Atlantic Ocean','UK');
SELECT ocean_name, country, COUNT(*) AS num_missions FROM deep_sea_exploration_missions WHERE YEAR(mission_date) = 2018 AND ocean_name = 'Indian Ocean' GROUP BY ocean_name, country;
Which vessels have been involved in accidents in the Pacific Ocean?
CREATE TABLE vessels (vessel_id INT,name VARCHAR(100)); CREATE TABLE maritime_accidents (accident_id INT,vessel_id INT,country VARCHAR(100),ocean VARCHAR(100)); INSERT INTO vessels (vessel_id,name) VALUES (1,'Sea Serpent'); INSERT INTO maritime_accidents (accident_id,vessel_id,country,ocean) VALUES (1,1,'Canada','Pacific Ocean');
SELECT vessels.name FROM vessels INNER JOIN maritime_accidents ON vessels.vessel_id = maritime_accidents.vessel_id WHERE maritime_accidents.ocean = 'Pacific Ocean';
List all organizations in the 'Organizations' table with a mission_area of 'Education'?
CREATE TABLE Organizations (org_id INT,name VARCHAR(50),mission_area VARCHAR(20));
SELECT * FROM Organizations WHERE mission_area = 'Education';
Find the total budget allocated for public services in each state.
CREATE SCHEMA gov_data;CREATE TABLE gov_data.budget_allocation (state VARCHAR(20),service VARCHAR(20),budget INT); INSERT INTO gov_data.budget_allocation (state,service,budget) VALUES ('California','Education',3000000),('California','Healthcare',4000000),('Texas','Education',2000000),('Texas','Healthcare',2500000),('New York','Education',2500000),('New York','Healthcare',3000000);
SELECT state, SUM(budget) as total_budget FROM gov_data.budget_allocation GROUP BY state;
Which public service had the highest citizen satisfaction score in Q3 2021?
CREATE TABLE Satisfaction (Quarter TEXT,Service TEXT,Score INTEGER); INSERT INTO Satisfaction (Quarter,Service,Score) VALUES ('Q3 2021','Education',85),('Q3 2021','Healthcare',80),('Q3 2021','Transportation',90);
SELECT Service, MAX(Score) FROM Satisfaction WHERE Quarter = 'Q3 2021' GROUP BY Service;
How many properties in the table 'sustainable_developments' are located in low-income areas?
CREATE TABLE sustainable_developments (id INT,property_name VARCHAR(50),low_income_area BOOLEAN); INSERT INTO sustainable_developments (id,property_name,low_income_area) VALUES (1,'Green Heights',true),(2,'Eco Estates',false),(3,'Solar Vista',true);
SELECT COUNT(*) FROM sustainable_developments WHERE low_income_area = true;
What is the average daily revenue for restaurants serving 'Vegan' cuisine in the city of 'Los Angeles' for the first quarter of 2022?
CREATE TABLE restaurant_revenue(restaurant_id INT,cuisine VARCHAR(255),daily_revenue DECIMAL(10,2),revenue_date DATE);
SELECT AVG(daily_revenue) FROM restaurant_revenue WHERE cuisine = 'Vegan' AND city = 'Los Angeles' AND revenue_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY cuisine, city;
What was the total revenue for 'Organic Veggie Pizza'?
CREATE TABLE restaurants (restaurant_id INT,name VARCHAR(255)); INSERT INTO restaurants (restaurant_id,name) VALUES (1,'Pizza Hut'); CREATE TABLE menu_items (menu_item_id INT,name VARCHAR(255),price DECIMAL(5,2),restaurant_id INT); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (1,'Organic Veggie Pizza',12.99,1);
SELECT SUM(price) FROM menu_items WHERE name = 'Organic Veggie Pizza' AND restaurant_id = 1;
What is the total mass of the Juno spacecraft in kg?
CREATE TABLE spacecraft (name TEXT,mass_kg INTEGER); INSERT INTO spacecraft (name,mass_kg) VALUES ('Juno',3625),('Voyager 1',722),('Cassini',5600);
SELECT mass_kg FROM spacecraft WHERE name = 'Juno';
List all unique medical conditions of astronauts from Russia.
CREATE TABLE AstronautMedical (id INT,astronaut_id INT,nationality VARCHAR(50),medical_condition VARCHAR(50)); INSERT INTO AstronautMedical (id,astronaut_id,nationality,medical_condition) VALUES (1,101,'Russia','Anemia'); INSERT INTO AstronautMedical (id,astronaut_id,nationality,medical_condition) VALUES (2,102,'Russia','Dehydration'); INSERT INTO AstronautMedical (id,astronaut_id,nationality,medical_condition) VALUES (3,103,'USA','Motion Sickness');
SELECT DISTINCT medical_condition FROM AstronautMedical WHERE nationality = 'Russia';
Which spacecraft have a mass greater than 1000 tons?
CREATE TABLE spacecraft (id INT,name VARCHAR(255),manufacturer VARCHAR(255),mass FLOAT); INSERT INTO spacecraft (id,name,manufacturer,mass) VALUES (1,'Voyager 1','Galactic Pioneers Inc.',770.),(2,'Voyager 2','Galactic Pioneers Inc.',780.),(3,'New Horizons','Space Explorers Ltd.',1010.);
SELECT name FROM spacecraft WHERE mass > 1000;
How many unique IP addresses have been used for login attempts in the last month?
CREATE TABLE login_attempts (user_id INT,ip_address VARCHAR(255),timestamp TIMESTAMP); INSERT INTO login_attempts (user_id,ip_address,timestamp) VALUES (1,'192.168.1.1','2022-01-01 10:00:00'),(2,'192.168.1.2','2022-01-02 15:30:00'),(1,'192.168.1.1','2022-01-03 08:45:00'),(3,'192.168.1.3','2022-01-04 14:20:00'),(4,'192.168.1.4','2022-01-05 21:00:00'),(1,'192.168.1.1','2022-01-06 06:15:00'),(5,'192.168.1.5','2022-01-07 12:30:00'),(1,'192.168.1.1','2022-01-07 19:45:00');
SELECT COUNT(DISTINCT ip_address) as unique_ip_addresses FROM login_attempts WHERE timestamp >= '2022-01-01 00:00:00' AND timestamp < '2022-02-01 00:00:00';
What are the top 5 most vulnerable systems in the IT department based on their average vulnerability scores in the last month?
CREATE TABLE systems (system_id INT,system_name VARCHAR(255),department VARCHAR(255),vulnerability_score DECIMAL(5,2));INSERT INTO systems (system_id,system_name,department,vulnerability_score) VALUES (1,'Web Server 1','IT',7.5),(2,'Database Server 1','IT',6.3),(3,'Email Server 1','IT',8.1),(4,'Firewall 1','IT',4.9),(5,'Web Server 2','IT',7.9),(6,'Network Switch 1','Network',5.1);
SELECT system_name, AVG(vulnerability_score) as avg_vulnerability_score FROM systems WHERE department = 'IT' GROUP BY system_name ORDER BY avg_vulnerability_score DESC LIMIT 5;
What is the percentage of autonomous vehicles sold in the US that are electric?
CREATE TABLE AutonomousVehicles (Make VARCHAR(50),Model VARCHAR(50),Year INT,Country VARCHAR(50),Type VARCHAR(50),Sales INT);
SELECT 100.0 * SUM(CASE WHEN Type = 'Electric' THEN Sales ELSE 0 END) / SUM(Sales) AS Percentage FROM AutonomousVehicles WHERE Country = 'United States';
What is the total number of bike-share trips in a month in New York City?
CREATE TABLE monthly_bike_trips (trip_id INT,city VARCHAR(20),trips_per_month INT); INSERT INTO monthly_bike_trips (trip_id,city,trips_per_month) VALUES (1,'New York City',90000),(2,'New York City',85000),(3,'New York City',95000);
SELECT SUM(trips_per_month) FROM monthly_bike_trips WHERE city = 'New York City';
What are the total sales of each product category in the year 2020?
CREATE TABLE product_sales (product_id INT,product_category VARCHAR(50),sale_date DATE,revenue DECIMAL(10,2)); CREATE TABLE products (product_id INT,product_name VARCHAR(50)); CREATE VIEW product_sales_view AS SELECT product_id,product_category,EXTRACT(YEAR FROM sale_date) AS sale_year,SUM(revenue) AS total_revenue FROM product_sales JOIN products ON product_sales.product_id = products.product_id GROUP BY product_id,product_category,sale_year;
SELECT product_category, total_revenue FROM product_sales_view WHERE sale_year = 2020 GROUP BY product_category;
Who is the top customer by sales in 2022?
CREATE TABLE customers (customer_id INT,total_sales_2022 FLOAT); INSERT INTO customers (customer_id,total_sales_2022) VALUES (1,25000.0),(2,30000.0),(3,22000.0),(4,35000.0);
SELECT customer_id, total_sales_2022 FROM customers ORDER BY total_sales_2022 DESC LIMIT 1;
Update 'John Smith's' risk assessment score to 700 in the risk_assessment_table
CREATE TABLE risk_assessment_table (assessment_id INT,policy_holder TEXT,risk_score INT); INSERT INTO risk_assessment_table (assessment_id,policy_holder,risk_score) VALUES (1,'John Smith',650),(2,'Jane Doe',500),(3,'Mike Johnson',800);
UPDATE risk_assessment_table SET risk_score = 700 WHERE policy_holder = 'John Smith';
Calculate the percentage of employees in each industry, categorized by union status
CREATE TABLE employees (id INT,name VARCHAR(255),industry VARCHAR(255),union_status VARCHAR(255),num_employees INT); INSERT INTO employees (id,name,industry,union_status,num_employees) VALUES (1,'John Doe','Manufacturing','Union',50),(2,'Jane Smith','Manufacturing','Non-Union',75),(3,'Bob Johnson','Retail','Union',30),(4,'Alice Williams','Retail','Union',40),(5,'Charlie Brown','Construction','Non-Union',100);
SELECT industry, union_status, 100.0 * COUNT(*) / (SELECT SUM(COUNT(*)) FROM employees GROUP BY industry) as 'Percentage' FROM employees GROUP BY industry, union_status;
Show total number of union members by state
CREATE TABLE union_members (id INT,name VARCHAR(50),state VARCHAR(2),city VARCHAR(20),occupation VARCHAR(20)); INSERT INTO union_members (id,name,state,city,occupation) VALUES (1,'John Doe','NY','New York','Engineer'); INSERT INTO union_members (id,name,state,city,occupation) VALUES (2,'Jane Smith','CA','Los Angeles','Teacher'); INSERT INTO union_members (id,name,state,city,occupation) VALUES (3,'Alice Johnson','NY','Buffalo','Nurse');
SELECT state, COUNT(*) as total_members FROM union_members GROUP BY state;
What is the maximum safety rating for vehicles in the vehiclesafety schema?
CREATE TABLE VehicleSafety (id INT,vehicle_id INT,safetyrating INT,PRIMARY KEY (id)); CREATE TABLE Vehicles (id INT,make VARCHAR(50),model VARCHAR(50),PRIMARY KEY (id)); CREATE TABLE LuxuryVehicles (id INT,vehicle_id INT,PRIMARY KEY (id),FOREIGN KEY (vehicle_id) REFERENCES Vehicles(id));
SELECT MAX(safetyrating) FROM vehicleSafety JOIN Vehicles ON vehicleSafety.vehicle_id = Vehicles.id WHERE EXISTS (SELECT * FROM LuxuryVehicles WHERE Vehicles.id = LuxuryVehicles.vehicle_id);
What is the maximum cargo weight for each vessel in the 'cargo_tracking' table?
CREATE TABLE cargo_tracking (id INT,vessel_name VARCHAR(50),cargo_weight DECIMAL(10,2));
SELECT vessel_name, MAX(cargo_weight) FROM cargo_tracking GROUP BY vessel_name;
What was the average speed of vessels that departed from Port A in Q1 2020?
CREATE TABLE Vessels (id INT,name TEXT,speed FLOAT,depart_port TEXT,depart_date DATE); INSERT INTO Vessels (id,name,speed,depart_port,depart_date) VALUES (1,'Vessel1',20.5,'Port A','2020-01-02'); INSERT INTO Vessels (id,name,speed,depart_port,depart_date) VALUES (2,'Vessel2',25.0,'Port A','2020-01-10');
SELECT AVG(speed) FROM Vessels WHERE depart_port = 'Port A' AND YEAR(depart_date) = 2020 AND QUARTER(depart_date) = 1;
How many total visitors attended the community events?
CREATE TABLE community_events (id INT,event_name VARCHAR(50),location VARCHAR(50),attendance INT); CREATE TABLE events_attended (id INT,event_id INT,attendee_id INT,date DATE); INSERT INTO community_events (id,event_name,location,attendance) VALUES (1,'Art in the Park','City Park',300),(2,'Museum Night','Museum',800),(3,'Kids Workshop','Museum',400); INSERT INTO events_attended (id,event_id,attendee_id,date) VALUES (1,1,1,'2021-06-05'),(2,1,2,'2021-06-05'),(3,2,3,'2021-06-05'),(4,2,4,'2021-06-05'),(5,3,5,'2021-06-06');
SELECT SUM(community_events.attendance) FROM community_events JOIN events_attended ON community_events.id = events_attended.event_id;
What is the maximum number of visitors at a single exhibition in Tokyo?
CREATE TABLE Exhibitions (exhibition_id INT,location VARCHAR(20),date DATE); INSERT INTO Exhibitions (exhibition_id,location,date) VALUES (1,'Tokyo','2022-06-01'),(2,'Tokyo','2022-06-15'),(3,'Tokyo','2022-07-01'); CREATE TABLE Visitors (visitor_id INT,exhibition_id INT,date DATE); INSERT INTO Visitors (visitor_id,exhibition_id,date) VALUES (1,1,'2022-06-01'),(2,1,'2022-06-01'),(3,2,'2022-06-15'),(4,3,'2022-07-01');
SELECT MAX(visitor_count) FROM (SELECT exhibition_id, COUNT(DISTINCT visitor_id) AS visitor_count FROM Visitors v JOIN Exhibitions e ON v.exhibition_id = e.exhibition_id WHERE e.location = 'Tokyo' GROUP BY exhibition_id) t;
What is the total waste generation by material type for each city in the last quarter?
CREATE TABLE waste_generation(city VARCHAR(255),material_type VARCHAR(255),generation_date DATE,quantity INT); INSERT INTO waste_generation VALUES ('CityA','Plastic','2022-01-01',100);
SELECT city, material_type, SUM(quantity) OVER (PARTITION BY city, material_type ORDER BY generation_date RANGE BETWEEN INTERVAL '3 months' PRECEDING AND CURRENT ROW) FROM waste_generation WHERE generation_date > DATEADD(quarter, -1, CURRENT_DATE)
How many drought-impacted regions are in Egypt and their average impact scores?
CREATE TABLE drought_impact_EG (region VARCHAR(50),country VARCHAR(20),impact_score INT); INSERT INTO drought_impact_EG (region,country,impact_score) VALUES ('Region1','Egypt',60),('Region2','Egypt',70);
SELECT COUNT(*), AVG(impact_score) FROM drought_impact_EG WHERE country = 'Egypt';
What is the average water consumption per capita in New York City for the year 2021?
CREATE TABLE new_york_water_use (year INT,population INT,water_consumption INT); INSERT INTO new_york_water_use (year,population,water_consumption) VALUES (2020,8500000,850000000),(2021,8600000,860000000);
SELECT AVG(new_york_water_use.water_consumption / new_york_water_use.population) as avg_water_consumption FROM new_york_water_use WHERE new_york_water_use.year = 2021;
What is the total water consumption in California in 2020?
CREATE TABLE water_usage(state VARCHAR(20),year INT,consumption INT); INSERT INTO water_usage(state,year,consumption) VALUES ('California',2015,30000),('California',2016,32000),('California',2017,34000),('California',2018,36000),('California',2019,38000);
SELECT SUM(consumption) FROM water_usage WHERE state = 'California' AND year = 2020;
List the total number of workout sessions attended by members from the USA and Canada, grouped by the country.
CREATE TABLE Members (MemberID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Country VARCHAR(50)); INSERT INTO Members (MemberID,FirstName,LastName,Country) VALUES (1,'John','Doe','USA'); INSERT INTO Members (MemberID,FirstName,LastName,Country) VALUES (2,'Jane','Doe','Canada'); CREATE TABLE Workouts (WorkoutID INT,MemberID INT,WorkoutDate DATE); INSERT INTO Workouts (WorkoutID,MemberID,WorkoutDate) VALUES (1,1,'2022-01-12'); INSERT INTO Workouts (WorkoutID,MemberID,WorkoutDate) VALUES (2,2,'2022-01-14');
SELECT w.Country, COUNT(*) as TotalWorkouts FROM Workouts w INNER JOIN Members m ON w.MemberID = m.MemberID WHERE m.Country IN ('USA', 'Canada') GROUP BY w.Country;
What is the minimum heart rate for users during evening workouts?
CREATE TABLE workouts (id INT,user_id INT,heart_rate INT,workout_time TIME); INSERT INTO workouts (id,user_id,heart_rate,workout_time) VALUES (1,1,120,'18:00:00');
SELECT MIN(heart_rate) FROM workouts WHERE workout_time BETWEEN '18:00:00' AND '23:59:59';
Count the number of unique users who interacted with the algorithmic fairness system in the last quarter
CREATE TABLE interactions (id INT,user_id INT,interaction_date DATE); INSERT INTO interactions (id,user_id,interaction_date) VALUES (1,1001,'2022-01-01'),(2,1002,'2022-02-15'),(3,1003,'2022-03-03'),(4,1001,'2022-03-25'),(5,1004,'2022-04-01'),(6,1003,'2022-03-17');
SELECT COUNT(DISTINCT user_id) FROM interactions WHERE interaction_date >= DATE_SUB(NOW(), INTERVAL 3 MONTH);
List all agricultural innovation metrics related to wheat in Egypt.
CREATE TABLE AgriInnov (id INT,metric VARCHAR(255),crop VARCHAR(255),country VARCHAR(255)); INSERT INTO AgriInnov (id,metric,crop,country) VALUES (1,'Yield','Wheat','Egypt'),(2,'Harvest Time','Wheat','Egypt');
SELECT * FROM AgriInnov WHERE crop = 'Wheat' AND country = 'Egypt';
List all agricultural innovation projects and their respective coordinators in the 'rural_development' database, sorted by project type in ascending order.
CREATE TABLE agri_innovation_project (project_id INT,project_name VARCHAR(50),project_type VARCHAR(50),coordinator_id INT); INSERT INTO agri_innovation_project (project_id,project_name,project_type,coordinator_id) VALUES (1,'Precision Agriculture','Technology',1001); CREATE TABLE coordinator (coordinator_id INT,coordinator_name VARCHAR(50),age INT,location VARCHAR(50)); INSERT INTO coordinator (coordinator_id,coordinator_name,age,location) VALUES (1001,'Anna Kim',45,'Seoul');
SELECT agri_innovation_project.project_name, agri_innovation_project.project_type, coordinator.coordinator_name FROM agri_innovation_project INNER JOIN coordinator ON agri_innovation_project.coordinator_id = coordinator.coordinator_id ORDER BY agri_innovation_project.project_type ASC;
What is the distribution of rural infrastructure projects in India, Pakistan, and Bangladesh, partitioned by type and ordered by the number of projects?
CREATE TABLE Infrastructure_Projects (ProjectID INT,Country VARCHAR(10),Type VARCHAR(20)); INSERT INTO Infrastructure_Projects (ProjectID,Country,Type) VALUES (1,'India','Irrigation'),(2,'Pakistan','Transportation'),(3,'Bangladesh','Energy'),(4,'India','Transportation'),(5,'Pakistan','Irrigation'),(6,'Bangladesh','Transportation');
SELECT Country, Type, COUNT(*) as Num_Projects FROM Infrastructure_Projects WHERE Country IN ('India', 'Pakistan', 'Bangladesh') GROUP BY Country, Type ORDER BY Num_Projects DESC;
What is the maximum duration of a space mission per astronaut?
CREATE TABLE Space_Missions (ID INT,Astronaut VARCHAR(50),Mission VARCHAR(50),Duration INT); INSERT INTO Space_Missions (ID,Astronaut,Mission,Duration) VALUES (1,'Neil Armstrong','Apollo 11',196),(2,'Buzz Aldrin','Apollo 11',195),(3,'Peggy Whitson','Expedition 50/51',288),(4,'Peter Douzinas','ISS',168),(5,'Sergei Krikalev','Mir',803);
SELECT Astronaut, MAX(Duration) FROM Space_Missions GROUP BY Astronaut;
What is the total amount of seafood (in tonnes) exported from Canada to the USA in 2021?
CREATE TABLE seafood_exports (id INT,exporter_country TEXT,importer_country TEXT,year INT,quantity INT,unit TEXT); INSERT INTO seafood_exports (id,exporter_country,importer_country,year,quantity,unit) VALUES (1,'Canada','USA',2021,500,'tonnes'),(2,'Canada','USA',2022,600,'tonnes');
SELECT SUM(quantity) FROM seafood_exports WHERE exporter_country = 'Canada' AND importer_country = 'USA' AND year = 2021 AND unit = 'tonnes';
How many visitors who identify as 'Male' have spent more than $100 on events in the 'Art' category?
CREATE TABLE Visitors (VisitorID INT,Age INT,Gender VARCHAR(10));CREATE TABLE Events (EventID INT,EventName VARCHAR(20),EventCategory VARCHAR(20));CREATE TABLE VisitorSpending (VisitorID INT,EventID INT,Spending INT);
SELECT COUNT(*) AS Num_Visitors FROM Visitors V INNER JOIN VisitorSpending VS ON V.VisitorID = VS.VisitorID INNER JOIN Events E ON VS.EventID = E.EventID WHERE V.Gender = 'Male' AND VS.Spending > 100 AND E.EventCategory = 'Art';
get viewers who liked 'Encanto' and 'Ray' in the viewership table
CREATE TABLE viewership(id INT PRIMARY KEY,movie VARCHAR(255),viewer VARCHAR(255)); CREATE TABLE likes(id INT PRIMARY KEY,movie VARCHAR(255),viewer VARCHAR(255));
SELECT viewership.viewer FROM viewership INNER JOIN likes ON viewership.movie = likes.movie WHERE viewership.movie IN ('Encanto', 'Ray') AND likes.movie IN ('Encanto', 'Ray') GROUP BY viewership.viewer HAVING COUNT(DISTINCT viewership.movie) = 2;
What is the average price of cannabis edibles per unit in Michigan in Q1 2023?
CREATE TABLE edibles_prices (price DECIMAL(5,2),unit INT,state VARCHAR(20),quarter VARCHAR(10)); INSERT INTO edibles_prices (price,unit,state,quarter) VALUES (20,5,'Michigan','Q1'),(22,5,'Michigan','Q1'),(18,5,'Michigan','Q1');
SELECT AVG(price / unit) as avg_price_per_unit FROM edibles_prices WHERE state = 'Michigan' AND quarter = 'Q1';
How many climate adaptation projects were completed in North America between 2015 and 2017?
CREATE TABLE climate_adaptation_projects (id INT,project_name VARCHAR(100),region VARCHAR(100),budget FLOAT,completion_year INT); INSERT INTO climate_adaptation_projects (id,project_name,region,budget,completion_year) VALUES (1,'Water Management System','North America',12000000,2016),(2,'Green Spaces Expansion','Europe',8000000,2015);
SELECT COUNT(*) FROM climate_adaptation_projects WHERE region = 'North America' AND completion_year BETWEEN 2015 AND 2017;
Identify the drug with the lowest sales amount in Europe in 2022.
CREATE TABLE sales (drug_name TEXT,continent TEXT,sales_amount INT,sale_date DATE); INSERT INTO sales (drug_name,continent,sales_amount,sale_date) VALUES ('Aspirin','Europe',1000,'2022-01-01');
SELECT drug_name, MIN(sales_amount) FROM sales WHERE continent = 'Europe' AND sale_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY drug_name;
What is the infection rate of Malaria in rural areas of Ghana, by district?
CREATE TABLE malaria_infections (id INT,patient_id INT,infection_date DATE,is_rural BOOLEAN,district VARCHAR(255));
SELECT district, COUNT(patient_id) / (SELECT COUNT(*) FROM malaria_infections WHERE is_rural = FALSE) AS infection_rate FROM malaria_infections WHERE is_rural = TRUE GROUP BY district;
Add diversity metrics for company OPQ with gender Male and gender Non-binary in the 'diversity_metrics' table
CREATE TABLE diversity_metrics (company_name VARCHAR(50),gender VARCHAR(10),representation_percentage DECIMAL(5,2));
INSERT INTO diversity_metrics (company_name, gender, representation_percentage) VALUES ('OPQ', 'Male', 50.00), ('OPQ', 'Non-binary', 5.00);
What is the maximum amount of funding raised by a company founded by a person of color in the sustainability industry?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founding_year INT,founder_race TEXT); INSERT INTO companies (id,name,industry,founding_year,founder_race) VALUES (1,'EcoInnovations','Sustainability',2012,'Person of Color'); INSERT INTO companies (id,name,industry,founding_year,founder_race) VALUES (2,'SmartGrid','Energy',2018,'White');
SELECT MAX(funding_amount) FROM funding_records INNER JOIN companies ON funding_records.company_id = companies.id WHERE companies.founder_race = 'Person of Color' AND companies.industry = 'Sustainability';
What is the total funding received by startups in the technology sector that were founded by women?
CREATE TABLE startups(id INT,name TEXT,sector TEXT,founder_gender TEXT,funding FLOAT); INSERT INTO startups VALUES (1,'Acme Inc','Technology','Female',2000000); INSERT INTO startups VALUES (2,'Beta Corp','Retail','Male',3000000); INSERT INTO startups VALUES (3,'Gamma Start','Technology','Female',5000000);
SELECT SUM(funding) FROM startups WHERE sector = 'Technology' AND founder_gender = 'Female';
Which industries have the most companies founded in a given year?
CREATE TABLE Company (id INT,name VARCHAR(50),industry VARCHAR(50),founding_year INT); INSERT INTO Company (id,name,industry,founding_year) VALUES (1,'Acme Inc','Tech',2010); INSERT INTO Company (id,name,industry,founding_year) VALUES (2,'Bravo Corp','Finance',2005); INSERT INTO Company (id,name,industry,founding_year) VALUES (3,'Charlie LLC','Retail',2010); INSERT INTO Company (id,name,industry,founding_year) VALUES (4,'Delta Inc','Healthcare',2008);
SELECT industry, founding_year, COUNT(*) as company_count FROM Company GROUP BY industry, founding_year ORDER BY company_count DESC;
Find the average age of farmers who cultivate maize in the 'crop_distribution' view.
CREATE VIEW crop_distribution AS SELECT f.name AS farmer_name,f.age AS farmer_age,c.crop_name FROM farmers f JOIN crops c ON f.id = c.farmer_id WHERE c.crop_name = 'maize'; INSERT INTO crops (id,farmer_id,crop_name,acres) VALUES (1,1,'maize',50),(2,2,'maize',75),(3,3,'soybean',100);
SELECT AVG(farmer_age) FROM crop_distribution WHERE crop_name = 'maize';
Add a new marine protected area 'Cabo Pulmo National Park' to Mexico with a size of 62.26 square miles.
CREATE TABLE marine_protected_areas (country VARCHAR(255),name VARCHAR(255),size FLOAT); INSERT INTO marine_protected_areas (country,name,size) VALUES ('Mexico','Cabo Pulmo National Park',62.26);
INSERT INTO marine_protected_areas (country, name, size) VALUES ('Mexico', 'Cabo Pulmo National Park', 62.26);
What is the name of the smart contract associated with the ID 5?
CREATE TABLE smart_contracts (id INT,name VARCHAR(255)); INSERT INTO smart_contracts (id,name) VALUES (5,'Compound');
SELECT name FROM smart_contracts WHERE id = 5;
What is the total supply of Bitcoin and Ethereum?
CREATE TABLE crypto_supply (coin VARCHAR(10),total_supply DECIMAL(20,2)); INSERT INTO crypto_supply (coin,total_supply) VALUES ('Bitcoin',18763463.12),('Ethereum',113453453.23);
SELECT coin, total_supply FROM crypto_supply WHERE coin IN ('Bitcoin', 'Ethereum');
Who is the creator of the 'Uniswap V3' smart contract?
CREATE TABLE smart_contracts (id INT,name VARCHAR(255),creator VARCHAR(255)); INSERT INTO smart_contracts (id,name,creator) VALUES (11,'Uniswap V3','Hayden Adams');
SELECT creator FROM smart_contracts WHERE name = 'Uniswap V3';
What is the average carbon sequestration in '2019' for 'African' forests?
CREATE TABLE forests (id INT,region VARCHAR(50)); INSERT INTO forests (id,region) VALUES (1,'African'); CREATE TABLE species (id INT,name VARCHAR(50)); CREATE TABLE carbon_sequestration (id INT,species_id INT,forest_id INT,year INT,sequestration FLOAT); INSERT INTO carbon_sequestration (id,species_id,forest_id,year,sequestration) VALUES (1,1,1,2019,2.8);
SELECT AVG(sequestration) FROM carbon_sequestration JOIN forests ON carbon_sequestration.forest_id = forests.id WHERE forests.region = 'African' AND carbon_sequestration.year = 2019;
What is the total carbon sequestration for each forest in the 'carbon' table?
CREATE TABLE carbon (forest_id INT,year INT,sequestration FLOAT);
SELECT forest_id, SUM(sequestration) FROM carbon GROUP BY forest_id;
Show the percentage of natural ingredients in each beauty product
CREATE TABLE product_ingredients (product VARCHAR(255),ingredient VARCHAR(255),is_natural BOOLEAN); INSERT INTO product_ingredients (product,ingredient,is_natural) VALUES ('Shampoo','Water',TRUE),('Conditioner','Silicones',FALSE);
SELECT product, (SUM(CASE WHEN is_natural THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) AS natural_ingredient_percentage FROM product_ingredients GROUP BY product;
Show the top 5 countries contributing to sales of organic skincare products.
CREATE TABLE cosmetics_sales(sales_date DATE,country VARCHAR(255),product_type VARCHAR(255),sales_quantity INT,sales_revenue DECIMAL(10,2)); CREATE TABLE product_ingredients(product_id INT,product_type VARCHAR(255),contains_natural_ingredients BOOLEAN,contains_organic_ingredients BOOLEAN);
SELECT cs.country, SUM(cs.sales_revenue) AS total_revenue FROM cosmetics_sales cs JOIN product_ingredients pi ON cs.product_type = pi.product_type WHERE pi.contains_natural_ingredients = TRUE AND pi.contains_organic_ingredients = TRUE GROUP BY cs.country ORDER BY total_revenue DESC LIMIT 5;
List all museums that have had an increase in attendance in the last two years compared to the previous two years.
CREATE TABLE Museums (museum_id INT,museum_name VARCHAR(50),year INT,attendance INT); INSERT INTO Museums (museum_id,museum_name,year,attendance) VALUES (1,'Metropolitan Museum',2017,10000),(2,'British Museum',2018,12000),(3,'Louvre Museum',2019,15000),(4,'State Hermitage',2020,18000);
SELECT museum_name FROM Museums WHERE year BETWEEN 2018 AND 2020 GROUP BY museum_name HAVING AVG(attendance) > (SELECT AVG(attendance) FROM Museums WHERE year BETWEEN 2016 AND 2017 GROUP BY museum_name);
What is the total assets of customers who have accounts in both New York and California branches?
CREATE TABLE branches (id INT,name VARCHAR(255)); INSERT INTO branches (id,name) VALUES (1,'New York'),(2,'California'); CREATE TABLE customers (id INT,name VARCHAR(255),total_assets DECIMAL(10,2),branch_id INT); INSERT INTO customers (id,name,total_assets,branch_id) VALUES (1,'Alice',50000,1),(2,'Bob',75000,1),(3,'Charlie',30000,2),(4,'Diana',60000,2);
SELECT SUM(c.total_assets) FROM customers c INNER JOIN branches b ON c.branch_id = b.id WHERE b.name IN ('New York', 'California') GROUP BY b.name;
What is the total transaction amount for customers in the Northeast region in January 2022?
CREATE TABLE transactions (transaction_id INT,customer_id INT,transaction_date DATE,transaction_amount DECIMAL(10,2)); INSERT INTO transactions (transaction_id,customer_id,transaction_date,transaction_amount) VALUES (1,2,'2022-01-05',350.00),(2,1,'2022-01-10',500.00),(3,3,'2022-02-15',700.00);
SELECT SUM(transaction_amount) FROM transactions WHERE customer_id IN (SELECT customer_id FROM customers WHERE region = 'Northeast') AND transaction_date BETWEEN '2022-01-01' AND '2022-01-31';
How many excavation sites are located in 'Italy' or 'Greece'?
CREATE TABLE ExcavationSites (id INT,site VARCHAR(20),location VARCHAR(30),start_date DATE,end_date DATE); INSERT INTO ExcavationSites (id,site,location,start_date,end_date) VALUES (1,'BronzeAge','UK','2000-01-01','2005-12-31'),(2,'AncientRome','Italy','1999-01-01','2002-12-31'),(3,'Mycenae','Greece','2003-01-01','2006-12-31');
SELECT COUNT(DISTINCT site) FROM ExcavationSites WHERE location IN ('Italy', 'Greece');
Calculate the average number of doctor visits per rural patient with heart disease
CREATE TABLE doctors (doctor_id INTEGER,hospital TEXT); INSERT INTO doctors (doctor_id,hospital) VALUES (1,'Pocahontas Memorial Hospital'),(2,'Pocahontas Memorial Hospital'),(3,'Memorial Hospital of Converse County'); CREATE TABLE visits (patient_id INTEGER,hospital TEXT,visit_date DATE,visit_type TEXT); INSERT INTO visits (patient_id,hospital,visit_date,visit_type) VALUES (1,'Pocahontas Memorial Hospital','2019-05-14','doctor'),(2,'Pocahontas Memorial Hospital','2020-03-12','doctor'),(3,'Memorial Hospital of Converse County','2020-07-20','doctor'); CREATE TABLE patients (patient_id INTEGER,diagnosis TEXT); INSERT INTO patients (patient_id,diagnosis) VALUES (1,'heart disease'),(2,'heart disease'),(3,'diabetes');
SELECT AVG(visits_per_patient) FROM (SELECT patient_id, COUNT(*) as visits_per_patient FROM visits JOIN patients ON visits.patient_id = patients.patient_id WHERE diagnosis = 'heart disease' GROUP BY patient_id) as heart_disease_patients;
How many doctors work in Indigenous rural areas, and what is their average salary?
CREATE TABLE doctors (id INT,age INT,salary INT,is_indigenous BOOLEAN); INSERT INTO doctors (id,age,salary,is_indigenous) VALUES (1,55,120000,true),(2,45,150000,false); CREATE TABLE locations (id INT,is_rural BOOLEAN); INSERT INTO locations (id,is_rural) VALUES (1,true),(2,false);
SELECT COUNT(doctors.id), AVG(doctors.salary) FROM doctors INNER JOIN locations ON doctors.id = locations.id WHERE locations.is_rural = true AND doctors.is_indigenous = true;
What is the percentage of the population that is vaccinated by age group in rural areas?
CREATE TABLE population (id INT,age INT,location VARCHAR(50),vaccinated BOOLEAN); INSERT INTO population (id,age,location,vaccinated) VALUES (1,20,'Rural',true);
SELECT age_group, (SUM(vaccinated_count) * 100.0 / SUM(total_count)) as vaccination_percentage FROM (SELECT age/10 as age_group, SUM(vaccinated) as vaccinated_count, COUNT(*) as total_count FROM population WHERE location = 'Rural' GROUP BY age/10) as subquery GROUP BY age_group;
What was the total amount of ESG investments made by Green Ventures in Q1 2021?
CREATE TABLE Green_Ventures (id INT,quarter VARCHAR(10),amount FLOAT); INSERT INTO Green_Ventures (id,quarter,amount) VALUES (1,'Q1 2021',500000),(2,'Q2 2021',700000);
SELECT SUM(amount) FROM Green_Ventures WHERE quarter = 'Q1 2021' AND context ILIKE '%ESG%';
What is the average number of streams per day for each song by artists from the United States on Apple Music?
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(100),Country VARCHAR(50)); INSERT INTO Artists (ArtistID,ArtistName,Country) VALUES (4,'Billie Eilish','United States'); CREATE TABLE StreamingPlatforms (PlatformID INT,PlatformName VARCHAR(50)); INSERT INTO StreamingPlatforms (PlatformID,PlatformName) VALUES (1,'Spotify'),(2,'Apple Music'); CREATE TABLE SongsStreams (SongID INT,ArtistID INT,PlatformID INT,StreamCount INT,ReleaseDate DATE); INSERT INTO SongsStreams (SongID,ArtistID,PlatformID,StreamCount,ReleaseDate) VALUES (5,4,2,1000000,'2019-03-29');
SELECT ss.SongID, AVG(ss.StreamCount / DATEDIFF('2022-12-31', ss.ReleaseDate)) AS AvgStreamsPerDay FROM SongsStreams ss JOIN Artists a ON ss.ArtistID = a.ArtistID JOIN StreamingPlatforms sp ON ss.PlatformID = sp.PlatformID WHERE a.Country = 'United States' AND sp.PlatformName = 'Apple Music' GROUP BY ss.SongID;
What was the total budget for the Operations department in each quarter of 2019?
CREATE TABLE Operations_Budget (id INT,department VARCHAR(50),category VARCHAR(50),amount FLOAT,budget_date DATE); INSERT INTO Operations_Budget (id,department,category,amount,budget_date) VALUES (1,'Operations','Salaries',50000,'2019-01-01'); INSERT INTO Operations_Budget (id,department,category,amount,budget_date) VALUES (2,'Operations','Office Supplies',10000,'2019-02-01');
SELECT department, QUARTER(budget_date) as quarter, SUM(amount) as total_budget FROM Operations_Budget WHERE YEAR(budget_date) = 2019 AND department = 'Operations' GROUP BY department, quarter;
What is the distribution of employees by education level?
CREATE TABLE Employees (id INT,name VARCHAR(50),education_level VARCHAR(50)); INSERT INTO Employees (id,name,education_level) VALUES (1,'Jamal Thompson','Master''s'); INSERT INTO Employees (id,name,education_level) VALUES (2,'Sophia Garcia','Bachelor''s'); INSERT INTO Employees (id,name,education_level) VALUES (3,'Hassan Patel','PhD');
SELECT education_level, COUNT(*) AS total FROM Employees GROUP BY education_level;
What is the maximum installed capacity (MW) of energy storage in 'Australia'?
CREATE TABLE max_energy_storage (storage_id INT,country VARCHAR(50),capacity FLOAT); INSERT INTO max_energy_storage (storage_id,country,capacity) VALUES (1,'Australia',50.1),(2,'Japan',75.2);
SELECT MAX(capacity) FROM max_energy_storage WHERE country = 'Australia';
How many wells were drilled in the Gulf of Mexico each year from 2017 to 2020?
CREATE TABLE drilling (drilling_id INT,well_id INT,drilling_date DATE,location VARCHAR(50)); INSERT INTO drilling (drilling_id,well_id,drilling_date,location) VALUES (1,4,'2017-03-02','Gulf of Mexico'),(2,5,'2018-06-18','Gulf of Mexico'),(3,6,'2019-09-24','Gulf of Mexico'),(4,7,'2020-11-05','Gulf of Mexico');
SELECT EXTRACT(YEAR FROM drilling_date) as year, COUNT(DISTINCT well_id) as num_wells FROM drilling WHERE location = 'Gulf of Mexico' GROUP BY year ORDER BY year;
Insert new records into 'ProductionFigures' table for the following data: (WellID, Year, GasQuantity, OilQuantity) - ('Well01', '2019', 5000, 10000), ('Well02', '2019', 6000, 12000)
CREATE TABLE ProductionFigures (WellID VARCHAR(10),Year INT,GasQuantity INT,OilQuantity INT);
INSERT INTO ProductionFigures (WellID, Year, GasQuantity, OilQuantity) VALUES ('Well01', '2019', '5000', '10000'), ('Well02', '2019', '6000', '12000');
Update the age column for a player in the players table
CREATE TABLE players (id INT PRIMARY KEY,name VARCHAR(50),age INT,sport VARCHAR(50));
UPDATE players SET age = 25 WHERE name = 'John Doe';
What is the most common foul in the 'basketball_fouls' table?
CREATE TABLE basketball_teams (team_id INT,name VARCHAR(50)); CREATE TABLE basketball_players (player_id INT,name VARCHAR(50),team_id INT); CREATE TABLE basketball_fouls (foul_id INT,player_id INT,type VARCHAR(50)); INSERT INTO basketball_teams (team_id,name) VALUES (1,'Chicago Bulls'),(2,'Los Angeles Lakers'); INSERT INTO basketball_players (player_id,name,team_id) VALUES (1,'Michael Jordan',1),(2,'Kobe Bryant',2); INSERT INTO basketball_fouls (foul_id,player_id,type) VALUES (1,1,'Block'),(2,1,'Charge'),(3,2,'Block'),(4,2,'Charge'),(5,2,'Travel');
SELECT type AS most_common_foul FROM basketball_fouls GROUP BY type ORDER BY COUNT(*) DESC LIMIT 1;
How many workers in fair-trade certified factories are based in Latin America?
CREATE TABLE workers (id INT,certification VARCHAR(20),region VARCHAR(20)); INSERT INTO workers (id,certification,region) VALUES (1,'Fair Trade','Brazil'),(2,'GOTS','India'),(3,'Fair Trade','Mexico');
SELECT COUNT(*) FROM workers WHERE certification = 'Fair Trade' AND region = 'Latin America';
What is the total production cost of linen products in the Netherlands?
CREATE TABLE production_cost (country VARCHAR(255),material VARCHAR(255),product VARCHAR(255),cost DECIMAL(10,2)); INSERT INTO production_cost (country,material,product,cost) VALUES ('Netherlands','linen','shirt',25.50); INSERT INTO production_cost (country,material,product,cost) VALUES ('Netherlands','linen','pants',35.75);
SELECT SUM(cost) FROM production_cost WHERE country = 'Netherlands' AND material = 'linen';
What is the total retail price of sustainable fabrics by country of origin?
CREATE TABLE products (product_id INT,product_name TEXT,country_of_origin TEXT,retail_price DECIMAL(5,2)); INSERT INTO products (product_id,product_name,country_of_origin,retail_price) VALUES (1,'Organic Cotton Shirt','India',35.00),(2,'Recycled Polyester Jacket','China',120.00),(3,'Hemp T-Shirt','France',45.00);
SELECT country_of_origin, SUM(retail_price) as total_retail_price FROM products GROUP BY country_of_origin;
Calculate the total value of loans issued to clients in the Asia-Pacific region, grouped by account type.
CREATE TABLE loans (loan_id INT,client_region VARCHAR(20),account_type VARCHAR(20),loan_amount DECIMAL(10,2)); INSERT INTO loans (loan_id,client_region,account_type,loan_amount) VALUES (1,'Asia-Pacific','Shariah Compliant',12000.00),(2,'Europe','Shariah Compliant',9000.00),(3,'Asia-Pacific','Conventional',15000.00),(4,'North America','Conventional',10000.00);
SELECT account_type, SUM(loan_amount) FROM loans WHERE client_region = 'Asia-Pacific' GROUP BY account_type;
How many financial capability training sessions were conducted by EmpowermentCDF in 2018?
CREATE TABLE EmpowermentCDF (id INT,event_type VARCHAR(20),event_date DATE); INSERT INTO EmpowermentCDF (id,event_type,event_date) VALUES (1,'Financial Capability Training','2018-02-14');
SELECT COUNT(*) FROM EmpowermentCDF WHERE event_type = 'Financial Capability Training' AND YEAR(event_date) = 2018;
What is the third highest account balance for Shariah-compliant finance customers?
CREATE TABLE shariah_compliant_finance(customer_id INT,account_balance DECIMAL(10,2)); INSERT INTO shariah_compliant_finance VALUES (1,5000),(2,7000),(3,6000),(4,8000),(5,9000);
SELECT account_balance FROM (SELECT account_balance, RANK() OVER (ORDER BY account_balance DESC) as rn FROM shariah_compliant_finance) t WHERE rn = 3;