instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total CO2 emission of conventional farming in France?
CREATE TABLE emissions (id INT,emission_type VARCHAR(255),quantity INT,unit VARCHAR(255),country VARCHAR(255)); INSERT INTO emissions (id,emission_type,quantity,unit,country) VALUES (1,'CO2',2000,'tonnes','France');
SELECT SUM(quantity) FROM emissions WHERE emission_type = 'CO2' AND country = 'France' AND unit = 'tonnes';
Delete the accommodation record for student 3
CREATE TABLE student_accommodations (student_id INT,accommodation_year INT,accommodation_type VARCHAR(255)); INSERT INTO student_accommodations (student_id,accommodation_year,accommodation_type) VALUES (1,2021,'Hearing'),(2,2021,'Visual'),(3,2020,'Mobility');
DELETE FROM student_accommodations WHERE student_id = 3;
What is the maximum and minimum response time for ambulances in each city in the state of California?
CREATE TABLE ambulance_response (id INT,city VARCHAR(255),response_time INT);
SELECT city, MIN(response_time) as min_response_time, MAX(response_time) as max_response_time FROM ambulance_response GROUP BY city;
Which countries have the highest military expenditure in 2020?
CREATE TABLE MilitaryExpenditure (CountryName TEXT,Expenditure INT,Year INT); INSERT INTO MilitaryExpenditure (CountryName,Expenditure,Year) VALUES ('United States',778000,2020),('China',252000,2020),('India',72930,2020),('Russia',61700,2020);
SELECT CountryName, Expenditure FROM MilitaryExpenditure WHERE Year = 2020 ORDER BY Expenditure DESC;
What is the total number of containers and their total weight transported by each vessel type in the last quarter?
CREATE TABLE vessels (vessel_id INT,vessel_type VARCHAR(50)); CREATE TABLE containers (container_id INT,container_weight INT,vessel_id INT,shipped_date DATE); INSERT INTO vessels VALUES (1,'Container Ship'); INSERT INTO vessels VALUES (2,'Bulk Carrier'); INSERT INTO containers VALUES (1,10,1,'2022-03-01'); INSERT INTO containers VALUES (2,15,2,'2022-02-15'); INSERT INTO containers VALUES (3,20,1,'2022-01-10');
SELECT vessels.vessel_type, COUNT(containers.container_id) as num_containers, SUM(containers.container_weight) as total_weight FROM vessels INNER JOIN containers ON vessels.vessel_id = containers.vessel_id WHERE containers.shipped_date > DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY vessels.vessel_type;
Which vessels were involved in accidents, and what were their average ages and capacities?
CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(100),age INT,capacity INT); CREATE TABLE accidents (accident_id INT,vessel_id INT); INSERT INTO vessels VALUES (1,'MV Ever Given',5); INSERT INTO vessels VALUES (2,'MV Maersk Mc-Kinney Moller',12); INSERT INTO accidents VALUES (1,1); INSERT INTO accidents VALUES (2,2);
SELECT vessels.vessel_name, AVG(vessels.age) as avg_age, AVG(vessels.capacity) as avg_capacity FROM vessels INNER JOIN accidents ON vessels.vessel_id = accidents.vessel_id GROUP BY vessels.vessel_name;
Who are the suppliers for the 'metal' department in factory 2?
CREATE TABLE factories (factory_id INT,department VARCHAR(20)); INSERT INTO factories (factory_id,department) VALUES (1,'textile'),(2,'metal'),(3,'textile'); CREATE TABLE suppliers (supplier_id INT,factory_id INT,supplier_name VARCHAR(30)); INSERT INTO suppliers (supplier_id,factory_id,supplier_name) VALUES (1,1,'Supplier A'),(2,2,'Supplier B'),(3,2,'Supplier C'),(4,3,'Supplier D');
SELECT supplier_name FROM suppliers WHERE factory_id = 2 AND department = 'metal';
List the top 3 streaming songs for the Hip-Hop genre in 2021.
CREATE TABLE songs (id INT PRIMARY KEY,title TEXT,year INT,genre TEXT,artist TEXT,streams INT); INSERT INTO songs (id,title,year,genre,artist,streams) VALUES (1,'Rap God',2013,'Hip-Hop','Eminem',100000000),(2,'Hotline Bling',2015,'Hip-Hop','Drake',200000000),(3,'Sicko Mode',2018,'Hip-Hop','Travis Scott',150000000),(4,'WAP',2021,'Hip-Hop','Cardi B',250000000),(5,'Industry Baby',2021,'Hip-Hop','Lil Nas X',300000000),(6,'Goosebumps',2016,'Hip-Hop','Travis Scott',120000000);
SELECT title, streams FROM songs WHERE genre = 'Hip-Hop' AND year = 2021 ORDER BY streams DESC LIMIT 3;
Insert a new record for a donation of $750 on April 20, 2023, for the Arts program
CREATE TABLE donations (donation_id INT,donation_amount FLOAT,donation_date DATE,program_name VARCHAR(50));
INSERT INTO donations (donation_id, donation_amount, donation_date, program_name) VALUES (4, 750, '2023-04-20', 'Arts');
How many students in each school have a mental health score below the average?
CREATE TABLE schools (id INT PRIMARY KEY,name VARCHAR(255)); CREATE TABLE students (id INT PRIMARY KEY,school_id INT,mental_health_score INT);
SELECT s.name, COUNT(st.id) FROM students st JOIN schools s ON st.school_id = s.id GROUP BY st.school_id HAVING AVG(st.mental_health_score) > st.mental_health_score;
What is the maximum number of open pedagogy projects per student?
CREATE TABLE student_open_pedagogy (student_id INT,project_count INT);
SELECT student_id, MAX(project_count) as max_projects FROM student_open_pedagogy;
What is the total energy consumption (in MWh) for each country in the year 2020?
CREATE TABLE energy_consumption (country VARCHAR(50),year INT,energy_consumption FLOAT); INSERT INTO energy_consumption (country,year,energy_consumption) VALUES ('USA',2020,3500.5),('Canada',2020,1200.3),('Mexico',2020,1800.2);
SELECT e.country, SUM(e.energy_consumption) FROM energy_consumption e WHERE e.year = 2020 GROUP BY e.country;
Delete the record for well 'K11' in 'Indian Ocean'.
CREATE TABLE wells (well_id VARCHAR(10),well_location VARCHAR(20)); INSERT INTO wells (well_id,well_location) VALUES ('K11','Indian Ocean'); CREATE TABLE production (well_id VARCHAR(10),production_count INT); INSERT INTO production (well_id,production_count) VALUES ('K11',15000);
DELETE FROM production WHERE well_id = 'K11';
Show the number of victories for each team in the UEFA Champions League
CREATE TABLE teams (id INT PRIMARY KEY,name TEXT,league TEXT,wins INT,losses INT,draws INT); INSERT INTO teams (id,name,league,wins,losses,draws) VALUES (1,'Real Madrid','La Liga',5,1,1),(2,'Bayern Munich','Bundesliga',5,1,1),(3,'Manchester City','English Premier League',5,1,0),(4,'Liverpool','English Premier League',4,2,0),(5,'Ajax','Eredivisie',4,1,0),(6,'Juventus','Serie A',4,1,0);
SELECT name, wins FROM teams;
What is the highest number of home runs hit by a player in a single MLB game?
CREATE TABLE single_game_homeruns (player VARCHAR(100),team VARCHAR(100),homeruns INT); INSERT INTO single_game_homeruns (player,team,homeruns) VALUES ('Bobby Lowe','Boston Beaneaters',4),('Lou Gehrig','New York Yankees',4);
SELECT MAX(homeruns) FROM single_game_homeruns;
How many buses in Beijing have been serviced in the last 60 days?
CREATE TABLE beijing_bus (bus_id INT,last_service DATE);
SELECT COUNT(*) FROM beijing_bus WHERE last_service >= CURDATE() - INTERVAL 60 DAY;
What is the total quantity of materials used per country?
CREATE TABLE materials (id INT,name VARCHAR(50),quantity INT,country VARCHAR(50)); INSERT INTO materials (id,name,quantity,country) VALUES (1,'organic cotton',1000,'India'),(2,'recycled polyester',1500,'China'),(3,'hemp',500,'Brazil');
SELECT country, SUM(quantity) FROM materials GROUP BY country;
What is the total quantity of recycled polyester used by brands in 2020?
CREATE TABLE recycled_polyester (brand VARCHAR(50),quantity INT,year INT); INSERT INTO recycled_polyester (brand,quantity,year) VALUES ('BrandD',15000,2020),('BrandE',22000,2020),('BrandF',11000,2020);
SELECT SUM(quantity) FROM recycled_polyester WHERE year = 2020;
Who are the top 5 customers in terms of total spending on ethical fashion?
CREATE TABLE Customers (CustomerID INT,Name VARCHAR(50),Spending FLOAT); INSERT INTO Customers (CustomerID,Name,Spending) VALUES (1,'Alice Johnson',1500),(2,'Bob Smith',1200),(3,'Charlie Brown',2000),(4,'David Williams',3000),(5,'Eva Green',1800),(6,'Fiona Lee',2200);
SELECT Name, SUM(Spending) FROM Customers ORDER BY SUM(Spending) DESC FETCH FIRST 5 ROWS ONLY;
What is the maximum loan amount for socially responsible loans in the Asia-Pacific region?
CREATE TABLE socially_responsible_loans (loan_id INT,region VARCHAR(20),loan_amount DECIMAL(10,2)); INSERT INTO socially_responsible_loans (loan_id,region,loan_amount) VALUES (101,'Asia-Pacific',50000),(102,'Europe',30000),(103,'Asia-Pacific',70000);
SELECT MAX(srl.loan_amount) FROM socially_responsible_loans srl WHERE srl.region = 'Asia-Pacific';
Find the top 3 countries with the highest average donation amount in the past 6 months.
CREATE TABLE Donations (DonationID INT,DonorName TEXT,Country TEXT,AmountDonated DECIMAL,DonationDate DATE); INSERT INTO Donations (DonationID,DonorName,Country,AmountDonated,DonationDate) VALUES (1,'Ravi Sharma','India',1000,'2022-01-15'); INSERT INTO Donations (DonationID,DonorName,Country,AmountDonated,DonationDate) VALUES (2,'Marie Jones','Canada',2000,'2022-02-10');
SELECT Country, AVG(AmountDonated) as AvgDonation FROM Donations WHERE DonationDate >= DATEADD(month, -6, GETDATE()) GROUP BY Country ORDER BY AvgDonation DESC LIMIT 3;
Obtain the top 3 countries with the highest number of organic produce suppliers in the organic_produce_suppliers table.
CREATE TABLE organic_produce_suppliers (supplier_id INT,supplier_name VARCHAR(255),country VARCHAR(255));
SELECT supplier_name, country, COUNT(*) as supplier_count FROM organic_produce_suppliers GROUP BY country ORDER BY supplier_count DESC LIMIT 3;
Update the name of supplier with id 1 to 'New Supplier Name'
CREATE TABLE Suppliers (id INT,name TEXT); INSERT INTO Suppliers (id,name) VALUES (1,'Supplier1'),(2,'Supplier2'),(3,'Supplier3');
UPDATE Suppliers SET name = 'New Supplier Name' WHERE id = 1;
What are the names and descriptions of violations for food trucks in Los Angeles that serve vegan food?
CREATE TABLE FoodTruck (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),location VARCHAR(255)); CREATE TABLE Violation (id INT PRIMARY KEY,food_truck_id INT,date DATE,description VARCHAR(255)); CREATE TABLE Menu (id INT PRIMARY KEY,food_truck_id INT,name VARCHAR(255),vegan BOOLEAN);
SELECT f.name, v.description FROM FoodTruck f INNER JOIN Violation v ON f.id = v.food_truck_id INNER JOIN Menu m ON f.id = m.food_truck_id WHERE m.vegan = TRUE AND f.location = 'Los Angeles';
What is the average water usage for crops in Spain?
CREATE TABLE crops (id INT,name VARCHAR(50),country VARCHAR(50),water_usage INT); INSERT INTO crops (id,name,country,water_usage) VALUES (1,'Wheat','Spain',1000),(2,'Barley','Spain',800);
SELECT AVG(water_usage) FROM crops WHERE country = 'Spain';
Which countries have the highest average delivery times for shipments?
CREATE TABLE Shipments (id INT,weight INT,delivery_date DATE,shipped_date DATE,country VARCHAR(50)); INSERT INTO Shipments (id,weight,delivery_date,shipped_date,country) VALUES (1,100,'2022-01-05','2022-01-03','USA'),(2,150,'2022-01-07','2022-01-06','Canada'),(3,200,'2022-02-12','2022-02-10','Mexico');
SELECT country, AVG(DATEDIFF(delivery_date, shipped_date)) AS avg_delivery_time FROM Shipments GROUP BY country ORDER BY avg_delivery_time DESC LIMIT 1;
Largest renewable energy project per location
CREATE TABLE renewable_energy_projects (id INT,name VARCHAR(255),location VARCHAR(255),capacity FLOAT); INSERT INTO renewable_energy_projects (id,name,location,capacity) VALUES (1,'SolarFarm1','CityA',1000),(2,'WindFarm1','CityB',2000),(3,'SolarFarm2','CityA',1500);
SELECT name, location, capacity FROM (SELECT name, location, capacity, ROW_NUMBER() OVER (PARTITION BY location ORDER BY capacity DESC) as rn FROM renewable_energy_projects) AS subquery WHERE rn = 1;
What is the total installed capacity of renewable energy projects in the US?
CREATE TABLE Renewable_Energy_Projects (id INT,country VARCHAR(20),installed_capacity FLOAT); INSERT INTO Renewable_Energy_Projects (id,country,installed_capacity) VALUES (1,'US',1200.5),(2,'Canada',1500.2),(3,'Mexico',900.1);
SELECT SUM(installed_capacity) FROM Renewable_Energy_Projects WHERE country = 'US';
What is the market share of Hotel X in terms of revenue generated by hotels in New York City?
CREATE TABLE hotels (hotel_id INT,hotel_name TEXT,city TEXT,revenue FLOAT); INSERT INTO hotels (hotel_id,hotel_name,city,revenue) VALUES (1,'Hotel X','New York City',1000000),(2,'Hotel Y','New York City',800000),(3,'Hotel Z','New York City',700000);
SELECT (hotels.revenue / (SELECT SUM(revenue) FROM hotels WHERE city = 'New York City') * 100) as market_share FROM hotels WHERE hotel_name = 'Hotel X';
How many artworks were created by artists from France?
CREATE TABLE Artists(id INT,name VARCHAR(255),birthplace VARCHAR(255)); INSERT INTO Artists(id,name,birthplace) VALUES (1,'Claude Monet','Paris,France'); INSERT INTO Artists(id,name,birthplace) VALUES (2,'Henri Matisse','Le Cateau-Cambrésis,France'); INSERT INTO Artists(id,name,birthplace) VALUES (3,'Pablo Picasso','Málaga,Spain');
SELECT COUNT(*) FROM Artists WHERE Artists.birthplace LIKE '%France%';
How many records are in the 'species' table?
CREATE TABLE species (id INT,name VARCHAR(255),population INT); INSERT INTO species (id,name,population) VALUES (1,'polar_bear',25000); INSERT INTO species (id,name,population) VALUES (2,'arctic_fox',30000);
SELECT COUNT(*) FROM species;
Update population of 'Reindeer' in animals table by 30%
CREATE TABLE animals (id INT PRIMARY KEY,species VARCHAR(50),population INT,region VARCHAR(50)); INSERT INTO animals (id,species,population,region) VALUES (1,'Reindeer',5000,'Arctic');
WITH cte AS (UPDATE animals SET population = population * 1.3 WHERE species = 'Reindeer') SELECT * FROM animals;
What is the maximum number of years a traditional art form has been preserved in each country?
CREATE TABLE countries (id INT,name TEXT); INSERT INTO countries (id,name) VALUES (1,'Nigeria'),(2,'Brazil'); CREATE TABLE art_forms (id INT,country_id INT,name TEXT,year_preserved INT); INSERT INTO art_forms (id,country_id,name,year_preserved) VALUES (1,1,'Tie-dye',500),(2,1,'Batik',1000),(3,2,'Capoeira',400);
SELECT c.name, MAX(af.year_preserved) FROM countries c JOIN art_forms af ON c.id = af.country_id GROUP BY c.id;
What was the total construction cost for projects in 'Urban' area?
CREATE TABLE InfrastructureProjects (id INT,name VARCHAR(50),location VARCHAR(50),cost FLOAT); INSERT INTO InfrastructureProjects (id,name,location,cost) VALUES (1,'Dam Reconstruction','Urban',5000000); INSERT INTO InfrastructureProjects (id,name,location,cost) VALUES (2,'Bridge Construction','Rural',3000000);
SELECT SUM(cost) FROM InfrastructureProjects WHERE location = 'Urban';
Calculate the average number of annual visitors to India from 2018 to 2023 who prioritize sustainable tourism.
CREATE TABLE india_tourism (year INT,visitors INT,sustainability_rating INT); INSERT INTO india_tourism (year,visitors,sustainability_rating) VALUES (2018,5000000,3),(2019,5500000,4),(2020,4000000,5),(2021,4500000,5),(2022,6000000,4),(2023,6500000,4);
SELECT AVG(visitors) FROM india_tourism WHERE sustainability_rating >= 4 AND year BETWEEN 2018 AND 2023;
Provide the number of tourists visiting Canada, grouped by continent.
CREATE TABLE tourism_stats (visitor_country VARCHAR(255),continent VARCHAR(255)); INSERT INTO tourism_stats (visitor_country,continent) VALUES ('Canada','North America');
SELECT continent, COUNT(*) FROM tourism_stats GROUP BY continent;
How many TV shows were produced in Japan between 2015 and 2020, grouped by genre, and what is the most popular genre?
CREATE TABLE tv_shows (id INT,title VARCHAR(100),rating FLOAT,production_country VARCHAR(50),release_year INT,genre VARCHAR(50)); INSERT INTO tv_shows (id,title,rating,production_country,release_year,genre) VALUES (1,'TV Show1',7.5,'Japan',2016,'Comedy'),(2,'TV Show2',8.2,'Japan',2018,'Drama'),(3,'TV Show3',6.9,'Japan',2019,'Comedy');
SELECT genre, COUNT(*) as show_count FROM tv_shows WHERE production_country = 'Japan' AND release_year BETWEEN 2015 AND 2020 GROUP BY genre ORDER BY show_count DESC LIMIT 1;
How many journalists were arrested in Middle East in the last 3 months?
CREATE TABLE journalist_arrests (id INT,journalist VARCHAR(255),location VARCHAR(255),date DATE); INSERT INTO journalist_arrests (id,journalist,location,date) VALUES (4,'Journalist 3','Middle East','2023-01-01'),(5,'Journalist 4','Middle East','2023-02-01'),(6,'Journalist 5','Middle East','2023-03-01');
SELECT COUNT(*) FROM journalist_arrests WHERE location = 'Middle East' AND date >= DATEADD(month, -3, GETDATE());
What is the average watch time per user for each content category?
CREATE TABLE user_content_views (view_id INT,user_id INT,content_id INT,view_date DATE,watch_time INT); CREATE TABLE content (content_id INT,content_category VARCHAR(20));
SELECT content.content_category, AVG(user_content_views.watch_time) as avg_watch_time FROM user_content_views JOIN content ON user_content_views.content_id = content.content_id GROUP BY content.content_category;
What is the inventory level for specific ingredients?
CREATE TABLE inventory (ingredient VARCHAR(255),quantity INT); INSERT INTO inventory (ingredient,quantity) VALUES ('Chicken',500),('Beef',300),('Potatoes',800),('Salt',100),('Pepper',50);
SELECT ingredient, quantity FROM inventory WHERE ingredient IN ('Chicken', 'Beef', 'Potatoes');
What is the total sales for each dish category by month?
CREATE TABLE Orders (OrderID INT,DishID INT,Quantity INT,OrderDate DATE); CREATE TABLE Dishes (DishID INT,DishName VARCHAR(50),Category VARCHAR(50),Price DECIMAL(5,2)); INSERT INTO Dishes (DishID,DishName,Category,Price) VALUES (1,'Veggie Pizza','Pizza',12.99),(2,'Margherita Pizza','Pizza',10.99),(3,'Chicken Caesar Salad','Salad',15.49),(4,'Garden Salad','Salad',11.99); INSERT INTO Orders (OrderID,DishID,Quantity,OrderDate) VALUES (1,1,2,'2022-01-01'),(2,2,1,'2022-01-02'),(3,3,3,'2022-01-03'),(4,1,1,'2022-01-04'),(5,4,2,'2022-02-05');
SELECT EXTRACT(MONTH FROM OrderDate) as Month, Category, SUM(Quantity * Price) as TotalSales FROM Orders JOIN Dishes ON Orders.DishID = Dishes.DishID GROUP BY Month, Category;
Calculate the total CO2 emissions for each country.
CREATE TABLE EnvironmentalImpact (SiteID INT,Country VARCHAR(50),Pollutant VARCHAR(50),AmountDecimal FLOAT,Measurement VARCHAR(50),Date DATE); ALTER TABLE MineSites ADD CONSTRAINT FK_SiteID FOREIGN KEY (SiteID) REFERENCES EnvironmentalImpact(SiteID); CREATE VIEW CO2View AS SELECT Country,SUM(AmountDecimal) AS TotalCO2Emissions FROM EnvironmentalImpact WHERE Pollutant = 'CO2' GROUP BY Country;
SELECT CO2View.Country, CO2View.TotalCO2Emissions FROM CO2View ORDER BY TotalCO2Emissions DESC;
Show the number of mining equipment units, by type, that were added to the 'equipment_inventory' table in 2022.
CREATE TABLE equipment_inventory_history (id INT,equipment_type VARCHAR(50),quantity INT,transaction_date DATE); INSERT INTO equipment_inventory_history (id,equipment_type,quantity,transaction_date) VALUES (1,'Excavator',5,'2022-01-01'),(2,'Drill',3,'2022-02-01'),(3,'Haul Truck',2,'2022-03-01');
SELECT equipment_type, SUM(quantity) as total_added FROM equipment_inventory_history WHERE transaction_date >= '2022-01-01' AND transaction_date < '2023-01-01' GROUP BY equipment_type;
Insert new records of network infrastructure investments in the 'Africa' region.
CREATE TABLE investments(id INT,investment VARCHAR(25),date DATE,region VARCHAR(20));
INSERT INTO investments(id, investment, date, region) VALUES (4, 'New data center', '2023-01-01', 'Africa'), (5, 'Fiber optic expansion', '2023-02-01', 'Africa');
List all mobile subscribers who have experienced a network outage in the past 7 days, along with the number and duration of each outage.
CREATE TABLE mobile_subscribers (id INT,latitude DECIMAL(9,6),longitude DECIMAL(9,6),monthly_data_usage DECIMAL(10,2));CREATE VIEW network_issues AS SELECT subscriber_id,date,issue_type,duration FROM network_outages;
SELECT ms.id, ms.latitude, ms.longitude, ms.monthly_data_usage, COUNT(ni.subscriber_id) as num_outages, SUM(ni.duration) as total_outage_duration FROM mobile_subscribers ms INNER JOIN network_issues ni ON ms.id = ni.subscriber_id WHERE ni.date >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) GROUP BY ms.id;
Update conservation status of 'Blue Whale'
CREATE TABLE species (id INT PRIMARY KEY,name VARCHAR(255),population INT,conservation_status VARCHAR(255),last_sighting DATE); INSERT INTO species (id,name,population,conservation_status,last_sighting) VALUES (1,'Blue Whale',10000,'Endangered','2020-01-01');
UPDATE species SET conservation_status = 'Critically Endangered' WHERE name = 'Blue Whale';
Create a new table named 'game_stats' with columns 'session_id', 'game_mode', 'kills', 'deaths', 'assists', 'score'
CREATE SCHEMA if not exists gaming; CREATE TABLE gaming.game_sessions (id INT,player_id INT,start_time TIMESTAMP,end_time TIMESTAMP,duration INT);
CREATE TABLE gaming.game_stats (session_id INT, game_mode VARCHAR(50), kills INT, deaths INT, assists INT, score INT);
What is the average session length for each game genre in the last month, sorted by average session length.
CREATE TABLE game_sessions(id INT,user_id INT,game_name VARCHAR(50),start_time DATETIME,end_time DATETIME); CREATE TABLE games(id INT,name VARCHAR(50),genre VARCHAR(50));
SELECT genres.genre, AVG(TIMESTAMPDIFF(SECOND, start_time, end_time)) as avg_session_length FROM game_sessions JOIN games ON game_sessions.game_name = games.name JOIN (SELECT DISTINCT game_name, genre FROM game_sessions JOIN games ON game_sessions.game_name = games.name) genres ON games.name = genres.game_name WHERE start_time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY genres.genre ORDER BY avg_session_length DESC;
What is the most popular genre of virtual reality games in Europe?
CREATE TABLE VRGames (GameID INT,GameName VARCHAR(100),Genre VARCHAR(50),Popularity INT,PlayerCountry VARCHAR(50)); INSERT INTO VRGames (GameID,GameName,Genre,Popularity,PlayerCountry) VALUES (1,'VRGameA','Action',10000,'Germany'),(2,'VRGameB','Simulation',12000,'France'),(3,'VRGameC','Action',15000,'Germany');
SELECT Genre, SUM(Popularity) as TotalPopularity FROM VRGames WHERE PlayerCountry LIKE 'Europe%' GROUP BY Genre ORDER BY TotalPopularity DESC;
Which esports event has the most participants?
CREATE TABLE EventParticipants (ParticipantID INT,EventID INT,ParticipantName VARCHAR(50)); INSERT INTO EventParticipants (ParticipantID,EventID) VALUES (1,1),(2,1),(3,2),(4,3),(5,3);
SELECT EventID, COUNT(*) as ParticipantCount FROM EventParticipants GROUP BY EventID ORDER BY ParticipantCount DESC LIMIT 1;
What is the total budget allocated for all departments in 'CityC'?
CREATE TABLE Budget (City VARCHAR(10),Department VARCHAR(20),Amount INT); INSERT INTO Budget (City,Department,Amount) VALUES ('CityC','Healthcare',15000000),('CityC','Education',20000000),('CityC','Transportation',10000000);
SELECT SUM(Amount) FROM Budget WHERE City = 'CityC';
What is the total healthcare budget for coastal districts?
CREATE TABLE districts (district_id INT,district_name VARCHAR(20),coast VARCHAR(10)); INSERT INTO districts (district_id,district_name,coast) VALUES (1,'Seaside','Coast'),(2,'Greenfield','Inland'),(3,'Harborside','Coast'); CREATE TABLE budget_allocation (budget_id INT,district_id INT,sector VARCHAR(20),budget_amount INT); INSERT INTO budget_allocation (budget_id,district_id,sector,budget_amount) VALUES (1,1,'Education',50000),(2,1,'Healthcare',80000),(3,2,'Education',60000),(4,2,'Healthcare',70000),(5,3,'Education',40000),(6,3,'Healthcare',85000);
SELECT SUM(budget_amount) FROM budget_allocation WHERE sector = 'Healthcare' AND districts.coast = 'Coast';
Delete the record of Erbium production in Q2 2020 from the Japanese mine.
CREATE TABLE production (id INT,mine_id INT,element TEXT,production FLOAT,datetime DATE); INSERT INTO production (id,mine_id,element,production,datetime) VALUES (1,1,'Erbium',130.5,'2020-04-01'),(2,2,'Holmium',170.2,'2020-04-15');
DELETE FROM production WHERE mine_id = 1 AND element = 'Erbium' AND QUARTER(datetime) = 2 AND YEAR(datetime) = 2020;
What is the total production of Neodymium for each country in 2020?
CREATE TABLE production (country VARCHAR(20),element VARCHAR(10),year INT,quantity INT); INSERT INTO production (country,element,year,quantity) VALUES ('China','Neodymium',2020,120000),('Australia','Neodymium',2020,8000);
SELECT country, SUM(quantity) as total_production FROM production WHERE element = 'Neodymium' AND year = 2020 GROUP BY country;
Update the revenue of 'Chicken Shawarma' dish in the restaurant_menu table.
CREATE TABLE restaurant_menu (dish VARCHAR(255),category VARCHAR(255),price DECIMAL(10,2)); INSERT INTO restaurant_menu (dish,category,price) VALUES ('Chicken Shawarma','Middle Eastern',8.99);
UPDATE restaurant_menu SET price = 9.99 WHERE dish = 'Chicken Shawarma';
What are the total sales for all restaurants located in 'Downtown'?
CREATE TABLE restaurants (id INT,name TEXT,location TEXT); INSERT INTO restaurants (id,name,location) VALUES (1,'Restaurant A','Downtown'),(2,'Restaurant B','Uptown');
SELECT SUM(sales) FROM sales JOIN restaurants ON sales.restaurant_id = restaurants.id WHERE restaurants.location = 'Downtown';
Which stores in Tokyo have sold more than 30 units of eco-friendly cleaning products since their launch?
CREATE TABLE products(product_id VARCHAR(20),product_name VARCHAR(20),launched_date DATE); INSERT INTO products (product_id,product_name,launched_date) VALUES ('Eco-friendly Cleaner','2022-01-01'); CREATE TABLE stores(store_id VARCHAR(20),store_location VARCHAR(20)); INSERT INTO stores (store_id,store_location) VALUES ('Tokyo Store 1','Tokyo'),('Tokyo Store 2','Tokyo'); CREATE TABLE sales(store_id VARCHAR(20),product_id VARCHAR(20),sale_date DATE,quantity INTEGER); INSERT INTO sales (store_id,product_id,sale_date,quantity) VALUES ('Tokyo Store 1','Eco-friendly Cleaner','2022-01-05',20),('Tokyo Store 2','Eco-friendly Cleaner','2022-01-07',40);
SELECT store_location, SUM(quantity) FROM sales JOIN stores ON sales.store_id = stores.store_id JOIN products ON sales.product_id = products.product_id WHERE products.product_name = 'Eco-friendly Cleaner' AND sale_date >= products.launched_date AND store_location = 'Tokyo' GROUP BY store_location HAVING SUM(quantity) > 30;
What is the name of the spacecraft with the highest mass?
CREATE TABLE Spacecraft (id INT,name VARCHAR(30),mass FLOAT); INSERT INTO Spacecraft (id,name,mass) VALUES (1,'Nebula',20000.0); INSERT INTO Spacecraft (id,name,mass) VALUES (2,'Pulsar',18000.0);
SELECT name FROM Spacecraft WHERE mass = (SELECT MAX(mass) FROM Spacecraft);
List all ticket sales records for the western_conference in the ticket_sales table.
CREATE TABLE ticket_sales (id INT,team VARCHAR(50),conference VARCHAR(50),tickets_sold INT,revenue FLOAT);
SELECT * FROM ticket_sales WHERE conference = 'western_conference';
What is the total number of tickets sold in events with 'Basketball' as the sport in the 'events' table?
CREATE TABLE events (event_id INT,sport VARCHAR(10),athlete_count INT,attendees INT,ticket_price DECIMAL(5,2));
SELECT SUM(attendees * ticket_price) FROM events WHERE sport = 'Basketball';
How many vulnerabilities were found in the last quarter for the 'cloud' asset type?
CREATE TABLE vulnerabilities (id INT,vuln_date DATE,asset_type VARCHAR(50)); INSERT INTO vulnerabilities (id,vuln_date,asset_type) VALUES (1,'2022-01-01','cloud'),(2,'2022-02-05','server'),(3,'2022-03-10','workstation');
SELECT COUNT(*) as vulnerability_count FROM vulnerabilities WHERE vuln_date >= DATEADD(quarter, -1, GETDATE()) AND asset_type = 'cloud';
What is the average severity of vulnerabilities detected in the last month for the finance department?
CREATE TABLE vulnerabilities (id INT,department VARCHAR(255),severity INT,detection_date DATE); INSERT INTO vulnerabilities (id,department,severity,detection_date) VALUES (1,'finance',7,'2022-01-05'),(2,'finance',5,'2022-02-10'),(3,'HR',3,'2022-01-02');
SELECT AVG(severity) FROM vulnerabilities WHERE detection_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND department = 'finance';
What were the top 5 malware types by the number of incidents in the North America region in 2021?
CREATE TABLE malware_incidents (id INT,malware_type VARCHAR(255),incident_count INT,region VARCHAR(255),occurrence_date DATE); INSERT INTO malware_incidents (id,malware_type,incident_count,region,occurrence_date) VALUES (1,'Ransomware',150,'North America','2021-01-01');
SELECT malware_type, incident_count FROM malware_incidents WHERE region = 'North America' AND occurrence_date >= '2021-01-01' AND occurrence_date < '2022-01-01' GROUP BY malware_type ORDER BY incident_count DESC LIMIT 5;
What is the total number of autonomous vehicles in Berlin, Germany and Madrid, Spain?
CREATE TABLE autonomous_vehicles (vehicle_id INT,city VARCHAR(20),country VARCHAR(20)); INSERT INTO autonomous_vehicles (vehicle_id,city,country) VALUES (1,'Berlin','Germany'),(2,'Berlin','Germany'),(3,'Madrid','Spain'),(4,'Madrid','Spain');
SELECT COUNT(*) FROM autonomous_vehicles WHERE city IN ('Berlin', 'Madrid') AND country IN ('Germany', 'Spain');
Insert a new record in the claims table with claim_id 3, policy_id 2, claim_amount 2500, and claim_date '2022-02-12'
CREATE TABLE claims (claim_id INT,policy_id INT,claim_amount DECIMAL(10,2),claim_date DATE);
INSERT INTO claims (claim_id, policy_id, claim_amount, claim_date) VALUES (3, 2, 2500, '2022-02-12');
What is the minimum wage for workers in the 'food' sector, and how many workers are paid this amount?
CREATE TABLE if not exists wages (id INT PRIMARY KEY,sector VARCHAR(255),wage DECIMAL(10,2)); INSERT INTO wages (id,sector,wage) VALUES (1,'food',12.00),(2,'food',12.00),(3,'manufacturing',15.00);
SELECT MIN(wage), COUNT(*) FROM wages WHERE sector = 'food' GROUP BY wage;
What are the maximum and minimum ranges of electric vehicles grouped by make?
CREATE TABLE Electric_Vehicles (Id INT,Make VARCHAR(255),Model VARCHAR(255),Year INT,Range INT); INSERT INTO Electric_Vehicles (Id,Make,Model,Year,Range) VALUES (1,'Tesla','Model 3',2020,263); INSERT INTO Electric_Vehicles (Id,Make,Model,Year,Range) VALUES (2,'Chevrolet','Bolt',2020,259); INSERT INTO Electric_Vehicles (Id,Make,Model,Year,Range) VALUES (3,'Nissan','Leaf',2020,150);
SELECT Make, MAX(Range) AS Max_Range, MIN(Range) AS Min_Range FROM Electric_Vehicles GROUP BY Make;
What is the change in electric vehicle sales, compared to the previous month, per make?
CREATE TABLE MonthlyElectricVehicleSales (id INT,sale_date DATE,make VARCHAR(20),model VARCHAR(20),num_vehicles_sold INT); INSERT INTO MonthlyElectricVehicleSales (id,sale_date,make,model,num_vehicles_sold) VALUES (1,'2022-01-01','Tesla','Model S',1200),(2,'2022-01-01','Tesla','Model 3',1500),(3,'2022-02-01','Tesla','Model S',1250),(4,'2022-02-01','Tesla','Model 3',1600),(5,'2022-03-01','Tesla','Model S',1300),(6,'2022-03-01','Tesla','Model 3',1700),(7,'2022-01-01','Volvo','XC60',200),(8,'2022-02-01','Volvo','XC60',250),(9,'2022-03-01','Volvo','XC60',300);
SELECT make, EXTRACT(MONTH FROM sale_date) AS month, (num_vehicles_sold - LAG(num_vehicles_sold) OVER (PARTITION BY make ORDER BY EXTRACT(MONTH FROM sale_date))) * 100.0 / LAG(num_vehicles_sold) OVER (PARTITION BY make ORDER BY EXTRACT(MONTH FROM sale_date)) AS pct_change FROM MonthlyElectricVehicleSales;
Find the number of users who have never used wearable technology.
CREATE TABLE Users (id INT,uses_wearable BOOLEAN); INSERT INTO Users (id,uses_wearable) VALUES (1,false),(2,true),(3,false),(4,true),(5,false);
SELECT COUNT(*) FROM Users WHERE uses_wearable = false;
List the number of members who joined in each month, for the last year.
CREATE TABLE members (id INT,join_date DATE);
SELECT MONTH(join_date) as month, COUNT(*) as members_joined FROM members WHERE join_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY month;
Find the AI safety incidents that occurred in Europe and were related to data privacy or unintended behavior.
CREATE TABLE eu_ai_safety_incidents (id INT,incident_name VARCHAR(255),country VARCHAR(255),incident_category VARCHAR(255)); INSERT INTO eu_ai_safety_incidents (id,incident_name,country,incident_category) VALUES (1,'IncidentF','Germany','Data Privacy'),(2,'IncidentG','France','Unintended Behavior'),(3,'IncidentH','UK','Data Privacy');
SELECT * FROM eu_ai_safety_incidents WHERE country IN ('Germany', 'France', 'UK') AND incident_category IN ('Data Privacy', 'Unintended Behavior');
What is the distribution of algorithm types used in explainable AI research?
CREATE TABLE explainable_ai (id INT,research_name VARCHAR(50),algorithm_type VARCHAR(50)); INSERT INTO explainable_ai (id,research_name,algorithm_type) VALUES (1,'Interpretable Neural Networks','Neural Network'),(2,'SHAP Values','Decision Tree'),(3,'LIME','Logistic Regression');
SELECT algorithm_type, COUNT(*) FROM explainable_ai GROUP BY algorithm_type;
What is the total cost of all agricultural innovation projects, ordered by the project cost in descending order?
CREATE TABLE agri_innovation_projects (id INT,project_name VARCHAR(255),location VARCHAR(255),sector VARCHAR(255),cost FLOAT); INSERT INTO agri_innovation_projects (id,project_name,location,sector,cost) VALUES (1,'Precision Agriculture','Village X','Agriculture',35000.00),(2,'Drip Irrigation','Village Y','Agriculture',28000.00),(3,'Solar Powered Cold Storage','Village Z','Agriculture',52000.00);
SELECT SUM(cost) as total_cost FROM agri_innovation_projects ORDER BY total_cost DESC;
What is the maximum amount of dissolved oxygen (DO) in the ocean_health table for each month in 2021?
CREATE TABLE ocean_health (date DATE,do_value INT); INSERT INTO ocean_health (date,do_value) VALUES ('2021-01-01',8),('2021-01-02',7),('2021-02-01',6),('2021-02-02',9);
SELECT EXTRACT(MONTH FROM date) as month, MAX(do_value) as max_do_value FROM ocean_health WHERE date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY EXTRACT(MONTH FROM date);
What is the stocking density (fish per cubic meter) for each species in 2021?
CREATE TABLE fish_stock (species VARCHAR(255),year INT,stocking_density INT); INSERT INTO fish_stock (species,year,stocking_density) VALUES ('Salmon',2021,30),('Tilapia',2021,50),('Catfish',2021,40);
SELECT species, AVG(stocking_density) as avg_density FROM fish_stock WHERE year = 2021 GROUP BY species;
What is the number of employees for contractors who implemented sustainable practices?
CREATE TABLE Contractors (ContractorID INT,ContractorName VARCHAR(50),City VARCHAR(50),State VARCHAR(2),Country VARCHAR(50)); CREATE TABLE LaborStatistics (StatisticID INT,ContractorID INT,EmployeeCount INT,HourlyRate FLOAT,Date DATE); CREATE TABLE SustainablePractices (PracticeID INT,ContractorID INT,PracticeType VARCHAR(50),ImplementationDate DATE); INSERT INTO Contractors (ContractorID,ContractorName,City,State,Country) VALUES (4,'MNO Construction','Miami','FL','USA'); INSERT INTO LaborStatistics (StatisticID,ContractorID,EmployeeCount,HourlyRate,Date) VALUES (1,4,60,40,'2022-01-05'); INSERT INTO SustainablePractices (PracticeID,ContractorID,PracticeType,ImplementationDate) VALUES (1,4,'Rainwater Harvesting','2022-02-01');
SELECT ContractorID FROM SustainablePractices; SELECT SUM(EmployeeCount) FROM LaborStatistics WHERE ContractorID IN (SELECT ContractorID FROM SustainablePractices);
What is the average price of an eighth of an ounce of cannabis in each dispensary?
CREATE TABLE Prices (dispensary VARCHAR(255),price DECIMAL(10,2),product VARCHAR(255)); INSERT INTO Prices (dispensary,price,product) VALUES ('Dispensary A',35,'Eighth'),('Dispensary A',40,'Quarter'),('Dispensary B',30,'Eighth'),('Dispensary B',45,'Quarter');
SELECT dispensary, AVG(price) FROM Prices WHERE product = 'Eighth' GROUP BY dispensary;
Insert a new case with the following data: case_id 6, client_name 'Jim Brown', case_type 'traffic', case_outcome 'pending', case_date '2022-05-05' into the 'traffic' table
CREATE TABLE traffic (case_id INT,client_name VARCHAR(50),case_type VARCHAR(20),case_outcome VARCHAR(20),case_date DATE);
INSERT INTO traffic (case_id, client_name, case_type, case_outcome, case_date) VALUES (6, 'Jim Brown', 'traffic', 'pending', '2022-05-05');
Calculate the average usage hours for machines that were maintained in the last 30 days.
CREATE TABLE machine_maintenance_new2 (id INT PRIMARY KEY,machine_name VARCHAR(50),last_maintenance_date DATE); CREATE TABLE machine_usage_new2 (id INT PRIMARY KEY,machine_name VARCHAR(50),usage_hours INT);
SELECT AVG(usage_hours) as avg_usage_hours FROM machine_usage_new2 m INNER JOIN machine_maintenance_new2 mm ON m.machine_name = mm.machine_name WHERE mm.last_maintenance_date > CURDATE() - INTERVAL 30 DAY;
Identify drugs that were approved but not launched in the market.
CREATE TABLE drug_approval (drug_id INT,approval_date DATE); INSERT INTO drug_approval (drug_id,approval_date) VALUES (101,'2020-01-01'),(102,'2019-06-15'),(103,'2021-03-20'); CREATE TABLE drug_launch (drug_id INT,launch_date DATE); INSERT INTO drug_launch (drug_id,launch_date) VALUES (101,'2020-02-01'),(103,'2021-04-01');
SELECT da.drug_id FROM drug_approval da LEFT JOIN drug_launch dl ON da.drug_id = dl.drug_id WHERE dl.drug_id IS NULL;
What was the total sales revenue for 'DrugB' in Q1 2021 in 'Europe'?
CREATE TABLE sales (drug_name TEXT,sale_date DATE,revenue FLOAT); INSERT INTO sales (drug_name,sale_date,revenue) VALUES ('DrugB','2021-01-01',12000),('DrugB','2021-01-02',13000),('DrugB','2021-04-01',14000),('DrugB','2021-04-02',15000);
SELECT SUM(revenue) FROM sales WHERE drug_name = 'DrugB' AND sale_date BETWEEN '2021-01-01' AND '2021-01-31';
Which wholesalers offer the deepest discounts on drugs in the Central region, and how many drugs do they discount?
CREATE TABLE wholesaler_discounts (id INT PRIMARY KEY,drug_id INT,wholesaler VARCHAR(255),discount_rate DECIMAL(4,2)); CREATE TABLE drugs (id INT PRIMARY KEY,region VARCHAR(255));
SELECT w.wholesaler, COUNT(w.id) as drugs_discounted, AVG(w.discount_rate) as average_discount_rate FROM wholesaler_discounts w INNER JOIN drugs d ON w.drug_id = d.id WHERE d.region = 'Central' GROUP BY w.wholesaler ORDER BY average_discount_rate DESC, drugs_discounted DESC;
What is the hospital capacity utilization rate by hospital name, ordered within each state?
CREATE TABLE CapacityUtilization (StateName VARCHAR(50),HospitalName VARCHAR(50),Capacity INT,Utilization INT); INSERT INTO CapacityUtilization (StateName,HospitalName,Capacity,Utilization) VALUES ('Alabama','HospitalA',250,75),('Alabama','HospitalB',300,80),('Alaska','HospitalX',50,60),('Arizona','HospitalY',400,90),('Arizona','HospitalZ',350,85);
SELECT StateName, HospitalName, Utilization, PERCENT_RANK() OVER (PARTITION BY StateName ORDER BY Utilization DESC) AS PercentRank FROM CapacityUtilization
What is the number of dental visits per year in each state?
CREATE TABLE dental_visits (id INT,state TEXT,visits INT); INSERT INTO dental_visits (id,state,visits) VALUES (1,'California',2); INSERT INTO dental_visits (id,state,visits) VALUES (2,'New York',3);
SELECT state, AVG(visits) FROM dental_visits GROUP BY state;
What is the total number of mental health visits in rural areas in the US?
CREATE TABLE mental_health_visits (visit_id INT,location VARCHAR(20)); INSERT INTO mental_health_visits (visit_id,location) VALUES (1,'Rural'); INSERT INTO mental_health_visits (visit_id,location) VALUES (2,'Urban');
SELECT COUNT(*) FROM mental_health_visits WHERE location = 'Rural';
List all companies founded by individuals from the ASEAN region
CREATE TABLE company_founding(id INT PRIMARY KEY,company_name VARCHAR(100),founder_country VARCHAR(50)); INSERT INTO company_founding VALUES (1,'Acme Inc','Singapore'); INSERT INTO company_founding VALUES (2,'Beta Corp','Indonesia'); INSERT INTO company_founding VALUES (3,'Charlie LLC','Thailand'); INSERT INTO company_founding VALUES (4,'Delta Inc','Malaysia'); INSERT INTO company_founding VALUES (5,'Echo Inc','Philippines');
SELECT company_name FROM company_founding WHERE founder_country IN ('Singapore', 'Indonesia', 'Thailand', 'Malaysia', 'Philippines');
What is the maximum funding raised in a single round by a startup with a female founder in the HealthTech sector?
CREATE TABLE funding_rounds (id INT,company_id INT,round_type TEXT,amount INT,date DATE); INSERT INTO funding_rounds (id,company_id,round_type,amount,date) VALUES (1,1,'Seed',1000000,'2020-01-01'),(2,2,'Series A',5000000,'2021-01-01'),(3,3,'Seed',2000000,'2019-01-01');
SELECT MAX(funding_rounds.amount) FROM funding_rounds JOIN companies ON funding_rounds.company_id = companies.id WHERE companies.founder_gender = 'Female' AND companies.industry = 'HealthTech';
Update the community_policing table and mark 'true' for the record where the community_policing_id is 3
CREATE TABLE community_policing (community_policing_id INT,is_active BOOLEAN);
UPDATE community_policing SET is_active = true WHERE community_policing_id = 3;
What is the minimum response time for emergency calls in each neighborhood?
CREATE TABLE neighborhoods (nid INT,neighborhood_name VARCHAR(255)); CREATE TABLE emergencies (eid INT,nid INT,response_time INT);
SELECT n.neighborhood_name, MIN(e.response_time) FROM neighborhoods n INNER JOIN emergencies e ON n.nid = e.nid GROUP BY n.neighborhood_name;
What is the total number of emergency response calls in each city district?
CREATE TABLE districts (did INT,name VARCHAR(255)); CREATE TABLE calls (cid INT,did INT,time DATETIME); INSERT INTO districts VALUES (1,'Downtown'),(2,'Uptown'); INSERT INTO calls VALUES (1,1,'2022-01-01 12:00:00'),(2,2,'2022-01-01 13:00:00');
SELECT d.name, COUNT(c.cid) as num_calls FROM districts d JOIN calls c ON d.did = c.did GROUP BY d.did;
What is the average age of painters in the database?
CREATE TABLE Artists (name VARCHAR(255),age INT,art VARCHAR(255)); INSERT INTO Artists (name,age,art) VALUES ('Picasso',91,'Painter'),('Van Gogh',37,'Painter'),('Dali',84,'Painter');
SELECT AVG(age) FROM Artists WHERE art = 'Painter';
What is the total number of clients who have invested in the 'Global Fund'?
CREATE TABLE clients (client_id INT,name TEXT,region TEXT); INSERT INTO clients (client_id,name,region) VALUES (1,'John Doe','US'),(2,'Jane Smith','APAC'),(3,'Mike Johnson','EU'),(4,'Sophia Chen','APAC'); CREATE TABLE investments (client_id INT,fund_id INT,amount DECIMAL(10,2)); INSERT INTO investments (client_id,fund_id,amount) VALUES (1,1,15000.00),(1,2,20000.00),(2,1,30000.00),(5,1,40000.00); CREATE TABLE funds (fund_id INT,fund_name TEXT,category TEXT); INSERT INTO funds (fund_id,fund_name,category) VALUES (1,'Global Fund','Fixed Income'),(2,'Regional Fund','Equity');
SELECT COUNT(DISTINCT c.client_id) FROM clients c JOIN investments i ON c.client_id = i.client_id JOIN funds f ON i.fund_id = f.fund_id WHERE f.fund_name = 'Global Fund';
Which investment strategies have a total transaction value of more than 100000 for a private equity firm?
CREATE TABLE investment_strategies (strategy_id INT,name VARCHAR(255)); CREATE TABLE private_equity_transactions (transaction_id INT,strategy_id INT,amount DECIMAL(10,2),trans_date DATE);
SELECT investment_strategies.name FROM investment_strategies INNER JOIN private_equity_transactions ON investment_strategies.strategy_id = private_equity_transactions.strategy_id GROUP BY investment_strategies.name HAVING SUM(private_equity_transactions.amount) > 100000;
Find the minimum ESG score for companies in the education sector.
CREATE TABLE companies (id INT,name VARCHAR(255),sector VARCHAR(255),ESG_score FLOAT); INSERT INTO companies (id,name,sector,ESG_score) VALUES (1,'EverFi','Education',75.0),(2,'Coursera','Education',78.5),(3,'Khan Academy','Education',82.0);
SELECT MIN(ESG_score) FROM companies WHERE sector = 'Education';
How many unique 'regions' are represented in the 'Locations' table for 'RenewableEnergy'?
CREATE TABLE LocationsRE (id INT,country VARCHAR(255),region VARCHAR(255),sector VARCHAR(255));
SELECT COUNT(DISTINCT region) FROM LocationsRE WHERE sector = 'RenewableEnergy';
List all military technologies and their regions from the 'Military_Tech' table.
CREATE TABLE Military_Tech (id INT,name VARCHAR(50),type VARCHAR(20),region VARCHAR(20)); INSERT INTO Military_Tech (id,name,type,region) VALUES (1,'Stealth Fighter','Aircraft','North America');
SELECT * FROM Military_Tech;
What was the total amount donated by repeat donors from Canada in Q1 2022?
CREATE TABLE Donors (DonorID int,DonorName varchar(50),Country varchar(50),FirstDonationDate date); INSERT INTO Donors VALUES (1,'John Smith','Canada','2021-01-01');
SELECT SUM(DonationAmount) FROM Donations D JOIN Donors DON ON D.DonorID = DON.DonorID WHERE DON.Country = 'Canada' AND D.DonationDate BETWEEN '2022-01-01' AND '2022-03-31' AND EXISTS (SELECT 1 FROM Donations D2 WHERE D2.DonorID = D.DonorID AND D2.DonationDate < '2022-01-01')
What is the percentage of total humanitarian aid spent on education in each world region?
CREATE TABLE humanitarian_aid (id INT,region TEXT,category TEXT,amount FLOAT); INSERT INTO humanitarian_aid (id,region,category,amount) VALUES (1,'Africa','Education',500),(2,'Asia','Health',750),(3,'Africa','Health',250);
SELECT region, (SUM(case when category = 'Education' then amount else 0 end) / SUM(amount)) * 100 as education_percentage FROM humanitarian_aid GROUP BY region;
What is the total number of refugee families supported by each NGO in the last 6 months?
CREATE TABLE NGOs (NGOID int,NGOName varchar(50)); INSERT INTO NGOs (NGOID,NGOName) VALUES (1,'International Rescue Committee'),(2,'Save the Children'); CREATE TABLE RefugeeSupport (SupportID int,NGOID int,FamilyID int,SupportDate date); INSERT INTO RefugeeSupport (SupportID,NGOID,FamilyID,SupportDate) VALUES (1,1,1,'2022-01-01'),(2,1,2,'2022-02-01'),(3,2,1,'2022-03-01');
SELECT NGOName, COUNT(DISTINCT FamilyID) as SupportedFamilies FROM NGOs INNER JOIN RefugeeSupport ON NGOs.NGOID = RefugeeSupport.NGOID WHERE SupportDate >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY NGOName;
How many vehicles of type 'Trolleybus' are due for maintenance in the next 30 days?
CREATE TABLE vehicles (id INT,vehicle_type VARCHAR(255),model_year INT,last_maintenance_date DATE,next_maintenance_date DATE); INSERT INTO vehicles (id,vehicle_type,model_year,last_maintenance_date,next_maintenance_date) VALUES (2004,'Trolleybus',2020,'2022-04-20','2022-07-20'),(2005,'Tram',2019,'2022-05-15','2022-11-15');
SELECT vehicle_type, TIMESTAMPDIFF(DAY, CURDATE(), next_maintenance_date) as days_until_next_maintenance FROM vehicles WHERE vehicle_type = 'Trolleybus' HAVING days_until_next_maintenance <= 30;