instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Count the number of records in the 'ingredients' table
CREATE TABLE ingredients (id INT,name TEXT,category TEXT); INSERT INTO ingredients (id,name,category) VALUES (1,'Tomato','Produce'),(2,'Olive Oil','Pantry'),(3,'Chicken Breast','Meat'),(4,'Salt','Pantry');
SELECT COUNT(*) FROM ingredients;
What is the average duration (in seconds) of songs released after 2018?
CREATE TABLE songs (id INT,title VARCHAR,duration INT,release_year INT); INSERT INTO songs (id,title,duration,release_year) VALUES (1,'Song1',180,2010),(2,'Song2',240,2015),(3,'Song3',120,2008),(4,'Song4',210,2018),(5,'Song5',300,2020),(6,'Song6',150,2016),(7,'Song7',360,2019),(8,'Song8',270,2017),(9,'Song9',240,2020),(10,'Song10',210,2015);
SELECT AVG(duration) as avg_duration FROM songs WHERE release_year > 2018;
Which region has the most visual arts events?
CREATE TABLE if not exists visual_arts_events (id INT,name VARCHAR(255),region VARCHAR(255),type VARCHAR(255)); INSERT INTO visual_arts_events (id,name,region,type) VALUES (1,'Modern Art Show','Northeast','Visual Arts'),(2,'Photography Exhibit','Southwest','Visual Arts'),(3,'Classic Art Exhibit','Southeast','Visual Arts'),(4,'Contemporary Art Exhibit','Northwest','Visual Arts');
SELECT region, COUNT(*) FROM visual_arts_events WHERE type = 'Visual Arts' GROUP BY region ORDER BY COUNT(*) DESC LIMIT 1;
Calculate the percentage of donations from each payment method
CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL,payment_method VARCHAR,program_id INT);
SELECT payment_method, 100.0 * COUNT(*) / SUM(COUNT(*)) OVER () as percentage FROM donations GROUP BY payment_method;
Which tree species were sighted at a wildlife sanctuary in 2018 and 2019?
CREATE TABLE sightings (id INT,species VARCHAR(255),sanctuary VARCHAR(255),sighting_date DATE);
SELECT species FROM sightings WHERE sanctuary = 'wildlife sanctuary' AND EXTRACT(YEAR FROM sighting_date) IN (2018, 2019);
How many units of product A are stored in each warehouse?
CREATE TABLE warehouses (warehouse_id INT,location TEXT); INSERT INTO warehouses (warehouse_id,location) VALUES (1,'New York'),(2,'Chicago'),(3,'Los Angeles'); CREATE TABLE inventory (product TEXT,warehouse_id INT,quantity INT); INSERT INTO inventory (product,warehouse_id,quantity) VALUES ('Product A',1,100),('Product A',2,200),('Product A',3,300);
SELECT i.product, w.location, SUM(i.quantity) as total_quantity FROM inventory i JOIN warehouses w ON i.warehouse_id = w.warehouse_id WHERE i.product = 'Product A' GROUP BY w.location;
Which countries have the most blockchain nodes and what is their average uptime?
CREATE TABLE blockchain_nodes (node_id INT,node_address VARCHAR(50),country VARCHAR(50),uptime DECIMAL(5,2),last_updated TIMESTAMP);
SELECT country, COUNT(node_id) as node_count, AVG(uptime) as avg_uptime FROM blockchain_nodes WHERE last_updated > '2021-06-01 00:00:00' GROUP BY country ORDER BY node_count DESC;
Add a new league to the teams table
CREATE TABLE teams (id INT PRIMARY KEY,name VARCHAR(50),league VARCHAR(50));
ALTER TABLE teams ADD league VARCHAR(50);
What is the total response time for emergency calls in the city of Chicago, broken down by hour of the day?
CREATE TABLE emergency_calls (id INT,call_time TIMESTAMP,response_time INT,city VARCHAR(20)); INSERT INTO emergency_calls VALUES (1,'2022-01-01 10:00:00',15,'Chicago'); CREATE VIEW hours AS SELECT DATEPART(hour,call_time) as hour,1 as hour_num FROM emergency_calls WHERE city = 'Chicago';
SELECT h.hour, SUM(response_time) as total_response_time FROM hours h JOIN emergency_calls ec ON h.hour = DATEPART(hour, ec.call_time) WHERE ec.city = 'Chicago' GROUP BY h.hour;
Which underwriters have processed more than 5 claims?
CREATE TABLE claims (id INT,underwriter_id INT,processed_date DATE); INSERT INTO claims (id,underwriter_id,processed_date) VALUES (1,1,'2021-01-01'),(2,2,'2021-02-01'),(3,1,'2021-03-01'),(4,2,'2021-02-02'),(5,2,'2021-02-03'),(6,3,'2021-03-01');
SELECT underwriter_id, COUNT(*) FROM claims GROUP BY underwriter_id HAVING COUNT(*) > 5;
What is the average visitor count for dance performances by age group?
CREATE TABLE events (event_id INT,event_name VARCHAR(50),event_type VARCHAR(50),visitor_count INT,age_group VARCHAR(20));
SELECT age_group, AVG(visitor_count) as avg_visitors FROM events WHERE event_type = 'Dance' GROUP BY age_group;
What is the maximum account balance for clients in the Western region?
CREATE TABLE clients (client_id INT,name VARCHAR(50),region VARCHAR(20),account_balance DECIMAL(10,2)); INSERT INTO clients (client_id,name,region,account_balance) VALUES (1,'John Doe','Western',15000.00),(2,'Jane Smith','Eastern',20000.00);
SELECT MAX(account_balance) FROM clients WHERE region = 'Western';
What is the distribution of article categories by gender?
CREATE TABLE article_categories (title text,category text,author_gender text); INSERT INTO article_categories (title,category,author_gender) VALUES ('Article 7','politics','Female'); INSERT INTO article_categories (title,category,author_gender) VALUES ('Article 8','sports','Male');
SELECT author_gender, category, COUNT(*) as count FROM article_categories GROUP BY author_gender, category;
Which artists have created more than 10 artworks in the 'Artworks' table?
CREATE TABLE Artworks (id INT,art_category VARCHAR(255),artist_name VARCHAR(255),year INT,art_medium VARCHAR(255),price DECIMAL(10,2));
SELECT artist_name, COUNT(*) as total FROM Artworks GROUP BY artist_name HAVING total > 10;
What's the total investment in climate finance in India and Brazil from 2015 to 2020?
CREATE TABLE finance_investments (country TEXT,year INT,amount FLOAT); INSERT INTO finance_investments (country,year,amount) VALUES ('India',2015,100000); INSERT INTO finance_investments (country,year,amount) VALUES ('Brazil',2015,50000);
SELECT SUM(amount) FROM finance_investments WHERE country IN ('India', 'Brazil') AND year BETWEEN 2015 AND 2020;
How many artists are associated with each platform?
CREATE TABLE Artists (artist_id INT,artist_name VARCHAR(255)); INSERT INTO Artists (artist_id,artist_name) VALUES (1,'Spotify'),(2,'Apple Music'),(3,'Tidal'); CREATE TABLE ArtistPlatforms (artist_id INT,platform_id INT); INSERT INTO ArtistPlatforms (artist_id,platform_id) VALUES (1,1),(1,2),(1,3),(2,1),(2,2),(3,3); CREATE TABLE Platforms (platform_id INT,platform_name VARCHAR(255)); INSERT INTO Platforms (platform_id,platform_name) VALUES (1,'Streaming'),(2,'Downloads'),(3,'Vinyl');
SELECT p.platform_name, COUNT(DISTINCT a.artist_id) AS artist_count FROM ArtistPlatforms ap JOIN Artists a ON ap.artist_id = a.artist_id JOIN Platforms p ON ap.platform_id = p.platform_id GROUP BY p.platform_name;
How many Shariah-compliant loans were issued by each branch in the last quarter?
CREATE TABLE branches (branch_id INT,name VARCHAR(255),address VARCHAR(255)); CREATE TABLE loans (loan_id INT,branch_id INT,date DATE,amount DECIMAL(10,2),shariah_compliant BOOLEAN);
SELECT branches.name, COUNT(loans.loan_id) as count FROM branches INNER JOIN loans ON branches.branch_id = loans.branch_id WHERE loans.date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND CURRENT_DATE AND loans.shariah_compliant = TRUE GROUP BY branches.name;
What's the average age of teachers in the teacher_development table?
CREATE TABLE teacher_development (id INT,name VARCHAR(50),age INT,subject VARCHAR(50));
SELECT AVG(age) FROM teacher_development WHERE subject = 'Mathematics';
What is the average donation amount in the 'donations' table?
CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL(10,2));
SELECT AVG(amount) FROM donations;
What is the maximum energy savings achieved by green buildings in Canada in 2016?
CREATE TABLE green_buildings (id INT,building_type VARCHAR(50),energy_savings FLOAT,year INT); INSERT INTO green_buildings (id,building_type,energy_savings,year) VALUES (1,'Residential',15.2,2014),(2,'Commercial',22.8,2016),(3,'Industrial',31.5,2018),(4,'Public',18.9,2017);
SELECT MAX(energy_savings) FROM green_buildings WHERE year = 2016 AND building_type IN ('Residential', 'Commercial');
What is the most popular genre among users in the United States?
CREATE TABLE users (id INT,name TEXT,country TEXT);CREATE TABLE user_genre_preferences (user_id INT,genre_id INT);CREATE TABLE genres (id INT,name TEXT); INSERT INTO users (id,name,country) VALUES (1,'User A','USA'),(2,'User B','Canada'); INSERT INTO user_genre_preferences (user_id,genre_id) VALUES (1,1),(1,2),(2,3); INSERT INTO genres (id,name) VALUES (1,'Rock'),(2,'Pop'),(3,'Jazz');
SELECT genres.name, COUNT(user_genre_preferences.user_id) AS popularity FROM genres JOIN user_genre_preferences ON genres.id = user_genre_preferences.genre_id JOIN users ON user_genre_preferences.user_id = users.id WHERE users.country = 'USA' GROUP BY genres.name ORDER BY popularity DESC LIMIT 1;
Update the 'DesignStandards' table to change the standard for retaining wall height from 4 to 5 feet for records where the structure type is 'Concrete'.
CREATE TABLE DesignStandards (ID INT,StructureType VARCHAR(20),Height FLOAT,Width FLOAT); INSERT INTO DesignStandards (ID,StructureType,Height,Width) VALUES (1,'Retaining Wall',4.0,3.0); INSERT INTO DesignStandards (ID,StructureType,Height,Width) VALUES (2,'Concrete Barrier',2.5,1.5);
UPDATE DesignStandards SET Height = 5.0 WHERE StructureType = 'Retaining Wall' AND Height = 4.0;
What is the total number of artworks in the 'Artworks' table created by artists from Asia?
CREATE TABLE Artworks (id INT,title VARCHAR(50),artist VARCHAR(50),date DATE,type VARCHAR(50)); INSERT INTO Artworks (id,title,artist,date,type) VALUES (1,'Painting 1','Li','2020-01-01','Painting');
SELECT COUNT(*) FROM Artworks WHERE artist LIKE 'Li%';
Find the average age of players who prefer RPG games
CREATE TABLE Players (PlayerID INT,Age INT,GamePreference VARCHAR(20)); INSERT INTO Players (PlayerID,Age,GamePreference) VALUES (1,28,'RPG'),(2,22,'FPS'),(3,35,'Strategy');
SELECT AVG(Age) FROM Players WHERE GamePreference = 'RPG';
What is the total transaction amount for each customer in the Southeast region in the last quarter of 2021?
CREATE TABLE transactions (transaction_id INT,customer_id INT,transaction_date DATE,transaction_amount DECIMAL(10,2)); INSERT INTO transactions (transaction_id,customer_id,transaction_date,transaction_amount) VALUES (17,2,'2021-10-05',350.00),(18,1,'2021-10-10',500.00),(19,3,'2021-11-15',600.00),(20,4,'2021-11-30',800.00),(21,3,'2021-12-20',900.00); CREATE TABLE customers (customer_id INT,name VARCHAR(100),region VARCHAR(50)); INSERT INTO customers (customer_id,name,region) VALUES (1,'John Doe','Southeast'),(2,'Jane Smith','Northeast'),(3,'Alice Johnson','Midwest'),(4,'Bob Brown','West');
SELECT customers.name, SUM(transactions.transaction_amount) FROM transactions INNER JOIN customers ON transactions.customer_id = customers.customer_id WHERE customers.region = 'Southeast' AND transactions.transaction_date BETWEEN '2021-10-01' AND '2021-12-31' GROUP BY customers.name;
Insert new records of athletes who joined in 2022
CREATE TABLE athletes (athlete_id INT,name VARCHAR(50),sport VARCHAR(50),join_year INT); INSERT INTO athletes (athlete_id,name,sport,join_year) VALUES (1,'Jane Doe','Basketball',2021),(2,'John Smith','Soccer',2019);
INSERT INTO athletes (athlete_id, name, sport, join_year) SELECT 3, 'Sara Johnson', 'Golf', 2022 WHERE NOT EXISTS (SELECT 1 FROM athletes WHERE name = 'Sara Johnson' AND join_year = 2022); INSERT INTO athletes (athlete_id, name, sport, join_year) SELECT 4, 'Mike Brown', 'Tennis', 2022 WHERE NOT EXISTS (SELECT 1 FROM athletes WHERE name = 'Mike Brown' AND join_year = 2022);
What is the total attendance for cultural events held in Tokyo?
CREATE TABLE Events_Locations (event_id INT,event_name VARCHAR(255),city VARCHAR(255),attendance INT); INSERT INTO Events_Locations (event_id,event_name,city,attendance) VALUES (1,'Art Exhibition','Paris',500),(2,'Music Festival','London',800),(6,'Theatre Performance','Tokyo',1000);
SELECT SUM(attendance) FROM Events_Locations WHERE city = 'Tokyo';
Find the number of unique content types in 'content_trends' table for the last month?
CREATE TABLE content_trends (content_id INT,user_country VARCHAR(50),content_type VARCHAR(50),user_engagement INT);
SELECT content_type, COUNT(DISTINCT content_id) FROM content_trends WHERE post_date >= CURDATE() - INTERVAL 1 MONTH GROUP BY content_type;
List the number of employees and their roles in the engineering department
CREATE TABLE employee (id INT,name VARCHAR(255),department VARCHAR(255),role VARCHAR(255)); INSERT INTO employee (id,name,department,role) VALUES (1,'John Doe','Engineering','Manager'),(2,'Jane Smith','Engineering','Engineer'),(3,'Mike Johnson','Engineering','Technician');
SELECT e.department, e.role, COUNT(e.id) as num_employees FROM employee e WHERE e.department = 'Engineering' GROUP BY e.department, e.role;
What is the average age of patients who received a flu shot in the state of California in 2020?
CREATE TABLE patients (patient_id INT,age INT,gender TEXT,state TEXT,date DATE); INSERT INTO patients (patient_id,age,gender,state,date) VALUES (1,35,'Female','California','2020-01-01');
SELECT AVG(age) FROM patients WHERE state = 'California' AND date LIKE '2020-%' AND procedure = 'Flu shot';
Which cities have inclusive housing policies and the highest percentage of green spaces?
CREATE TABLE City (id INT PRIMARY KEY,name VARCHAR(50),population INT,green_space_percentage DECIMAL(5,2),inclusive_housing BOOLEAN); CREATE VIEW Inclusive_Cities AS SELECT * FROM City WHERE inclusive_housing = true;
SELECT City.name, City.green_space_percentage FROM City INNER JOIN Inclusive_Cities ON City.id = Inclusive_Cities.id WHERE City.green_space_percentage = (SELECT MAX(green_space_percentage) FROM City WHERE inclusive_housing = true);
What is the total number of employees working in mining operations in the Oceanian region?
CREATE TABLE Employees (EmployeeID INT,Name VARCHAR(50),OperationID INT,Department VARCHAR(50)); INSERT INTO Employees (EmployeeID,Name,OperationID,Department) VALUES (6,'Brian Johnson',6,'Mining'); INSERT INTO Employees (EmployeeID,Name,OperationID,Department) VALUES (7,'Sarah Lee',7,'Mining');
SELECT COUNT(DISTINCT Employees.EmployeeID) FROM Employees INNER JOIN MiningOperations ON Employees.OperationID = MiningOperations.OperationID WHERE Employees.Department = 'Mining' AND MiningOperations.Country IN (SELECT Country FROM Countries WHERE Region = 'Oceania');
What is the average time to resolve a cybersecurity incident for each military branch in 2020?
CREATE TABLE CybersecurityIncidents (id INT,branch VARCHAR(255),year INT,incidents INT,resolution_time INT); INSERT INTO CybersecurityIncidents (id,branch,year,incidents,resolution_time) VALUES (1,'Air Force',2019,20,100),(2,'Navy',2018,30,150),(3,'Army',2020,40,200),(4,'Air Force',2020,50,120),(5,'Navy',2020,60,180),(6,'Army',2019,70,250);
SELECT branch, AVG(resolution_time) FROM CybersecurityIncidents WHERE year = 2020 GROUP BY branch;
What is the percentage of waste recycled in the circular economy initiative in 2021?
CREATE TABLE circular_economy(year INT,recycled_waste FLOAT,total_waste FLOAT); INSERT INTO circular_economy(year,recycled_waste,total_waste) VALUES(2021,1234.56,2345.67);
SELECT (recycled_waste / total_waste) * 100 FROM circular_economy WHERE year = 2021;
What is the total number of vehicles in the 'fleet' table that are older than 5 years?
CREATE TABLE fleet (id INT,type TEXT,model TEXT,year INT); INSERT INTO fleet (id,type,model,year) VALUES (1,'bus','Artic',2015),(2,'bus','Midi',2018),(3,'tram','Cantrib',2010),(4,'train','EMU',2000);
SELECT COUNT(*) as count FROM fleet WHERE year < 2016;
Compare the energy storage capacity of Batteries and Pumped Hydro
CREATE TABLE energy_storage_capacity (tech VARCHAR(50),capacity FLOAT); INSERT INTO energy_storage_capacity (tech,capacity) VALUES ('Batteries',2345.6),('Flywheels',1234.5),('Pumped Hydro',5678.9),('Batteries',3456.7),('Pumped Hydro',7890.1);
SELECT tech, capacity FROM energy_storage_capacity WHERE tech IN ('Batteries', 'Pumped Hydro');
What is the total number of renewable energy projects in Brazil?
CREATE TABLE renewable_projects (id INT,project_name TEXT,location TEXT);
SELECT COUNT(*) FROM renewable_projects WHERE renewable_projects.location = 'Brazil';
What is the total mass of space debris in descending order of mass in the space_debris table?
CREATE TABLE space_debris (debris_type VARCHAR(30),mass FLOAT,debris_id INT); INSERT INTO space_debris VALUES ('Fuel Tank',1500.20,1),('Upper Stage',3000.50,2),('Payload Adapter',700.30,3),('Instrument',100.10,4);
SELECT debris_type, mass, ROW_NUMBER() OVER (ORDER BY mass DESC) AS rank FROM space_debris;
What is the number of autonomous driving research papers published in the research_papers table for each month in the year 2021?
CREATE TABLE research_papers (id INT,title VARCHAR(100),publication_date DATE); INSERT INTO research_papers (id,title,publication_date) VALUES (1,'Deep Learning for Autonomous Driving','2021-01-01'),(2,'Motion Planning for Autonomous Vehicles','2020-12-01'),(3,'Simulation for Autonomous Driving Testing','2022-03-01');
SELECT EXTRACT(MONTH FROM publication_date) AS month, COUNT(*) FROM research_papers WHERE EXTRACT(YEAR FROM publication_date) = 2021 GROUP BY month;
What is the difference between the maximum and minimum transaction amounts for user ID 10?
CREATE TABLE transactions (user_id INT,transaction_amount DECIMAL(10,2),transaction_date DATE,country VARCHAR(255)); INSERT INTO transactions (user_id,transaction_amount,transaction_date,country) VALUES (10,50.00,'2022-01-01','US'),(10,100.00,'2022-01-02','US');
SELECT user_id, MAX(transaction_amount) - MIN(transaction_amount) as transaction_amount_difference FROM transactions WHERE user_id = 10 GROUP BY user_id;
Find the total CO2 emissions for each mine and the percentage of the total.
CREATE TABLE emissions (mine_id INT,co2_emissions INT); INSERT INTO emissions (mine_id,co2_emissions) VALUES (1,5000); INSERT INTO emissions (mine_id,co2_emissions) VALUES (2,7000);
SELECT mine_id, co2_emissions, ROUND(100.0 * co2_emissions / (SELECT SUM(co2_emissions) FROM emissions), 2) AS percentage FROM emissions;
Find the total revenue for each movie genre in a year.
CREATE TABLE movie_revenue (movie VARCHAR(255),genre VARCHAR(255),release_year INT,revenue INT); INSERT INTO movie_revenue (movie,genre,release_year,revenue) VALUES ('Movie1','Action',2018,50000000),('Movie2','Comedy',2019,70000000),('Movie3','Drama',2020,60000000),('Movie4','Action',2020,80000000);
SELECT genre, SUM(revenue) as total_revenue FROM movie_revenue GROUP BY genre ORDER BY total_revenue DESC;
Delete the military technology record 'Balloon Reconnaissance System' from the 'military_technologies' table
CREATE TABLE military_technologies (technology_code VARCHAR(10),technology_name VARCHAR(20),manufacturer VARCHAR(20)); INSERT INTO military_technologies (technology_code,technology_name,manufacturer) VALUES ('MT001','Balloon Reconnaissance System','SkyView Inc');
DELETE FROM military_technologies WHERE technology_name = 'Balloon Reconnaissance System';
Which vessels have a compliance score below 70 and have traveled to the Arctic Ocean?
CREATE TABLE vessels (id INT,name TEXT,type TEXT,compliance_score INT);CREATE TABLE routes (id INT,vessel_id INT,destination TEXT,date DATE); INSERT INTO vessels (id,name,type,compliance_score) VALUES (1,'VesselF','Cargo',65); INSERT INTO routes (id,vessel_id,destination,date) VALUES (1,1,'Arctic','2022-02-15');
SELECT v.name FROM vessels v JOIN routes r ON v.id = r.vessel_id WHERE v.compliance_score < 70 AND r.destination = 'Arctic';
What is the average bioprocess engineering cost for projects in Germany?
CREATE TABLE costs (id INT,project VARCHAR(50),country VARCHAR(50),cost FLOAT); INSERT INTO costs (id,project,country,cost) VALUES (1,'Bioprocess1','Germany',100000); INSERT INTO costs (id,project,country,cost) VALUES (2,'Bioprocess2','Germany',150000); INSERT INTO costs (id,project,country,cost) VALUES (3,'Bioprocess3','France',120000);
SELECT AVG(cost) FROM costs WHERE country = 'Germany';
How many families were assisted by each organization?
CREATE TABLE assistance (organization TEXT,families_assisted INTEGER); INSERT INTO assistance (organization,families_assisted) VALUES ('Red Cross',200),('Doctors Without Borders',150),('UNICEF',250);
SELECT a.organization, SUM(a.families_assisted) FROM assistance a GROUP BY a.organization;
What is the distribution of funding sources by event category?
CREATE TABLE funding (id INT,program_id INT,source VARCHAR(255),amount DECIMAL(10,2),date DATE); CREATE TABLE events (id INT,name VARCHAR(255),category VARCHAR(255),date DATE);
SELECT e.category, f.source, SUM(f.amount) FROM funding f INNER JOIN (programs p INNER JOIN events e ON p.id = e.program_id) ON f.program_id = p.id GROUP BY e.category, f.source;
What is the average number of followers for users who have interacted with posts in the 'travel' category on LinkedIn in the last month?
CREATE TABLE interaction_data (user_id INT,post_id INT,platform VARCHAR(20),date DATE); INSERT INTO interaction_data (user_id,post_id,platform,date) VALUES (1,1,'LinkedIn','2022-02-01'),(2,2,'LinkedIn','2022-02-02'),(3,1,'LinkedIn','2022-02-03'); CREATE TABLE user_data (user_id INT,followers INT,category VARCHAR(50),platform VARCHAR(20)); INSERT INTO user_data (user_id,followers,category,platform) VALUES (1,1000,'travel','LinkedIn'),(2,2000,'technology','LinkedIn'),(3,500,'travel','LinkedIn');
SELECT AVG(followers) FROM user_data INNER JOIN interaction_data ON user_data.user_id = interaction_data.user_id WHERE interaction_data.category = 'travel' AND interaction_data.platform = 'LinkedIn' AND interaction_data.date >= DATEADD(month, -1, GETDATE());
Show the number of virtual tours for each hotel_id in the 'virtual_tour_stats' table
CREATE TABLE virtual_tour_stats (hotel_id INT,view_date DATE,view_duration INT);
SELECT hotel_id, COUNT(*) FROM virtual_tour_stats GROUP BY hotel_id;
What is the maximum number of seats for Airbus aircraft?
CREATE TABLE Seats (aircraft VARCHAR(50),seats INT); INSERT INTO Seats (aircraft,seats) VALUES ('Airbus A380',853),('Airbus A350',550);
SELECT aircraft, MAX(seats) FROM Seats WHERE aircraft LIKE 'Airbus%';
What are the names and types of vessels that have docked in the Port of Oakland in the last month?
CREATE TABLE Port (port_name VARCHAR(50),dock_count INT); INSERT INTO Port VALUES ('Port of Oakland',12); CREATE TABLE Vessels (vessel_name VARCHAR(50),vessel_type VARCHAR(50),last_dock_date DATE); INSERT INTO Vessels VALUES ('Vessel A','Container','2022-03-05'),('Vessel B','Tanker','2022-03-10'),('Vessel C','Container','2022-03-15'),('Vessel D','Bulk Carrier','2022-03-20'),('Vessel E','Container','2022-03-25');
SELECT V.vessel_name, V.vessel_type FROM Vessels V INNER JOIN Port P ON 1=1 WHERE V.last_dock_date >= DATEADD(MONTH, -1, GETDATE());
What is the number of mobile customers who have not made any voice calls in the last month in the 'tundra' region?
CREATE TABLE subscribers (id INT,type VARCHAR(10),region VARCHAR(10)); INSERT INTO subscribers (id,type,region) VALUES (1,'prepaid','tundra'),(2,'postpaid','tundra'),(3,'prepaid','tundra'); CREATE TABLE calls (subscriber_id INT,call_date DATE); INSERT INTO calls (subscriber_id,call_date) VALUES (1,'2022-01-15'),(2,'2022-01-10'),(3,NULL);
SELECT COUNT(*) FROM subscribers LEFT JOIN calls ON subscribers.id = calls.subscriber_id WHERE subscribers.region = 'tundra' AND calls.call_date IS NULL;
Delete all records related to the 'China' country in the 'flight_safety_records' table.
CREATE TABLE flight_safety_records (airline VARCHAR(50),country VARCHAR(50),incidents INT); INSERT INTO flight_safety_records (airline,country,incidents) VALUES ('Air China','China',5),('China Southern','China',3),('China Eastern','China',4),('United Airlines','USA',2),('Delta Airlines','USA',1);
DELETE FROM flight_safety_records WHERE country = 'China';
What is the total production of soybean and corn in the United States and Canada in 2020?
CREATE TABLE us_crops (name VARCHAR(255),year INT,production INT); INSERT INTO us_crops (name,year,production) VALUES ('soybean',2020,11297460),('corn',2020,360749400); CREATE TABLE ca_crops (name VARCHAR(255),year INT,production INT); INSERT INTO ca_crops (name,year,production) VALUES ('soybean',2020,123000),('corn',2020,14200000);
SELECT 'United States' AS country, SUM(production) AS soybean_production FROM us_crops WHERE name = 'soybean' AND year = 2020 UNION ALL SELECT 'United States' AS country, SUM(production) AS corn_production FROM us_crops WHERE name = 'corn' AND year = 2020 UNION ALL SELECT 'Canada' AS country, SUM(production) AS soybean_production FROM ca_crops WHERE name = 'soybean' AND year = 2020 UNION ALL SELECT 'Canada' AS country, SUM(production) AS corn_production FROM ca_crops WHERE name = 'corn' AND year = 2020;
How many volunteers are needed for each event?
CREATE TABLE Event_Volunteers (id INT,event_id INT,num_volunteers INT);
SELECT Event.name, Event_Volunteers.num_volunteers FROM Event JOIN Event_Volunteers ON Event.id = Event_Volunteers.event_id;
What is the average age of policyholders who live in 'CA' and have a car make of 'Toyota'?
CREATE TABLE Policyholder (PolicyholderID INT,Age INT,Gender VARCHAR(10),CarMake VARCHAR(20),State VARCHAR(20)); INSERT INTO Policyholder (PolicyholderID,Age,Gender,CarMake,State) VALUES (1,35,'Female','Toyota','CA'); INSERT INTO Policyholder (PolicyholderID,Age,Gender,CarMake,State) VALUES (2,42,'Male','Honda','CA');
SELECT AVG(Age) FROM Policyholder WHERE CarMake = 'Toyota' AND State = 'CA';
Create a view named "inclusive_properties" containing all properties located in historically underrepresented communities
CREATE TABLE properties (property_id INT,property_name VARCHAR(255),location VARCHAR(255),inclusive_community BOOLEAN); INSERT INTO properties (property_id,property_name,location,inclusive_community) VALUES (1,'Harmony House','Bronx',true),(2,'Sunrise Villas','Seattle',false),(3,'Casa Unida','Los Angeles',true);
CREATE VIEW inclusive_properties AS SELECT * FROM properties WHERE inclusive_community = true;
What is the average budget of cybersecurity exercises in the last 6 months?
CREATE TABLE CybersecurityExercises (Id INT,Name VARCHAR(50),Budget FLOAT,Date DATE); INSERT INTO CybersecurityExercises (Id,Name,Budget,Date) VALUES (1,'Exercise1',5000,'2021-01-01'); INSERT INTO CybersecurityExercises (Id,Name,Budget,Date) VALUES (2,'Exercise2',7000,'2021-02-15');
SELECT AVG(Budget) FROM CybersecurityExercises WHERE Date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)
Insert a new record into the contract_negotiations table for a new contract with country A for 5 million dollars
CREATE TABLE contract_negotiations (country VARCHAR(255),contract_value INT,negotiation_date DATE); INSERT INTO contract_negotiations (country,contract_value,negotiation_date) VALUES ('Country B',3000000,'2021-01-01'),('Country C',4000000,'2021-02-01');
INSERT INTO contract_negotiations (country, contract_value, negotiation_date) VALUES ('Country A', 5000000, CURDATE());
What is the percentage of cases won by the prosecution?
CREATE TABLE cases (id INT,case_type VARCHAR(10),case_outcome VARCHAR(10));
SELECT (COUNT(*) FILTER (WHERE case_type = 'prosecution' AND case_outcome = 'won')) * 100.0 / COUNT(*) AS percentage_of_won_cases FROM cases WHERE case_type = 'prosecution';
Insert a new row with the following data: make - 'Volvo', model - 'XC90', autonomy_level - 2 into the autonomous_driving_research table.
CREATE TABLE autonomous_driving_research (id INT,make VARCHAR(50),model VARCHAR(50),autonomy_level INT);
INSERT INTO autonomous_driving_research (make, model, autonomy_level) VALUES ('Volvo', 'XC90', 2);
Add a new entry to the 'players' table with ID 3, name 'Alex'
CREATE TABLE players (player_id INT,name VARCHAR(255));
INSERT INTO players (player_id, name) VALUES (3, 'Alex');
List all rural infrastructure projects, along with the number of jobs created, in descending order by the number of jobs created.
CREATE TABLE rural_infrastructure (project_id INT,project_name VARCHAR(255),jobs_created INT);
select project_name, jobs_created from rural_infrastructure order by jobs_created desc;
Insert a new cultivar 'Blue Dream' into the 'CannabisCultivars' table with strain type 'Hybrid' and origin 'California'.
CREATE TABLE CannabisCultivars (id INT,name VARCHAR(255),type VARCHAR(255),origin VARCHAR(255));
INSERT INTO CannabisCultivars (name, type, origin) VALUES ('Blue Dream', 'Hybrid', 'California');
What is the average orbit height for each orbit type, considering only geosynchronous orbits, based on the SatelliteOrbits table?
CREATE TABLE SatelliteOrbits (SatelliteID INT,OrbitType VARCHAR(50),OrbitHeight INT); INSERT INTO SatelliteOrbits (SatelliteID,OrbitType,OrbitHeight) VALUES (101,'LEO',500),(201,'MEO',8000),(301,'GEO',36000),(401,'LEO',600),(501,'MEO',10000),(601,'GEO',35000),(701,'GEO',37000);
SELECT OrbitType, AVG(OrbitHeight) AS AvgOrbitHeight FROM SatelliteOrbits WHERE OrbitType = 'GEO' GROUP BY OrbitType;
Find the number of users who played game 'A' on any date in January 2021
CREATE TABLE game_sessions (user_id INT,game_name VARCHAR(10),login_date DATE); INSERT INTO game_sessions (user_id,game_name,login_date) VALUES (1,'A','2021-01-01'),(2,'B','2021-01-02'),(3,'B','2021-01-03'),(4,'C','2021-01-04'),(5,'A','2021-01-05');
SELECT COUNT(DISTINCT user_id) FROM game_sessions WHERE game_name = 'A' AND login_date BETWEEN '2021-01-01' AND '2021-01-31';
What is the maximum funding amount for startups founded by a team of at least two people in the renewable energy industry?
CREATE TABLE startup (id INT,name TEXT,industry TEXT,founder_count INT,founder_gender TEXT); INSERT INTO startup (id,name,industry,founder_count,founder_gender) VALUES (1,'RenewStartup1','Renewable Energy',2,'Male'); INSERT INTO startup (id,name,industry,founder_count,founder_gender) VALUES (2,'RenewStartup2','Renewable Energy',1,'Female');
SELECT MAX(funding_amount) FROM investment_rounds ir JOIN startup s ON ir.startup_id = s.id WHERE s.industry = 'Renewable Energy' AND s.founder_count >= 2;
What is the average ocean acidification level in the Indian and Atlantic Oceans?
CREATE TABLE ocean_acidification_multi (location VARCHAR(255),level FLOAT); INSERT INTO ocean_acidification_multi (location,level) VALUES ('Indian Ocean',8.05),('Atlantic Ocean',8.1);
SELECT AVG(level) FROM ocean_acidification_multi WHERE location IN ('Indian Ocean', 'Atlantic Ocean');
How many customers are there in each age group (young adults, middle-aged, seniors)?
CREATE TABLE customers (id INT,name VARCHAR(255),age INT,account_balance DECIMAL(10,2)); INSERT INTO customers (id,name,age,account_balance) VALUES (1,'John Doe',23,5000.00),(2,'Jane Smith',45,7000.00),(3,'Alice Johnson',63,9000.00);
SELECT CASE WHEN age BETWEEN 18 AND 35 THEN 'Young adults' WHEN age BETWEEN 36 AND 60 THEN 'Middle-aged' ELSE 'Seniors' END AS age_group, COUNT(*) FROM customers GROUP BY age_group;
What is the total number of AI assistant interactions in hotels with over 100 rooms?
CREATE TABLE ai_assistants (id INT PRIMARY KEY,hotel_name VARCHAR(50),assistant_name VARCHAR(50),room_count INT,assistant_interactions INT); INSERT INTO ai_assistants (id,hotel_name,assistant_name,room_count,assistant_interactions) VALUES (1,'Grand Hotel','Smart Concierge',150,120),(2,'Metropolitan Suites','AI Butler',120,90);
SELECT hotel_name, SUM(assistant_interactions) FROM ai_assistants WHERE room_count > 100 GROUP BY hotel_name HAVING COUNT(*) > 1;
What is the maximum, minimum and average fairness score of the models developed by different organizations?
CREATE TABLE fairness_scores (model_id INT,org_id INT,fairness_score FLOAT); INSERT INTO fairness_scores (model_id,org_id,fairness_score) VALUES (101,1,0.75),(102,1,0.85),(103,2,0.95),(104,2,0.9),(105,3,0.8);
SELECT org_id, MAX(fairness_score) as max_score, MIN(fairness_score) as min_score, AVG(fairness_score) as avg_score FROM fairness_scores GROUP BY org_id;
What are the names and types of military technology that were updated in the year 2020 in the TECH_UPDATES table?
CREATE TABLE TECH_UPDATES (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),year INT,country VARCHAR(255));
SELECT name, type FROM TECH_UPDATES WHERE year = 2020 AND country = (SELECT country FROM TECH_UPDATES WHERE name = (SELECT MAX(name) FROM TECH_UPDATES WHERE year = 2020) AND type = (SELECT MAX(type) FROM TECH_UPDATES WHERE year = 2020) LIMIT 1);
What are the sustainable textile sourcing countries with a sustainability rating greater than 85?
CREATE TABLE sustainable_sourcing (id INT,country VARCHAR(20),sustainability_rating INT); INSERT INTO sustainable_sourcing (id,country,sustainability_rating) VALUES (1,'Nepal',90); INSERT INTO sustainable_sourcing (id,country,sustainability_rating) VALUES (2,'Ghana',86);
SELECT country FROM sustainable_sourcing WHERE sustainability_rating > 85;
What is the total cost of all public awareness campaigns in 2022?
CREATE TABLE campaigns (campaign_id INT,year INT,cost DECIMAL(10,2)); INSERT INTO campaigns (campaign_id,year,cost) VALUES (1,2022,50000.00),(2,2021,40000.00),(3,2022,60000.00);
SELECT SUM(cost) FROM campaigns WHERE year = 2022;
How many employees are there in each department of the 'DisabilityServices' organization?
CREATE TABLE Employees (ID INT,Name VARCHAR(255),Department VARCHAR(255)); INSERT INTO Employees (ID,Name,Department) VALUES (1,'John Doe','HR'),(2,'Jane Smith','IT'),(3,'Alice Johnson','Finance');
SELECT Department, COUNT(*) as NumberOfEmployees FROM Employees GROUP BY Department;
What is the minimum altitude for satellites in the Iridium constellation?
CREATE TABLE iridium_satellites (satellite_id INT,name VARCHAR(100),type VARCHAR(50),altitude INT);
SELECT MIN(altitude) FROM iridium_satellites WHERE type = 'Satellite';
List the top 3 biosensor technologies by R&D investment in descending order.
CREATE SCHEMA if not exists biosensors;CREATE TABLE if not exists biosensors.technologies (id INT,name VARCHAR(50),rd_investment DECIMAL(10,2)); INSERT INTO biosensors.technologies (id,name,rd_investment) VALUES (1,'BioSensor1',3000000.00),(2,'BioSensor2',2500000.00),(3,'BioSensor3',2000000.00),(4,'BioSensor4',1500000.00);
SELECT * FROM biosensors.technologies ORDER BY rd_investment DESC LIMIT 3;
What is the total number of renewable energy projects in the renewable_projects table, excluding solar projects?
CREATE TABLE renewable_projects (id INT,name VARCHAR(50),type VARCHAR(50),country VARCHAR(50)); INSERT INTO renewable_projects (id,name,type,country) VALUES (1,'Solar Project 1','Solar','Country A'); INSERT INTO renewable_projects (id,name,type,country) VALUES (2,'Wind Project 1','Wind','Country A'); INSERT INTO renewable_projects (id,name,type,country) VALUES (3,'Hydro Project 1','Hydro','Country A');
SELECT COUNT(*) FROM renewable_projects WHERE type != 'Solar';
How many species are there in the 'North Pacific' region?
ocean_species;
SELECT COUNT(*) FROM ocean_species WHERE region = 'North Pacific';
What is the average session length for each game, sorted by genre?
CREATE TABLE game_sessions(id INT,user_id INT,game_name VARCHAR(50),start_time DATETIME,end_time DATETIME);
SELECT genres.genre, AVG(TIMESTAMPDIFF(SECOND, start_time, end_time)) as avg_session_length FROM game_sessions JOIN (SELECT DISTINCT game_name, genre FROM game_sessions JOIN games ON game_sessions.game_name = games.name) genres ON game_sessions.game_name = genres.game_name GROUP BY genres.genre ORDER BY avg_session_length DESC;
What is the total cargo weight transported by vessels to Port E in Q2 2021?
CREATE TABLE Vessels (id INT,name TEXT,cargo_weight INT,arrive_port TEXT,arrive_date DATE); INSERT INTO Vessels (id,name,cargo_weight,arrive_port,arrive_date) VALUES (1,'Vessel1',1000,'Port E','2021-04-15'); INSERT INTO Vessels (id,name,cargo_weight,arrive_port,arrive_date) VALUES (2,'Vessel2',1500,'Port E','2021-05-01');
SELECT SUM(cargo_weight) FROM Vessels WHERE arrive_port = 'Port E' AND YEAR(arrive_date) = 2021 AND QUARTER(arrive_date) = 2;
List all satellites in the 'satellite_info' table
CREATE TABLE satellite_info (id INT PRIMARY KEY,satellite_name VARCHAR(255),country VARCHAR(255),launch_date DATE,orbit VARCHAR(255));
SELECT * FROM satellite_info;
List all mental health conditions treated in a given facility, ordered by the number of times they were treated.
CREATE TABLE facilities (facility_id INT,condition VARCHAR(50),num_treatments INT); INSERT INTO facilities VALUES (1,'Depression',3),(1,'Anxiety',5),(1,'ADHD',2);
SELECT condition FROM facilities WHERE facility_id = 1 ORDER BY num_treatments DESC;
Display the number of cruelty-free and non-cruelty-free skincare products.
CREATE TABLE Products (id INT,name VARCHAR(50),type VARCHAR(20),cruelty_free BOOLEAN); INSERT INTO Products (id,name,type,cruelty_free) VALUES (1,'Cleanser','Skincare',true),(2,'Toner','Skincare',true),(3,'Moisturizer','Skincare',false);
SELECT CASE WHEN cruelty_free = true THEN 'Cruelty-free' ELSE 'Non-cruelty-free' END as product_type, COUNT(*) as count FROM Products WHERE type = 'Skincare' GROUP BY product_type;
What is the average attendance for cultural events by month and city, pivoted to display the month and city in separate columns?
CREATE TABLE cultural_events (id INT,city VARCHAR(50),event VARCHAR(50),month VARCHAR(50),attendance INT); INSERT INTO cultural_events (id,city,event,month,attendance) VALUES (1,'New York','Art Exhibit','January',2500),(2,'Los Angeles','Theater Performance','February',1800),(3,'Chicago','Music Concert','March',2200);
SELECT city, SUM(CASE month WHEN 'January' THEN attendance ELSE 0 END) as January, SUM(CASE month WHEN 'February' THEN attendance ELSE 0 END) as February, SUM(CASE month WHEN 'March' THEN attendance ELSE 0 END) as March FROM cultural_events GROUP BY city;
Calculate the total travel time (in days) for each vessel that has traveled to the Port of Dar es Salaam in the last 6 months, ordered by the total travel time in descending order.
CREATE TABLE Vessels (vessel_id INT,vessel_name VARCHAR(20)); CREATE TABLE Routes (route_id INT,departure_port VARCHAR(20),arrival_port VARCHAR(20)); CREATE TABLE VesselTravel (vessel_id INT,route INT,departure_date DATE,travel_time INT); INSERT INTO Vessels (vessel_id,vessel_name) VALUES (1,'Vessel1'),(2,'Vessel2'),(3,'Vessel3'),(4,'Vessel4'),(5,'Vessel5'),(6,'Vessel6'),(7,'Vessel7'); INSERT INTO Routes (route_id,departure_port,arrival_port) VALUES (1,'Los Angeles','Tokyo'),(2,'Rotterdam','New York'),(3,'Santos','Hong Kong'),(4,'Mumbai','Shanghai'),(5,'Buenos Aires','Jakarta'),(6,'Dakar','Lagos'),(7,'Valparaiso','Singapore'),(8,'Dar es Salaam','Sydney'); INSERT INTO VesselTravel (vessel_id,route,departure_date,travel_time) VALUES (1,8,'2021-02-01',55),(2,8,'2021-03-01',56),(3,8,'2021-04-01',57),(4,8,'2021-05-01',54),(5,8,'2021-06-01',55),(6,8,'2021-07-01',56);
SELECT v.vessel_id, SUM(travel_time) as total_travel_time FROM Vessels v JOIN VesselTravel vt ON v.vessel_id = vt.vessel_id JOIN Routes r ON vt.route = r.route_id WHERE r.arrival_port = 'Dar es Salaam' AND vt.departure_date >= DATEADD(month, -6, GETDATE()) GROUP BY v.vessel_id ORDER BY total_travel_time DESC;
Identify oyster farms in the South China Sea with water salinity below 30 parts per thousand in December.
CREATE TABLE South_China_Sea (salinity INT,farm_id INT,type VARCHAR(10)); INSERT INTO South_China_Sea (salinity,farm_id,type) VALUES (28,2001,'Oyster'); INSERT INTO South_China_Sea (salinity,farm_id,type) VALUES (35,2002,'Oyster'); CREATE TABLE Oyster_Farms (id INT,name VARCHAR(20)); INSERT INTO Oyster_Farms (id,name) VALUES (2001,'Oyster Farm A'); INSERT INTO Oyster_Farms (id,name) VALUES (2002,'Oyster Farm B');
SELECT Oyster_Farms.name FROM South_China_Sea INNER JOIN Oyster_Farms ON South_China_Sea.farm_id = Oyster_Farms.id WHERE South_China_Sea.salinity < 30 AND South_China_Sea.type = 'Oyster' AND South_China_Sea.month = '2022-12-01';
Calculate the average price and quantity for each product category
CREATE TABLE sales_data (sale_id INT,product_id INT,sale_date DATE,price DECIMAL(5,2),quantity INT); INSERT INTO sales_data (sale_id,product_id,sale_date,price,quantity) VALUES (1,1,'2021-01-01',12.50,10),(2,2,'2021-01-02',13.00,15),(3,3,'2021-01-03',12.75,12),(4,4,'2021-01-04',45.00,5),(5,5,'2021-01-05',35.00,3);
SELECT category, AVG(price) AS avg_price, AVG(quantity) AS avg_quantity FROM sales_data JOIN products ON sales_data.product_id = products.product_id GROUP BY category;
What is the maximum speed of a spacecraft launched by NASA?
CREATE TABLE spacecraft (id INT,name VARCHAR(255),launch_country VARCHAR(255),launch_date DATE,max_speed FLOAT);
SELECT max(max_speed) as max_nasa_speed FROM spacecraft WHERE launch_country = 'United States' AND name LIKE 'NASA%';
What is the maximum network infrastructure investment in France for the last 5 years?
CREATE TABLE france_data (year INT,investment FLOAT); INSERT INTO france_data (year,investment) VALUES (2017,2500000),(2018,3000000),(2019,3500000),(2020,4000000),(2021,4500000);
SELECT MAX(investment) as max_investment FROM france_data WHERE year BETWEEN 2017 AND 2021;
Insert a new fish species into the fish_species table
CREATE TABLE fish_species (id INT PRIMARY KEY,species VARCHAR(255),scientific_name VARCHAR(255));
INSERT INTO fish_species (id, species, scientific_name) VALUES (101, 'Tilapia', 'Tilapia nilotica');
Who is the director of the movie with the highest rating?
CREATE TABLE movies (id INT,title TEXT,rating FLOAT,director TEXT); INSERT INTO movies (id,title,rating,director) VALUES (1,'Movie1',4.5,'Director1'),(2,'Movie2',3.2,'Director2'),(3,'Movie3',4.7,'Director3');
SELECT director FROM movies WHERE rating = (SELECT MAX(rating) FROM movies);
What is the average production budget for horror movies?
CREATE TABLE ProductionCompany (id INT PRIMARY KEY,name VARCHAR(255),genre VARCHAR(100),budget INT);
SELECT AVG(budget) FROM ProductionCompany WHERE genre = 'Horror';
What is the total population of all shark species in the Pacific Ocean, and how many of those species are threatened?
CREATE TABLE shark_species (species_name TEXT,population INTEGER,ocean TEXT,threat_level TEXT);
SELECT SUM(population), COUNT(species_name) FROM shark_species WHERE ocean = 'Pacific Ocean' AND threat_level = 'threatened';
How many trains have been maintained in 'north' region in the last month?
CREATE TABLE train_maintenance (maintenance_id INT,train_id INT,region VARCHAR(10),date DATE); INSERT INTO train_maintenance (maintenance_id,train_id,region,date) VALUES (1,101,'north','2022-01-05'),(2,102,'north','2022-01-10'),(3,103,'south','2022-01-15'),(4,104,'north','2022-02-01');
SELECT COUNT(*) FROM train_maintenance WHERE region = 'north' AND date >= DATEADD(MONTH, -1, GETDATE());
Identify cities with the highest budget allocation for roads and healthcare services.
CREATE TABLE cities (city_id INT,city_name VARCHAR(255),total_budget INT); CREATE TABLE healthcare_services (service_id INT,service_name VARCHAR(255),city_id INT,budget INT); CREATE TABLE roads (road_id INT,road_name VARCHAR(255),city_id INT,budget INT);
SELECT c.city_name, SUM(h.budget) as total_healthcare_budget, SUM(r.budget) as total_roads_budget FROM cities c INNER JOIN healthcare_services h ON c.city_id = h.city_id INNER JOIN roads r ON c.city_id = r.city_id GROUP BY c.city_name ORDER BY total_healthcare_budget + total_roads_budget DESC LIMIT 5;
What is the total number of accommodations provided, by accommodation type, for each country?
CREATE TABLE Accommodations (ID INT PRIMARY KEY,Country VARCHAR(50),AccommodationType VARCHAR(50),Quantity INT); INSERT INTO Accommodations (ID,Country,AccommodationType,Quantity) VALUES (1,'USA','Sign Language Interpretation',300),(2,'Canada','Wheelchair Ramp',250),(3,'Mexico','Assistive Listening Devices',150),(4,'Japan','Mobility Assistance',200),(5,'Germany','Sign Language Interpretation',400),(6,'Egypt','Wheelchair Ramp',100);
SELECT Country, AccommodationType, SUM(Quantity) as Total FROM Accommodations GROUP BY Country, AccommodationType;
What is the minimum research grant amount awarded to a professor in the Chemistry department who has published at least one paper?
CREATE TABLE department (name VARCHAR(255),id INT);CREATE TABLE professor (name VARCHAR(255),department_id INT,grant_amount DECIMAL(10,2),publication_year INT);
SELECT MIN(grant_amount) FROM professor WHERE department_id IN (SELECT id FROM department WHERE name = 'Chemistry') AND publication_year IS NOT NULL;
What are the names and safety ratings for suppliers with a supplier ID between 300 and 500?
CREATE TABLE Suppliers (supplier_id INTEGER,supplier_name TEXT,safety_rating INTEGER); INSERT INTO Suppliers (supplier_id,supplier_name,safety_rating) VALUES (123,'Acme Corp',90),(234,'Beta Inc',85),(345,'Gamma Ltd',95),(456,'Delta Co',80),(567,'Epsilon plc',92);
SELECT s.supplier_name, s.safety_rating FROM Suppliers s WHERE s.supplier_id BETWEEN 300 AND 500;
What is the average number of passengers per bus trip, partitioned by month and ranked by the highest average?
CREATE TABLE bus_trips (id INT,trip_date DATE,passengers INT); INSERT INTO bus_trips (id,trip_date,passengers) VALUES (1,'2022-01-01',50),(2,'2022-01-01',60),(3,'2022-02-01',40);
SELECT AVG(passengers) OVER (PARTITION BY DATEPART(mm, trip_date) ORDER BY AVG(passengers) DESC) as avg_passengers, trip_date FROM bus_trips WHERE trip_date >= DATEADD(year, -1, GETDATE());