instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What was the total revenue for the state of California in January 2022?
CREATE TABLE sales (id INT,state VARCHAR(20),revenue DECIMAL(10,2),month INT,year INT);
SELECT SUM(revenue) FROM sales WHERE state = 'California' AND month = 1 AND year = 2022;
Count the number of restaurants in the "urban" area that serve vegetarian options.
CREATE TABLE restaurant_menu (restaurant_id INT,serves_vegetarian BOOLEAN);INSERT INTO restaurant_menu (restaurant_id,serves_vegetarian) VALUES (1,TRUE),(2,FALSE),(3,TRUE),(4,TRUE),(5,FALSE);CREATE TABLE restaurants (restaurant_id INT,name VARCHAR(255),area VARCHAR(255));INSERT INTO restaurants (restaurant_id,name,area) VALUES (1,'Plant-Based Bistro','urban'),(2,'Steakhouse','urban'),(3,'Vegetarian Cafe','suburban'),(4,'Italian Restaurant','rural'),(5,'Seafood Grill','urban');
SELECT COUNT(restaurant_menu.restaurant_id) FROM restaurant_menu JOIN restaurants ON restaurant_menu.restaurant_id = restaurants.restaurant_id WHERE restaurants.area = 'urban' AND restaurant_menu.serves_vegetarian = TRUE;
Show the average delivery time and cost for each customer in South America.
CREATE TABLE Customer_Deliveries (id INT,delivery_date DATETIME,delivery_country VARCHAR(50),customer_id INT,delivery_time INT,delivery_cost DECIMAL(10,2)); INSERT INTO Customer_Deliveries (id,delivery_date,delivery_country,customer_id,delivery_time,delivery_cost) VALUES (1,'2022-01-01','Brazil',1,3,50.00),(2,'2022-01-02','Argentina',2,4,60.00),(3,'2022-01-03','Colombia',3,5,70.00);
SELECT customer_id, AVG(delivery_time) AS average_delivery_time, AVG(delivery_cost) AS average_delivery_cost FROM Customer_Deliveries WHERE delivery_country IN ('Brazil', 'Argentina', 'Colombia') GROUP BY customer_id;
What is the minimum mental health score of students in 'Fall 2021'?
CREATE TABLE student_mental_health (student_id INT,mental_health_score INT,date DATE); INSERT INTO student_mental_health (student_id,mental_health_score,date) VALUES (1,80,'2021-09-01'),(2,85,'2021-09-01'),(3,70,'2021-09-02');
SELECT MIN(mental_health_score) FROM student_mental_health WHERE date = '2021-09-01';
What is the total installed renewable energy capacity (in MW) for each country in the renewable_energy table, grouped by country and sorted by the highest capacity?
CREATE TABLE renewable_energy (city VARCHAR(50),country VARCHAR(50),technology VARCHAR(50),capacity FLOAT); INSERT INTO renewable_energy (city,country,technology,capacity) VALUES ('CityA','CountryA','Solar',30),('CityB','CountryB','Solar',50),('CityC','CountryA','Solar',80);
SELECT country, SUM(capacity) as total_renewable_energy_capacity FROM renewable_energy GROUP BY country ORDER BY total_renewable_energy_capacity DESC;
What is the total flight time for each aircraft model?
CREATE TABLE Aircraft (ID INT,Model VARCHAR(50),FlightHours INT); INSERT INTO Aircraft (ID,Model,FlightHours) VALUES (1,'B747',120000),(2,'A320',90000),(3,'A380',150000),(4,'B777',200000);
SELECT Model, SUM(FlightHours) OVER (PARTITION BY Model) as TotalFlightTime FROM Aircraft;
How many products were sold by each vendor in the United Kingdom?
CREATE TABLE sales (sale_id int,product_id int,vendor_id int,quantity int,sale_date date); CREATE TABLE vendors (vendor_id int,vendor_name varchar(255),country varchar(50)); INSERT INTO sales (sale_id,product_id,vendor_id,quantity,sale_date) VALUES (1,1,101,10,'2022-01-01'); INSERT INTO vendors (vendor_id,vendor_name,country) VALUES (101,'Eco Vendors','United Kingdom');
SELECT vendor_id, SUM(quantity) AS total_sold FROM sales JOIN vendors ON sales.vendor_id = vendors.vendor_id WHERE country = 'United Kingdom' GROUP BY vendor_id;
List suppliers with the highest CO2 emissions and their total emissions in the past year.
CREATE TABLE suppliers (supplier_id INT,supplier_name VARCHAR(255),co2_emissions INT); CREATE VIEW supplier_orders AS SELECT supplier_id,SUM(quantity_ordered * product_co2_emissions) as total_co2 FROM orders GROUP BY supplier_id;
SELECT s.supplier_name, SUM(so.total_co2) as total_emissions FROM suppliers s INNER JOIN supplier_orders so ON s.supplier_id = so.supplier_id WHERE so.order_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND CURRENT_DATE GROUP BY s.supplier_name ORDER BY total_emissions DESC LIMIT 10;
Show the total quantity of raw materials for each department
CREATE TABLE departments (id INT,name VARCHAR(20)); CREATE TABLE products (id INT,department_id INT,name VARCHAR(20),material VARCHAR(20),quantity INT); INSERT INTO departments (id,name) VALUES (1,'textiles'),(2,'metallurgy'); INSERT INTO products (id,department_id,name,material,quantity) VALUES (1,1,'beam','steel',100),(2,1,'plate','steel',200),(3,2,'rod','aluminum',150),(4,2,'foil','aluminum',50),(5,1,'yarn','cotton',200),(6,1,'thread','polyester',300),(7,2,'wire','copper',500);
SELECT d.name, SUM(p.quantity) FROM departments d INNER JOIN products p ON d.id = p.department_id GROUP BY d.name;
List the names of all volunteers who have worked on projects related to 'disaster relief' or 'housing' and their total donations, excluding any duplicates.
CREATE TABLE donations (id INT,donor_id INT,amount INT); CREATE TABLE donors (id INT,name VARCHAR(30),cause_area VARCHAR(20)); INSERT INTO donors (id,name,cause_area) VALUES (1,'Bob','disaster relief'),(2,'Alice','housing'),(3,'Charlie','education'); INSERT INTO donations (id,donor_id,amount) VALUES (1,1,500),(2,1,500),(3,2,700);
SELECT donors.name, SUM(donations.amount) FROM donors INNER JOIN donations ON donors.id = donations.donor_id WHERE donors.cause_area IN ('disaster relief', 'housing') GROUP BY donors.name;
What is the maximum number of marine species found in any ocean basin?
CREATE TABLE number_of_species (ocean VARCHAR(255),species_count INT); INSERT INTO number_of_species (ocean,species_count) VALUES ('Pacific',20000),('Atlantic',15000),('Indian',12000),('Southern',8000);
SELECT MAX(species_count) FROM number_of_species;
How many visitors interacted with digital museum content in Sydney in Q1 2021?
CREATE TABLE Digital_Content_Interactions (visitor_id INT,city VARCHAR(50),quarter INT,year INT,interaction_count INT);
SELECT SUM(interaction_count) FROM Digital_Content_Interactions WHERE city = 'Sydney' AND quarter = 1 AND year = 2021;
How many network devices are installed in each region?
CREATE TABLE network_devices (id INT,region VARCHAR(10),device_type VARCHAR(20)); INSERT INTO network_devices (id,region,device_type) VALUES (1,'urban','tower'),(2,'rural','tower'),(3,'urban','router'),(4,'rural','router'),(5,'urban','switch');
SELECT region, COUNT(*) FROM network_devices GROUP BY region;
Delete all records from the 'sustainable_forestry' table where the location is 'Location2'.
CREATE TABLE sustainable_forestry (id INT,location VARCHAR(255),species VARCHAR(255)); INSERT INTO sustainable_forestry (id,location,species) VALUES (1,'Location1','Pine'),(2,'Location2','Oak'),(3,'Location3','Spruce'),(4,'Location4','Pine');
DELETE FROM sustainable_forestry WHERE location = 'Location2';
What is the total amount of financial assistance provided to microfinance borrowers?
CREATE TABLE microfinance (id INT,borrower_id INT,amount DECIMAL(10,2)); INSERT INTO microfinance (id,borrower_id,amount) VALUES (1,1,200.00),(2,2,300.00),(3,3,150.00),(4,4,400.00);
SELECT SUM(amount) FROM microfinance;
How many safety inspections were conducted per month in the last year?
CREATE TABLE inspections (id INT,vessel_id INT,inspection_date DATE);
SELECT MONTH(inspection_date) as month, COUNT(*) as num_inspections FROM inspections WHERE inspection_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY month;
What is the total number of police calls in the state of California?
CREATE TABLE police_calls (id INT,call_type VARCHAR(50),call_location VARCHAR(100),call_date DATE,city VARCHAR(50),state VARCHAR(50)); INSERT INTO police_calls (id,call_type,call_location,call_date,city,state) VALUES (1,'Disturbance','789 Oak St','2022-02-01','San Francisco','CA');
SELECT COUNT(*) FROM police_calls WHERE state = 'CA';
Delete exhibitions of artist 'Yayoi Kusama' from the 'Exhibitions' table.
CREATE TABLE Exhibitions (exhibition_id INT,exhibition_name VARCHAR(255),artist_id INT); INSERT INTO Exhibitions (exhibition_id,exhibition_name,artist_id) VALUES (1,'Infinity Nets',8),(2,'My Eternal Soul',8);
DELETE FROM Exhibitions WHERE artist_id = 8;
What are the annual sales figures for garments made with organic cotton?
CREATE TABLE Sales (saleID INT,garmentID INT,year INT,revenue DECIMAL(5,2)); INSERT INTO Sales (saleID,garmentID,year,revenue) VALUES (1,1,2020,25000.00),(2,2,2020,30000.00),(3,1,2019,22000.00);
SELECT SUM(revenue) FROM Sales WHERE garmentID IN (SELECT garmentID FROM GarmentProduction WHERE material = 'Organic Cotton');
What is the percentage of cases that resulted in a conviction, for each court location, in the past year?
CREATE TABLE Courts (Location VARCHAR(255),CourtID INT); CREATE TABLE Cases (CaseID INT,CourtID INT,CaseDate DATE,Verdict VARCHAR(255));
SELECT Courts.Location, COUNT(*) OVER(PARTITION BY Courts.Location) * 100.0 / SUM(COUNT(*)) OVER() AS Percentage FROM Courts JOIN Cases ON Courts.CourtID = Cases.CourtID WHERE Verdict = 'Conviction' AND CaseDate >= DATEADD(YEAR, -1, GETDATE()) GROUP BY Courts.Location, Courts.CourtID;
What is the total number of labor hours worked on mining projects in South America in 2020?
CREATE TABLE labor (project_id INT,region TEXT,hours INT,year INT); INSERT INTO labor (project_id,region,hours,year) VALUES (1,'South America',2500,2020),(2,'North America',3000,2019);
SELECT SUM(hours) FROM labor WHERE region = 'South America' AND year = 2020;
What is the average labor cost per square foot for LEED-certified projects in New York?
CREATE TABLE Labor_Per_Square_Foot (id INT,project_name TEXT,state TEXT,is_leed_certified BOOLEAN,labor_cost_per_square_foot FLOAT); INSERT INTO Labor_Per_Square_Foot (id,project_name,state,is_leed_certified,labor_cost_per_square_foot) VALUES (1,'Sustainable Offices','New York',true,60.0),(2,'Conventional Building','New York',false,50.0);
SELECT AVG(labor_cost_per_square_foot) FROM Labor_Per_Square_Foot WHERE state = 'New York' AND is_leed_certified = true;
Find the average number of animals per habitat for each education program.
CREATE TABLE animals_per_habitat (id INT,habitat_id INT,animal_count INT); CREATE TABLE education_programs (id INT,habitat_id INT,coordinator_name VARCHAR(50));
SELECT e.coordinator_name, AVG(ap.animal_count) FROM animals_per_habitat ap INNER JOIN education_programs e ON ap.habitat_id = e.habitat_id GROUP BY e.coordinator_name;
Find the earliest call date and call type in the 'beach_patrol' table.
CREATE TABLE beach_patrol (id INT,call_type VARCHAR(20),call_date TIMESTAMP); INSERT INTO beach_patrol VALUES (1,'swimming','2022-01-03 19:00:00'),(2,'lost_child','2022-01-04 20:00:00');
SELECT call_type, MIN(call_date) FROM beach_patrol;
What is the infection rate of malaria in each district?
CREATE TABLE districts (district_id INT,district_name TEXT,region TEXT,malaria_cases INT); INSERT INTO districts (district_id,district_name,region,malaria_cases) VALUES (1,'Downtown','East',45),(2,'Uptown','East',78),(3,'Rural','West',32);
SELECT district, malaria_cases/population AS infection_rate FROM (SELECT district_name AS district, SUM(malaria_cases) OVER (PARTITION BY region) AS malaria_cases, SUM(population) OVER (PARTITION BY region) AS population FROM districts JOIN populations ON districts.district_id = populations.district_id) ORDER BY district;
How many climate communication campaigns has the Government of India launched in the last 5 years?
CREATE TABLE climate_communication_campaigns (campaign_id INT,campaign_name VARCHAR(50),launch_date DATE,sponsor VARCHAR(50)); INSERT INTO climate_communication_campaigns (campaign_id,campaign_name,launch_date,sponsor) VALUES (1,'Green Future','2017-01-01','Government of India'),(2,'Climate Action','2018-06-15','Government of India'),(3,'Eco Life','2019-12-12','Government of India');
SELECT COUNT(campaign_id) FROM climate_communication_campaigns WHERE sponsor = 'Government of India' AND launch_date >= DATEADD(year, -5, GETDATE());
Insert data into the 'electric_vehicles' table
CREATE TABLE electric_vehicles (id INT,model VARCHAR(50),battery_capacity INT);
INSERT INTO electric_vehicles (id, model, battery_capacity) VALUES (1, 'Tesla Model 3', 75);
What is the total funding received by companies founded by women?
CREATE TABLE Company (id INT,name TEXT,industry TEXT,location TEXT,founding_year INT,founder_gender TEXT,total_funding FLOAT); INSERT INTO Company (id,name,industry,location,founding_year,founder_gender,total_funding) VALUES (1,'EcoInnovations','GreenTech','Nigeria',2018,'Female',5000000),(2,'BioSolutions','Biotech','Brazil',2015,'Male',12000000),(3,'TechBoost','Tech','India',2012,'Male',20000000),(4,'CleanTech','GreenTech','Canada',2020,'Female',8000000);
SELECT SUM(total_funding) FROM Company WHERE founder_gender = 'Female';
What is the daily revenue from vegetarian dishes?
CREATE TABLE sales (sale_id INT,sale_date DATETIME,item_id INT,quantity INT,price FLOAT);
SELECT DATE(sale_date) as sale_date, SUM(price * quantity) as daily_revenue FROM sales JOIN menus ON sales.item_id = menus.menu_id WHERE menus.category = 'vegetarian' GROUP BY sale_date;
What is the total revenue generated from games released in the last 2 years, and how many games were released in this period?
CREATE TABLE GameDesign (GameID INT,GameTitle VARCHAR(20),ReleaseDate DATE); INSERT INTO GameDesign (GameID,GameTitle,ReleaseDate) VALUES (1,'RacingGame','2020-01-01'),(2,'RPG','2019-06-15'),(3,'Shooter','2018-12-25'),(4,'Puzzle','2021-02-20'),(5,'Strategy','2020-07-01');
SELECT SUM(Price) AS TotalRevenue, COUNT(GameID) AS GameCount FROM GameDesign WHERE ReleaseDate >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR);
Identify the number of art performances and heritage sites in each country.
CREATE TABLE CountryData (Country VARCHAR(20),ArtPerformances INT,HeritageSites INT); INSERT INTO CountryData VALUES ('USA',5,3),('Canada',2,1); CREATE VIEW ArtPerformanceCount AS SELECT Country,COUNT(*) AS ArtPerformances FROM CityPerformances GROUP BY Country; CREATE VIEW HeritageSiteCount AS SELECT Country,COUNT(*) AS HeritageSites FROM HeritageSites GROUP BY Country;
SELECT d.Country, a.ArtPerformances, h.HeritageSites FROM CountryData d JOIN ArtPerformanceCount a ON d.Country = a.Country JOIN HeritageSiteCount h ON d.Country = h.Country;
What is the average number of shares for posts in Russian?
CREATE TABLE posts (id INT,language VARCHAR(255),shares INT); INSERT INTO posts (id,language,shares) VALUES (1,'English',10),(2,'Russian',20),(3,'French',30),(4,'Russian',40);
SELECT AVG(shares) FROM posts WHERE language = 'Russian';
Show the maximum and minimum transaction amounts for each customer in the last month.
CREATE TABLE customers (customer_id INT,name VARCHAR(50)); CREATE TABLE transactions (transaction_id INT,customer_id INT,transaction_amount DECIMAL(10,2)); INSERT INTO customers (customer_id,name) VALUES (1,'John Doe'); INSERT INTO customers (customer_id,name) VALUES (2,'Jane Smith'); INSERT INTO transactions (transaction_id,customer_id,transaction_amount) VALUES (1,1,100.00); INSERT INTO transactions (transaction_id,customer_id,transaction_amount) VALUES (2,2,200.00);
SELECT customer_id, MAX(transaction_amount) as max_transaction_amount, MIN(transaction_amount) as min_transaction_amount FROM transactions WHERE transaction_date BETWEEN DATEADD(month, -1, GETDATE()) AND GETDATE() GROUP BY customer_id;
Insert records into the 'product_transparency' table
CREATE TABLE product_transparency (product_id INT,supplier_id INT,material VARCHAR(50),country_of_origin VARCHAR(50),production_process VARCHAR(50)); INSERT INTO product_transparency (product_id,supplier_id,material,country_of_origin,production_process) VALUES (101,1,'Organic Cotton','India','Handloom'); INSERT INTO product_transparency (product_id,supplier_id,material,country_of_origin,production_process) VALUES (102,2,'Recycled Polyester','Brazil','Machine Woven');
INSERT INTO product_transparency (product_id, supplier_id, material, country_of_origin, production_process) VALUES (101, 1, 'Organic Cotton', 'India', 'Handloom'); INSERT INTO product_transparency (product_id, supplier_id, material, country_of_origin, production_process) VALUES (102, 2, 'Recycled Polyester', 'Brazil', 'Machine Woven');
What is the average salary for employees in each department, and how many employees are in each department?
CREATE TABLE departments (department_id INT,department_name VARCHAR(255)); CREATE TABLE employees (employee_id INT,employee_name VARCHAR(255),department_id INT,salary DECIMAL(10,2)); INSERT INTO departments (department_id,department_name) VALUES (1,'HR'),(2,'IT'),(3,'Marketing'); INSERT INTO employees (employee_id,employee_name,department_id,salary) VALUES (1,'John Doe',1,50000),(2,'Jane Smith',2,60000),(3,'Alice Johnson',3,55000),(4,'Bob Brown',1,52000);
SELECT department_id, department_name, AVG(salary) OVER (PARTITION BY department_id) as avg_salary, COUNT(*) OVER (PARTITION BY department_id) as num_employees FROM departments d JOIN employees e ON d.department_id = e.department_id;
What is the maximum number of games played by users from Canada?
CREATE TABLE Players (PlayerID INT,PlayerName VARCHAR(50),Country VARCHAR(50),GamesPlayed INT); INSERT INTO Players (PlayerID,PlayerName,Country,GamesPlayed) VALUES (1,'John Doe','USA',100),(2,'Jane Smith','Canada',80),(3,'Taro Yamada','Japan',70),(4,'Hana Nakamura','Japan',60);
SELECT MAX(GamesPlayed) FROM Players WHERE Country = 'Canada';
Find the number of aquatic species in each feeding habit category.
CREATE TABLE aquatic_feeding_categories (id INT,feeding_category VARCHAR(255),species_count INT); INSERT INTO aquatic_feeding_categories (id,feeding_category,species_count) VALUES (1,'Carnivore',3),(2,'Herbivore',2),(3,'Omnivore',3);
SELECT feeding_category, species_count FROM aquatic_feeding_categories;
Update the 'regulations' table to set the 'status' column as 'active' for regulations that have a 'publication_date' before '2021-01-01' and 'jurisdiction' containing 'US'.
CREATE TABLE regulations (regulation_id INT,jurisdiction VARCHAR(255),subject VARCHAR(255),publication_date DATE,status VARCHAR(255));
UPDATE regulations SET status = 'active' WHERE jurisdiction LIKE '%US%' AND publication_date < '2021-01-01';
Which countries have hosted the most esports events?
CREATE TABLE cities (id INT,name VARCHAR(255),country VARCHAR(255)); INSERT INTO cities (id,name,country) VALUES (1,'CityA','USA'),(2,'CityB','Canada'),(3,'CityC','Mexico'),(4,'CityD','Brazil'),(5,'CityE','South Korea');
SELECT c.country, COUNT(DISTINCT e.id) as num_events FROM esports_events e JOIN cities c ON e.location = c.name GROUP BY c.country ORDER BY num_events DESC;
What is the average rating of hotels in each country from the hotel_ratings view?
CREATE VIEW hotel_ratings AS SELECT h.hotel_id,h.hotel_name,h.city,h.country,AVG(r.rating) AS avg_rating FROM luxury_hotels h JOIN ratings r ON h.hotel_id = r.hotel_id GROUP BY h.country;
SELECT country, AVG(avg_rating) FROM hotel_ratings GROUP BY country;
What is the average number of accommodations provided per student with a disability?
CREATE TABLE Accommodations (ID INT,StudentID INT,Disability VARCHAR(50),Accommodation VARCHAR(50)); INSERT INTO Accommodations (ID,StudentID,Disability,Accommodation) VALUES (1,1,'Visual Impairment','Braille Materials'); INSERT INTO Accommodations (ID,StudentID,Disability,Accommodation) VALUES (2,1,'Visual Impairment','Assistive Technology'); INSERT INTO Accommodations (ID,StudentID,Disability,Accommodation) VALUES (3,2,'Hearing Impairment','Sign Language Interpreter'); INSERT INTO Accommodations (ID,StudentID,Disability,Accommodation) VALUES (4,2,'Hearing Impairment','Closed Captioning');
SELECT Disability, AVG(COUNT(*)) as AvgAccommodationsPerStudent FROM Accommodations GROUP BY Disability;
What is the average number of cultural heritage sites in each country?
CREATE TABLE cultural_sites (site_id INT,site_name VARCHAR(50),country VARCHAR(50)); INSERT INTO cultural_sites VALUES (1,'Acropolis','Greece'),(2,'Colosseum','Italy'),(3,'Machu Picchu','Peru'),(4,'Taj Mahal','India'),(5,'Petra','Jordan');
SELECT country, AVG(site_count) FROM (SELECT country, COUNT(*) as site_count FROM cultural_sites GROUP BY country) AS subquery GROUP BY country;
Calculate the running total of sales for each dispensary, for the current month.
CREATE TABLE Dispensaries (DispensaryID INT,DispensaryName VARCHAR(50)); CREATE TABLE Sales (SaleID INT,DispensaryID INT,QuantitySold INT,SaleDate DATE);
SELECT DispensaryID, SaleDate, QuantitySold, SUM(QuantitySold) OVER (PARTITION BY DispensaryID ORDER BY SaleDate) AS RunningTotal FROM Sales WHERE SaleDate >= DATEADD(month, 0, GETDATE());
What is the average donation amount per donor by program category?
CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE,DonationAmount FLOAT,ProgramCategory TEXT); INSERT INTO Donations (DonationID,DonorID,DonationDate,DonationAmount,ProgramCategory) VALUES (1,1,'2022-01-01',75.00,'Education'),(2,2,'2022-02-14',125.00,'Health'); CREATE TABLE Donors (DonorID INT,DonorName TEXT); INSERT INTO Donors (DonorID,DonorName) VALUES (1,'John Smith'),(2,'Jane Doe');
SELECT AVG(DonationAmount) AS AvgDonationPerDonor, ProgramCategory FROM (SELECT DonorID, DonationAmount, ProgramCategory FROM Donations) AS DonationData INNER JOIN Donors ON DonationData.DonorID = Donors.DonorID GROUP BY ProgramCategory;
Which mobile and broadband services have experienced the highest growth in revenue in the last quarter?
CREATE TABLE services (service_id INT,service_name VARCHAR(50),service_type VARCHAR(50)); CREATE TABLE revenue_history (history_id INT,service_id INT,revenue INT,revenue_date DATE);
SELECT s.service_name, s.service_type, (r2.revenue - r1.revenue) AS revenue_growth FROM services s INNER JOIN revenue_history r1 ON s.service_id = r1.service_id AND r1.revenue_date = DATEADD(quarter, -1, GETDATE()) INNER JOIN revenue_history r2 ON s.service_id = r2.service_id AND r2.revenue_date = GETDATE() ORDER BY revenue_growth DESC;
How many smart contracts are deployed on the 'cardano' network?
CREATE TABLE blockchain (id INT,network VARCHAR(20),tx_type VARCHAR(20),contract_count INT); INSERT INTO blockchain (id,network,tx_type,contract_count) VALUES (1,'cardano','smart_contract',3000);
SELECT SUM(contract_count) FROM blockchain WHERE network = 'cardano' AND tx_type = 'smart_contract';
What is the average occupancy rate for hotels in New Zealand that promote sustainability?
CREATE TABLE hotel_occupancy(hotel_id INT,hotel_name TEXT,country TEXT,is_sustainable BOOLEAN,occupancy_rate INT); INSERT INTO hotel_occupancy (hotel_id,hotel_name,country,is_sustainable,occupancy_rate) VALUES (1,'Eco Retreat','New Zealand',true,80),(2,'Luxury Resort','New Zealand',false,70),(3,'Green Hotel','New Zealand',true,90);
SELECT AVG(occupancy_rate) FROM hotel_occupancy WHERE country = 'New Zealand' AND is_sustainable = true;
Update the age of patient 1 in the community health center A to 46.
CREATE TABLE community_health_center (name TEXT,patient_id INTEGER,age INTEGER); INSERT INTO community_health_center (name,patient_id,age) VALUES ('Community health center A',1,45),('Community health center A',2,50);
UPDATE community_health_center SET age = 46 WHERE name = 'Community health center A' AND patient_id = 1
Who are the top 5 customers with the highest financial wellbeing scores in 2020 at EthicalFinance?
CREATE TABLE EthicalFinance (id INT,customer_id INT,score INT,score_date DATE); INSERT INTO EthicalFinance (id,customer_id,score,score_date) VALUES (1,2001,95,'2020-12-31');
SELECT customer_id, score FROM EthicalFinance WHERE YEAR(score_date) = 2020 ORDER BY score DESC LIMIT 5;
Rank the top 3 cities with the highest CO2 emissions in 2020 and their total emissions.
CREATE TABLE city_emissions (city VARCHAR(50),year INT,co2_emissions FLOAT); INSERT INTO city_emissions (city,year,co2_emissions) VALUES ('New York',2020,50.3),('Los Angeles',2020,45.6),('Mumbai',2020,40.7);
SELECT city, SUM(co2_emissions) AS total_emissions, RANK() OVER (ORDER BY SUM(co2_emissions) DESC) as co2_rank FROM city_emissions WHERE year = 2020 GROUP BY city HAVING COUNT(*) FILTER (WHERE year = 2020) > 2 ORDER BY total_emissions DESC, city;
What is the total revenue for the top 3 genres?
CREATE TABLE MusicGenre (GenreID INT,GenreName VARCHAR(50),Revenue DECIMAL(10,2)); INSERT INTO MusicGenre (GenreID,GenreName,Revenue) VALUES (1,'Pop',500000.00),(2,'Rock',450000.00),(3,'Jazz',300000.00),(4,'Country',250000.00),(5,'Blues',200000.00);
SELECT GenreName, SUM(Revenue) AS TotalRevenue FROM (SELECT GenreName, Revenue, ROW_NUMBER() OVER (ORDER BY Revenue DESC) AS Rank FROM MusicGenre) AS Subquery WHERE Rank <= 3 GROUP BY GenreName;
What is the minimum time between accidents for vessels in the 'Atlantic' region?
CREATE TABLE Accidents (ID INT PRIMARY KEY,VesselID INT,Region TEXT,AccidentTime DATETIME); INSERT INTO Accidents (ID,VesselID,Region,AccidentTime) VALUES (1,1,'Atlantic','2021-01-01 10:00:00'),(2,2,'Pacific','2021-02-01 15:00:00'),(3,3,'Atlantic','2021-03-01 09:00:00');
SELECT MIN(DATEDIFF('ss', LAG(AccidentTime) OVER (PARTITION BY VesselID ORDER BY AccidentTime), AccidentTime)) FROM Accidents WHERE Region = 'Atlantic';
What is the average price of organic fruits sold by vendors in California?
CREATE TABLE vendors (vendor_id INT,vendor_name VARCHAR(50),state VARCHAR(50)); INSERT INTO vendors VALUES (1,'VendorA','California'); INSERT INTO vendors VALUES (2,'VendorB','Texas'); CREATE TABLE products (product_id INT,product_name VARCHAR(50),price DECIMAL(5,2),organic BOOLEAN); INSERT INTO products VALUES (1,'Apple',1.50,true); INSERT INTO products VALUES (2,'Banana',0.75,false); INSERT INTO products VALUES (3,'Orange',2.00,true);
SELECT AVG(price) FROM products JOIN vendors ON true WHERE products.organic = true AND vendors.state = 'California';
What is the total number of cases and the maximum bail amount in 'justice_cases' table, filtered by 'Violent Crime'?
CREATE TABLE justice_cases (id INT,case_type TEXT,bail_amount INT); INSERT INTO justice_cases (id,case_type,bail_amount) VALUES (1,'Violent Crime',10000),(2,'Property Crime',5000),(3,'Violent Crime',15000);
SELECT COUNT(*), MAX(bail_amount) FROM justice_cases WHERE case_type = 'Violent Crime';
How many green buildings are present in each continent, excluding those with a construction date before 2010?
CREATE TABLE building_details (id INT,building_name VARCHAR(255),continent VARCHAR(255),construction_date DATE);
SELECT continent, COUNT(*) AS building_count FROM building_details WHERE construction_date >= '2010-01-01' GROUP BY continent;
How many tools are there in each category?
CREATE TABLE tool (category VARCHAR(20),tool VARCHAR(20),score INT); INSERT INTO tool (category,tool,score) VALUES ('AI','Chatbot',85),('AI','Image Recognition',90),('Data','Data Visualization',80),('Data','Data Analysis',85);
SELECT category AS category, COUNT(tool) AS num_tools FROM tool GROUP BY category;
Update the sustainable_sourcing table, setting the organic_certified flag to 1 where the country_of_origin is 'Italy'
CREATE TABLE sustainable_sourcing (ingredient_name VARCHAR(50),country_of_origin VARCHAR(50),organic_certified INT);
UPDATE sustainable_sourcing SET organic_certified = 1 WHERE country_of_origin = 'Italy';
What are the earliest and latest years for modern art exhibitions?
CREATE TABLE Exhibitions (ExhibitionID INT,Gallery VARCHAR(100),ArtworkID INT,Country VARCHAR(50),Year INT);
SELECT MIN(Exhibitions.Year) AS EarliestYear, MAX(Exhibitions.Year) AS LatestYear FROM Exhibitions INNER JOIN Artworks ON Exhibitions.ArtworkID = Artworks.ArtworkID WHERE Artworks.Year >= 1900;
What is the percentage of community health workers who identify as LGBTQ+?
CREATE TABLE community_health_workers (id INT,name VARCHAR(50),identifies_as_lgbtq BOOLEAN); INSERT INTO community_health_workers (id,name,identifies_as_lgbtq) VALUES (1,'Alex Garcia',true),(2,'Jamie Smith',false),(3,'Sam Nguyen',true);
SELECT (COUNT(*) FILTER (WHERE identifies_as_lgbtq = true)) * 100.0 / COUNT(*) as percentage FROM community_health_workers;
What is the total budget for community development initiatives in 'community_development' table, grouped by initiative type?
CREATE TABLE community_development (id INT,initiative_type VARCHAR(50),budget INT); INSERT INTO community_development (id,initiative_type,budget) VALUES (1,'Education',50000); INSERT INTO community_development (id,initiative_type,budget) VALUES (2,'Housing',75000);
SELECT initiative_type, SUM(budget) FROM community_development GROUP BY initiative_type;
How many projects are there in the 'water_infrastructure' table in 'New York'?
CREATE TABLE water_infrastructure (id INT,project_name VARCHAR(50),location VARCHAR(50),cost FLOAT); INSERT INTO water_infrastructure (id,project_name,location,cost) VALUES (1,'Water Treatment Plant','San Francisco',5000000); INSERT INTO water_infrastructure (id,project_name,location,cost) VALUES (2,'Dam','New York',8000000);
SELECT COUNT(*) FROM water_infrastructure WHERE location = 'New York';
What is the total carbon emissions of all airlines in the EU in 2019?
CREATE TABLE IF NOT EXISTS airlines (id INT PRIMARY KEY,name TEXT,region TEXT,total_emissions INT,year INT); INSERT INTO airlines (id,name,region,total_emissions,year) VALUES (1,'Airline1','EU',120000,2019),(2,'Airline2','EU',150000,2018),(3,'Airline3','Asia',180000,2019);
SELECT SUM(total_emissions) FROM airlines WHERE region = 'EU' AND year = 2019;
Which software products have the highest average severity of vulnerabilities in the last year?
CREATE TABLE vulnerabilities (id INT,product VARCHAR(50),severity INT,last_patch DATE);
SELECT product, AVG(severity) as avg_severity FROM vulnerabilities WHERE last_patch < DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY product ORDER BY avg_severity DESC;
Find all satellites launched at the 'Vandenberg' launch site.
CREATE TABLE Satellite_Launches (satellite_id INT,launch_year INT,launch_site VARCHAR(255)); INSERT INTO Satellite_Launches (satellite_id,launch_year,launch_site) VALUES (1,2012,'Kourou'),(2,2008,'Vandenberg'),(3,2015,'Baikonur'),(4,2005,'Plesetsk'),(5,2010,'Vandenberg');
SELECT satellite_id FROM Satellite_Launches WHERE launch_site = 'Vandenberg';
Delete records of athletes from the 'tennis_athletes' table who have not participated in Wimbledon?
CREATE TABLE tennis_athletes (athlete_id INT,name VARCHAR(50),age INT,ranking INT,participated_in_wimbledon INT);
DELETE FROM tennis_athletes WHERE participated_in_wimbledon = 0;
Identify and update vessels with outdated engine technology in the fleet_information table.
CREATE TABLE fleet_information (id INT,vessel_name VARCHAR(255),engine_technology DATE); INSERT INTO fleet_information (id,vessel_name,engine_technology) VALUES (1,'Ocean Titan','2000-01-01'),(2,'Sea Explorer','2020-01-01');
UPDATE fleet_information SET engine_technology = '2010-01-01' WHERE id IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY engine_technology) AS rn FROM fleet_information WHERE engine_technology < '2015-01-01') t WHERE t.rn > 1);
What is the average number of AI technology features adopted by hotels in Tokyo?
CREATE TABLE hotels (hotel_id INT,hotel_name TEXT,city TEXT,ai_adoption INT,ai_features INT); INSERT INTO hotels (hotel_id,hotel_name,city,ai_adoption,ai_features) VALUES (1,'The Park Hyatt Tokyo','Tokyo',1,3),(2,'The Four Seasons Hotel Tokyo','Tokyo',1,4),(3,'The Shangri-La Hotel Tokyo','Tokyo',0,0),(4,'The InterContinental Tokyo','Tokyo',1,5),(5,'The Langham Tokyo','Tokyo',0,0);
SELECT city, AVG(ai_features) as avg_features FROM hotels WHERE city = 'Tokyo' GROUP BY city;
What is the total number of defense technology patents filed by the 'National Defense Lab' in the last 3 years?
CREATE TABLE patents (id INT,lab VARCHAR(255),patent_date DATE);
SELECT COUNT(*) as total_patents_filed FROM patents WHERE lab = 'National Defense Lab' AND patent_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR);
List the defense projects with their start and end dates for the UK in 2019?
CREATE TABLE DefenseProjects (project_id INT,project_name VARCHAR(50),start_date DATE,end_date DATE,country VARCHAR(50)); INSERT INTO DefenseProjects (project_id,project_name,start_date,end_date,country) VALUES (1,'Project A','2019-01-01','2019-12-31','UK'),(2,'Project B','2018-06-15','2020-06-15','USA'),(3,'Project C','2019-07-01','2020-01-01','Germany');
SELECT project_name, start_date, end_date FROM DefenseProjects WHERE country = 'UK' AND (start_date BETWEEN '2019-01-01' AND '2019-12-31') OR (end_date BETWEEN '2019-01-01' AND '2019-12-31');
What is the average ocean pH, grouped by month?
CREATE TABLE ocean_ph (id INT,month INT,ph FLOAT); INSERT INTO ocean_ph (id,month,ph) VALUES (1,1,8.1); INSERT INTO ocean_ph (id,month,ph) VALUES (2,2,8.0); INSERT INTO ocean_ph (id,month,ph) VALUES (3,3,7.9);
SELECT month, AVG(ph) FROM ocean_ph GROUP BY month;
List the number of unique mental health conditions per patient in Texas.
CREATE TABLE patient_mental_health_info (patient_id INT,condition VARCHAR(50)); INSERT INTO patient_mental_health_info (patient_id,condition) VALUES (1,'Anxiety'),(1,'Depression'),(2,'Depression'),(3,'PTSD'),(3,'Anxiety'); CREATE TABLE patient_state (patient_id INT,state VARCHAR(50)); INSERT INTO patient_state (patient_id,state) VALUES (1,'Texas'),(2,'Texas'),(3,'California');
SELECT patient_id, COUNT(DISTINCT condition) AS unique_conditions FROM patient_mental_health_info JOIN patient_state ON patient_state.patient_id = patient_mental_health_info.patient_id WHERE state = 'Texas' GROUP BY patient_id;
Find the total biomass of fish in the sustainable_seafood_trends table for each fishing_method.
CREATE TABLE sustainable_seafood_trends (fishing_method VARCHAR(255),biomass FLOAT); INSERT INTO sustainable_seafood_trends (fishing_method,biomass) VALUES ('Line Fishing',500),('Trawling',700),('Potting',600);
SELECT fishing_method, SUM(biomass) FROM sustainable_seafood_trends GROUP BY fishing_method;
What is the maximum financial wellbeing score for clients in the North region?
CREATE TABLE clients (id INT,name VARCHAR,region VARCHAR,financial_wellbeing_score INT); INSERT INTO clients (id,name,region,financial_wellbeing_score) VALUES (1,'Bala','North',78),(2,'Chandra','South',69),(3,'Devi','North',82),(4,'Easwar','East',57);
SELECT MAX(financial_wellbeing_score) FROM clients WHERE region = 'North';
What is the total number of public meetings for each department in the state of California?
CREATE TABLE PublicMeetings (MeetingId INT,MeetingDate DATE,Department VARCHAR(255),State VARCHAR(255)); INSERT INTO PublicMeetings (MeetingId,MeetingDate,Department,State) VALUES (1,'2021-01-01','Transportation','California'),(2,'2021-02-01','Education','California'),(3,'2021-03-01','Healthcare','California');
SELECT Department, COUNT(*) OVER (PARTITION BY Department) as TotalMeetings FROM PublicMeetings WHERE State = 'California';
What was the highest claim amount processed in California?
CREATE TABLE claims (id INT,state VARCHAR(2),amount DECIMAL(10,2)); INSERT INTO claims (id,state,amount) VALUES (1,'TX',500.00),(2,'CA',1500.00),(3,'TX',250.00);
SELECT MAX(amount) FROM claims WHERE state = 'CA';
What is the total transaction value per customer type for the past month?
CREATE TABLE customers (customer_id INT,customer_type VARCHAR(20)); INSERT INTO customers (customer_id,customer_type) VALUES (1,'Retail'),(2,'Wholesale'),(3,'Institutional'); CREATE TABLE transactions (transaction_date DATE,customer_id INT,transaction_value DECIMAL(10,2)); INSERT INTO transactions (transaction_date,customer_id,transaction_value) VALUES ('2022-01-01',1,500.00),('2022-01-02',1,750.00),('2022-01-03',2,3000.00),('2022-01-04',3,15000.00),('2022-02-05',1,200.00),('2022-02-06',2,1200.00),('2022-02-07',3,800.00);
SELECT customers.customer_type, SUM(transactions.transaction_value) as total_transaction_value FROM transactions JOIN customers ON transactions.customer_id = customers.customer_id WHERE transactions.transaction_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY customers.customer_type;
Delete all community policing records that are not active from the 'community_policing' table
CREATE TABLE community_policing (community_policing_id INT,is_active BOOLEAN);
DELETE FROM community_policing WHERE is_active = false;
Display the number of Renewable Energy Projects in each country
CREATE TABLE projects_by_country (id INT,country VARCHAR(50),project_type VARCHAR(50)); INSERT INTO projects_by_country (id,country,project_type) VALUES (1,'USA','Wind Farm'),(2,'Canada','Solar Plant'),(3,'Mexico','Hydro Plant'),(4,'USA','Solar Plant'),(5,'Canada','Wind Farm');
SELECT country, COUNT(*) FROM projects_by_country GROUP BY country;
What is the total number of electric vehicle sales in 2019 and 2020?
CREATE TABLE EV_Sales (Year INT,Make VARCHAR(50),Model VARCHAR(50),Sales INT); INSERT INTO EV_Sales (Year,Make,Model,Sales) VALUES (2020,'Tesla','Model 3',300000); INSERT INTO EV_Sales (Year,Make,Model,Sales) VALUES (2020,'Tesla','Model Y',150000); INSERT INTO EV_Sales (Year,Make,Model,Sales) VALUES (2019,'Nissan','Leaf',120000);
SELECT SUM(Sales) FROM EV_Sales WHERE Year IN (2019, 2020);
What is the average citizen satisfaction score for 'ServiceC' in 'RegionD'?
CREATE TABLE Satisfaction(service VARCHAR(20),region VARCHAR(20),score INT); INSERT INTO Satisfaction VALUES ('ServiceA','RegionC',85),('ServiceA','RegionD',87),('ServiceC','RegionD',84),('ServiceB','RegionC',88),('ServiceB','RegionD',86);
SELECT AVG(score) FROM Satisfaction WHERE service = 'ServiceC' AND region = 'RegionD';
Which restaurants had more than 500 violations?
CREATE TABLE InspectionRecords(restaurant_name VARCHAR(20),violations INT); INSERT INTO InspectionRecords(restaurant_name,violations) VALUES ('Restaurant A',400),('Restaurant B',600),('Restaurant C',300);
SELECT restaurant_name FROM InspectionRecords HAVING violations > 500;
What is the total number of visitors from 'India'?
CREATE TABLE visitors (id INT,country VARCHAR(255),exhibition_id INT); INSERT INTO visitors (id,country,exhibition_id) VALUES (1,'India',1),(2,'Brazil',1),(3,'Russia',1),(4,'India',2),(5,'Brazil',2); CREATE TABLE exhibitions (id INT,name VARCHAR(255),type VARCHAR(255)); INSERT INTO exhibitions (id,name,type) VALUES (1,'Contemporary Art','Modern'),(2,'Ancient Civilizations','Historical');
SELECT COUNT(*) FROM visitors WHERE country = 'India';
What is the average number of employees in the year 2022 for companies in the Healthcare industry?
CREATE TABLE company_stats (id INT,name VARCHAR(50),industry VARCHAR(50),employees INT,year INT); INSERT INTO company_stats (id,name,industry,employees,year) VALUES (1,'HealthCare AI','Healthcare',50,2022); INSERT INTO company_stats (id,name,industry,employees,year) VALUES (2,'GreenTech Solutions','Environment',100,2022); INSERT INTO company_stats (id,name,industry,employees,year) VALUES (3,'CareBots Inc','Healthcare',75,2022);
SELECT AVG(employees) FROM company_stats WHERE year = 2022 AND industry = 'Healthcare';
What is the average length of songs in the pop genre that were released after 2010?
CREATE TABLE songs (id INT,title VARCHAR(255),length FLOAT,genre VARCHAR(255),release_year INT); INSERT INTO songs (id,title,length,genre,release_year) VALUES (1,'Song1',200.5,'Pop',2011),(2,'Song2',180.3,'Rock',2008),(3,'Song3',220.0,'Pop',2012);
SELECT AVG(length) FROM songs WHERE genre = 'Pop' AND release_year > 2010;
Delete all records in the wellbeing_programs table with athlete_id 1
CREATE TABLE wellbeing_programs (program_id INT,athlete_id INT); INSERT INTO wellbeing_programs (program_id,athlete_id) VALUES (1,1),(2,3),(3,1),(4,2);
DELETE FROM wellbeing_programs WHERE athlete_id = 1;
What is the total number of satellites in geostationary orbit?
CREATE TABLE satellite_orbits (satellite_name TEXT,orbit_type TEXT); INSERT INTO satellite_orbits (satellite_name,orbit_type) VALUES ('Intelsat 1','Geostationary'),('Intelsat 2','Geostationary'),('Intelsat 3','Geostationary');
SELECT COUNT(*) FROM satellite_orbits WHERE orbit_type = 'Geostationary';
Which countries have the highest average annual donation amounts?
CREATE TABLE Donations (DonorID INT,Country VARCHAR(50),Amount DECIMAL(10,2)); INSERT INTO Donations (DonorID,Country,Amount) VALUES (1,'USA',5000),(2,'Canada',3000),(3,'Mexico',1000);
SELECT Country, AVG(Amount) as AvgDonation FROM Donations GROUP BY Country ORDER BY AvgDonation DESC;
What is the average quantity of 'Hats' sold by 'Retailer H'?
CREATE TABLE RetailerH (item VARCHAR(20),quantity INT); INSERT INTO RetailerH VALUES ('Hats',10),('Hats',15);
SELECT AVG(quantity) FROM RetailerH WHERE item = 'Hats' AND retailer = 'Retailer H';
What is the total number of open civic tech projects in the state of Illinois?
CREATE TABLE city (id INT PRIMARY KEY,name TEXT,state TEXT); CREATE TABLE project (id INT PRIMARY KEY,name TEXT,status TEXT,city_id INT,FOREIGN KEY (city_id) REFERENCES city(id));
SELECT COUNT(*) FROM project WHERE city_id IN (SELECT id FROM city WHERE state = 'IL') AND status = 'Open';
Update the name of product with id 1 to 'Eco-friendly Product1' in 'FarmersMarket' view
CREATE VIEW FarmersMarket AS SELECT * FROM Products WHERE is_organic = TRUE; INSERT INTO Products (id,name,is_organic) VALUES (1,'Product1',TRUE),(2,'Product2',FALSE),(3,'Product3',TRUE);
UPDATE FarmersMarket SET name = 'Eco-friendly Product1' WHERE id = 1;
How many refugees are there in total in the refugees table, grouped by their nationality?
CREATE TABLE refugees (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),nationality VARCHAR(50)); INSERT INTO refugees (id,name,age,gender,nationality) VALUES (1,'Ahmed',12,'Male','Syrian'); INSERT INTO refugees (id,name,age,gender,nationality) VALUES (2,'Fatima',15,'Female','Afghan');
SELECT nationality, COUNT(*) FROM refugees GROUP BY nationality;
What is the total number of players for the "PuzzleGames" genre in the Oceania region?
CREATE TABLE Games (GameID INT,GameName VARCHAR(255),Genre VARCHAR(255));CREATE TABLE Players (PlayerID INT,PlayerName VARCHAR(255),GameID INT);CREATE VIEW PlayerCount AS SELECT g.Genre,c.Country,COUNT(p.PlayerID) as PlayerCount FROM Games g JOIN Players p ON g.GameID = p.GameID JOIN (SELECT PlayerID,Country FROM PlayerProfile GROUP BY PlayerID) c ON p.PlayerID = c.PlayerID GROUP BY g.Genre,c.Country;
SELECT Genre, SUM(PlayerCount) as TotalPlayers FROM PlayerCount WHERE Genre = 'PuzzleGames' AND Country = 'Oceania' GROUP BY Genre;
What is the minimum salary for employees working in the digital divide sector?
CREATE TABLE digital_divide_employees (employee_id INT,sector VARCHAR(20),salary DECIMAL(10,2)); INSERT INTO digital_divide_employees (employee_id,sector,salary) VALUES (1,'digital_divide',60000.00),(2,'technology_accessibility',65000.00),(3,'digital_divide',62000.00);
SELECT MIN(salary) FROM digital_divide_employees WHERE sector = 'digital_divide';
How many community engagement programs were conducted in 'City X' last year?
CREATE TABLE Community_Engagement (id INT,city VARCHAR(50),year INT,num_programs INT); INSERT INTO Community_Engagement (id,city,year,num_programs) VALUES (1,'City X',2021,10);
SELECT SUM(num_programs) FROM Community_Engagement WHERE city = 'City X' AND year = 2021;
What is the average duration of therapy sessions for each therapist, ordered by the average duration?
CREATE TABLE therapists (id INT,name VARCHAR(50),specialty VARCHAR(50)); INSERT INTO therapists (id,name,speciality) VALUES (1,'Charlotte Thompson','EMDR'); INSERT INTO therapists (id,name,speciality) VALUES (2,'Daniel Kim','Psychodynamic'); CREATE TABLE treatments (id INT,patient_id INT,therapist_id INT,date DATE,duration INT); INSERT INTO treatments (id,patient_id,therapist_id,date,duration) VALUES (1,1,1,'2022-01-01',75); INSERT INTO treatments (id,patient_id,therapist_id,date,duration) VALUES (2,2,2,'2022-01-02',50);
SELECT t.name as therapist_name, AVG(duration) as avg_duration FROM treatments t JOIN therapists tr ON t.therapist_id = tr.id GROUP BY therapist_name ORDER BY avg_duration DESC;
What is the minimum distance between Venus and Mars?
CREATE TABLE space_planets (name TEXT,distance_from_sun FLOAT); INSERT INTO space_planets (name,distance_from_sun) VALUES ('Mercury',0.39),('Venus',0.72),('Earth',1.00),('Mars',1.52),('Jupiter',5.20),('Saturn',9.58),('Uranus',19.18),('Neptune',30.07);
SELECT MIN(ABS(v.distance_from_sun - m.distance_from_sun)) FROM space_planets v, space_planets m WHERE v.name = 'Venus' AND m.name = 'Mars';
Delete all IoT sensor data for farm_id 777
CREATE TABLE iot_sensor_data (id INT,farm_id INT,sensor_type VARCHAR(255),value FLOAT,measurement_date DATE);
DELETE FROM iot_sensor_data WHERE farm_id = 777;
Show the names and costs of all military technologies in the 'communication' category.
CREATE TABLE military_tech (tech_name TEXT,category TEXT,cost INTEGER); INSERT INTO military_tech (tech_name,category,cost) VALUES ('UAV','Surveillance',10000),('Satellite','Communication',15000),('AI System','intelligence operations',20000);
SELECT tech_name, cost FROM military_tech WHERE category = 'Communication'
What is the total amount donated per month in the 'Donations' table?
CREATE TABLE Donations (DonorID INT,DonationDate DATE,Amount DECIMAL(10,2)); INSERT INTO Donations (DonorID,DonationDate,Amount) VALUES (1,'2022-02-01',120.00),(2,'2022-01-15',75.00),(3,'2022-03-05',150.00),(4,'2022-02-28',200.00);
SELECT DATE_FORMAT(DonationDate, '%Y-%m') as Month, SUM(Amount) as TotalDonated FROM Donations GROUP BY Month;
What are the names and types of intangible cultural heritage elements in the Asia-Pacific region?
CREATE TABLE intangible_heritage (id INT,name VARCHAR(255),region VARCHAR(255)); INSERT INTO intangible_heritage (id,name,region) VALUES (1,'Bharatanatyam','Asia-Pacific'); INSERT INTO intangible_heritage (id,name,region) VALUES (2,'Kabuki','Asia-Pacific');
SELECT name, type FROM (SELECT id, name, region, 'intangible' as type FROM intangible_heritage WHERE region = 'Asia-Pacific') AS subquery;