instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total property size in the housing_affordability table for each owner?
CREATE TABLE housing_affordability (property_id INT,size FLOAT,owner_id INT); INSERT INTO housing_affordability (property_id,size,owner_id) VALUES (1,800,1),(2,900,1),(3,1000,2);
SELECT owner_id, SUM(size) FROM housing_affordability GROUP BY owner_id;
What is the list of unique students who have taken mental health surveys in open pedagogy courses but have not completed any professional development courses?
CREATE TABLE mental_health_surveys (student_id INT,course_type VARCHAR(50),survey_date DATE); INSERT INTO mental_health_surveys VALUES (1,'open_pedagogy','2021-06-01'),(2,'open_pedagogy','2021-07-01'),(3,'open_pedagogy','2021-08-01'); CREATE TABLE professional_development (student_id INT,course_completed VARCHAR(50)); ...
SELECT DISTINCT student_id FROM mental_health_surveys WHERE student_id NOT IN (SELECT student_id FROM professional_development);
What is the maximum heart rate recorded for members from Canada?
CREATE TABLE Members (MemberID INT,Country VARCHAR(20),HeartRate FLOAT); INSERT INTO Members (MemberID,Country,HeartRate) VALUES (1,'Canada',185.2),(2,'USA',200.1),(3,'Canada',190.0);
SELECT MAX(HeartRate) FROM Members WHERE Country = 'Canada';
What's the average age of players who prefer VR games, and how many of them are there?
CREATE TABLE players (id INT,name VARCHAR(50),age INT,game_preference VARCHAR(20)); INSERT INTO players (id,name,age,game_preference) VALUES (1,'John Doe',25,'VR'); INSERT INTO players (id,name,age,game_preference) VALUES (2,'Jane Smith',30,'Non-VR');
SELECT AVG(age), COUNT(*) FROM players WHERE game_preference = 'VR';
What is the total amount donated by each donor?
CREATE TABLE Donors (DonorID INT,DonorName TEXT); INSERT INTO Donors (DonorID,DonorName) VALUES (1,'John Doe'),(2,'Jane Smith');
SELECT Donors.DonorID, Donors.DonorName, SUM(Donations.DonationAmount) AS TotalDonated FROM Donors JOIN Donations ON Donors.DonorID = Donations.DonorID GROUP BY Donors.DonorID, Donors.DonorName;
What is the average depth of all marine species in the Mediterranean Sea, grouped by species name?
CREATE TABLE marine_species_avg_depths_mediterranean (name VARCHAR(255),basin VARCHAR(255),depth FLOAT); INSERT INTO marine_species_avg_depths_mediterranean (name,basin,depth) VALUES ('Species9','Mediterranean',234.56),('Species10','Pacific',567.89);
SELECT name, AVG(depth) as avg_depth FROM marine_species_avg_depths_mediterranean WHERE basin = 'Mediterranean' GROUP BY name;
What is the average number of court_hearings for cases in the 'criminal_court' table?
CREATE TABLE criminal_court (id INT,case_id INT,court_hearings INT,case_status TEXT);
SELECT AVG(court_hearings) FROM criminal_court WHERE case_status = 'closed';
Find AI safety incidents by algorithm in the past 6 months.
CREATE TABLE ai_safety_incidents (incident_date DATE,ai_algorithm VARCHAR(255),incidents INT); INSERT INTO ai_safety_incidents (incident_date,ai_algorithm,incidents) VALUES ('2022-01-01','Algorithm E',30),('2022-02-15','Algorithm F',45),('2022-03-03','Algorithm E',50);
SELECT ai_algorithm, SUM(incidents) AS total_incidents FROM ai_safety_incidents WHERE incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY ai_algorithm;
How many cultural events were attended by people from Latin America?
CREATE TABLE Events (EventID INT,Name TEXT,Attendance INT);CREATE TABLE Attendees (AttendeeID INT,EventID INT,Country TEXT);
SELECT SUM(Events.Attendance) FROM Events INNER JOIN Attendees ON Events.EventID = Attendees.EventID WHERE Attendees.Country = 'Latin America';
List all restorative justice programs in the US and Canada, along with their start dates, if available.
CREATE TABLE justice_programs (id INT,country VARCHAR(255),program VARCHAR(255),start_date DATE); INSERT INTO justice_programs (id,country,program,start_date) VALUES (1,'US','Victim Offender Mediation','1995-01-01'),(2,'Canada','Restorative Circles','2000-01-01'),(3,'US','Peacebuilding Circles',NULL);
SELECT country, program, start_date FROM justice_programs WHERE country IN ('US', 'Canada');
How many articles were written by local authors?
CREATE TABLE articles (id INT,title VARCHAR(50),author_location VARCHAR(20)); INSERT INTO articles (id,title,author_location) VALUES (1,'Article1','local'),(2,'Article2','international');
SELECT COUNT(*) FROM articles WHERE author_location = 'local';
Find the maximum number of posts by a user in the 'social_media' database.
CREATE TABLE users (user_id INT,num_posts INT); INSERT INTO users (user_id,num_posts) VALUES (1,15),(2,8),(3,22),(4,3),(5,25),(6,23),(7,2),(8,30),(9,4),(10,28);
SELECT MAX(num_posts) FROM users;
What is the production cost per garment for the top 3 producing factories in the world?
CREATE TABLE production (id INT,factory VARCHAR(255),country VARCHAR(255),cost DECIMAL(10,2),quantity INT); INSERT INTO production (id,factory,country,cost,quantity) VALUES (1,'Fabric Inc','Spain',150.00,100),(2,'Stitch Time','USA',120.00,200),(3,'Sew Good','India',130.00,150);
SELECT factory, cost/quantity as cost_per_garment FROM (SELECT factory, cost, quantity, ROW_NUMBER() OVER (ORDER BY quantity DESC) as rn FROM production) t WHERE rn <= 3;
Determine the maximum number of likes received by posts published in the 'global_posts' table, authored by users from Africa, in the year 2021.
CREATE TABLE global_posts (title VARCHAR(255),likes INT,publication_year INT,author_continent VARCHAR(50)); INSERT INTO global_posts (title,likes,publication_year,author_continent) VALUES ('Post1',250,2021,'Africa'),('Post2',300,2020,'Africa'),('Post3',150,2022,'Africa'),('Post4',400,2021,'Europe');
SELECT MAX(likes) FROM global_posts WHERE publication_year = 2021 AND author_continent = 'Africa';
Which countries have the highest number of ethical fashion vendors?
CREATE TABLE Countries (Country VARCHAR(50),VendorCount INT); INSERT INTO Countries (Country,VendorCount) VALUES ('France',300),('Italy',250),('Spain',200),('Germany',400),('Sweden',280),('Norway',150),('Denmark',180);
SELECT Country, VendorCount FROM Countries ORDER BY VendorCount DESC FETCH FIRST 3 ROWS ONLY;
List all mental health conditions treated in public awareness campaigns in the Asia-Pacific region.
CREATE TABLE campaigns (campaign_id INT,campaign_name TEXT,region TEXT); CREATE TABLE conditions (condition_id INT,condition_name TEXT,campaign_id INT); INSERT INTO campaigns (campaign_id,campaign_name,region) VALUES (1,'Mental Health Matters','Asia-Pacific'); INSERT INTO conditions (condition_id,condition_name,campaig...
SELECT conditions.condition_name FROM conditions JOIN campaigns ON conditions.campaign_id = campaigns.campaign_id WHERE campaigns.region = 'Asia-Pacific';
What is the average carbon footprint of cotton products sourced from India and Pakistan?
CREATE TABLE Material_Sources (source_id INT,country VARCHAR(50),material VARCHAR(50),carbon_footprint FLOAT);
SELECT AVG(Material_Sources.carbon_footprint) as avg_carbon_footprint FROM Material_Sources WHERE Material_Sources.country IN ('India', 'Pakistan') AND Material_Sources.material = 'cotton';
How many players from Asia are using VR technology?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(50)); INSERT INTO Players (PlayerID,Age,Gender,Country) VALUES (1,25,'Male','Japan'); INSERT INTO Players (PlayerID,Age,Gender,Country) VALUES (2,30,'Female','China'); CREATE TABLE VRAdoption (PlayerID INT,VRPurchaseDate DATE); INSERT INTO VR...
SELECT COUNT(Players.PlayerID) FROM Players INNER JOIN VRAdoption ON Players.PlayerID = VRAdoption.PlayerID WHERE Players.Country LIKE 'Asia%';
What is the average R&D expenditure for drugs approved in 2017 and 2018?
CREATE TABLE drugs (drug_id INT,drug_name TEXT,approval_year INT,R_D_expenses FLOAT); INSERT INTO drugs (drug_id,drug_name,approval_year,R_D_expenses) VALUES (1001,'DrugA',2017,1200000),(1002,'DrugB',2018,1500000),(1003,'DrugC',2017,1300000),(1004,'DrugD',2018,1100000);
SELECT approval_year, AVG(R_D_expenses) as avg_R_D_expenses FROM drugs WHERE approval_year IN (2017, 2018) GROUP BY approval_year;
Delete the record for the course "AI Ethics" from the "courses" table
CREATE TABLE courses (id INT PRIMARY KEY,name VARCHAR(50),instructor VARCHAR(50),department VARCHAR(50));
DELETE FROM courses WHERE name = 'AI Ethics';
What is the total weight of apples in the inventory?
CREATE TABLE inventory (product_id INT,product_name VARCHAR(30),weight FLOAT); INSERT INTO inventory (product_id,product_name,weight) VALUES (1,'Apples',15.3),(2,'Oranges',12.9);
SELECT SUM(weight) FROM inventory WHERE product_name = 'Apples';
What is the average time to process cases by case type in the 'criminal_cases' table?
CREATE TABLE criminal_cases (case_id INT,case_number VARCHAR(20),case_type VARCHAR(30),court_location VARCHAR(30),processing_date DATE);
SELECT case_type, AVG(DATEDIFF(processing_date, court_date)) AS avg_processing_time FROM criminal_cases GROUP BY case_type;
Which professional development courses did teachers in the 'Uptown' school district complete in the last year?
CREATE TABLE teacher (teacher_id INT,district_id INT,FOREIGN KEY (district_id) REFERENCES school_district(district_id)); CREATE TABLE course (course_id INT,course_name VARCHAR(50),course_year INT,PRIMARY KEY(course_id)); CREATE TABLE teacher_course (teacher_id INT,course_id INT,completed_date DATE,PRIMARY KEY(teacher_i...
SELECT c.course_name, c.course_year FROM teacher t INNER JOIN teacher_course tc ON t.teacher_id = tc.teacher_id INNER JOIN course c ON tc.course_id = c.course_id WHERE t.district_id = 2 AND tc.completed_date >= '2021-01-01' AND tc.completed_date < '2022-01-01';
Identify the graduate programs with the highest average impact factor of their published research grants.
CREATE TABLE program (id INT,name VARCHAR(50),type VARCHAR(50)); CREATE TABLE grant (id INT,title VARCHAR(100),program_id INT,impact_factor DECIMAL(3,1));
SELECT p.name, AVG(g.impact_factor) as avg_impact_factor FROM program p JOIN grant g ON p.id = g.program_id GROUP BY p.name ORDER BY avg_impact_factor DESC LIMIT 1;
List all autonomous driving research projects and their respective funding sources.
CREATE TABLE AutonomousDrivingResearch (id INT,project_name VARCHAR(50),funding_source VARCHAR(50)); INSERT INTO AutonomousDrivingResearch (id,project_name,funding_source) VALUES (1,'Project A','Company X'); INSERT INTO AutonomousDrivingResearch (id,project_name,funding_source) VALUES (2,'Project B','Government Y');
SELECT project_name, funding_source FROM AutonomousDrivingResearch;
What is the average response time for citizen feedback in the rural areas?
CREATE TABLE Feedback (Location VARCHAR(255),ResponseTime INT); INSERT INTO Feedback (Location,ResponseTime) VALUES ('Rural',120),('Rural',150),('Urban',90),('Urban',100);
SELECT AVG(ResponseTime) FROM Feedback WHERE Location = 'Rural';
What was the total number of theatre performances in each borough in 2020?
CREATE TABLE TheatrePerformances (id INT,borough VARCHAR(10),performance_type VARCHAR(20),performance_date DATE); INSERT INTO TheatrePerformances (id,borough,performance_type,performance_date) VALUES (1,'Manhattan','Play','2020-02-01'),(2,'Brooklyn','Musical','2020-10-15'),(3,'Queens','Opera','2020-07-03');
SELECT borough, performance_type, COUNT(*) as performance_count FROM TheatrePerformances WHERE YEAR(performance_date) = 2020 AND performance_type = 'Play' GROUP BY borough, performance_type;
Add a new column gender_equality to the social_good table
CREATE TABLE social_good (region VARCHAR(255),ai_impact FLOAT,updated_on DATE);
ALTER TABLE social_good ADD gender_equality VARCHAR(255);
What is the total number of disaster preparedness drills and exercises in the state of Texas, compared to the number of drills and exercises in the state of California?
CREATE TABLE preparedness_drills (id INT,state VARCHAR(20),drill_type VARCHAR(20),date DATE); INSERT INTO preparedness_drills (id,state,drill_type,date) VALUES (1,'Texas','evacuation','2021-01-01'); INSERT INTO preparedness_drills (id,state,drill_type,date) VALUES (2,'California','shelter','2021-01-02');
SELECT state, SUM(drill_count) FROM (SELECT state, COUNT(*) AS drill_count FROM preparedness_drills WHERE state = 'Texas' GROUP BY state UNION ALL SELECT 'California' AS state, COUNT(*) AS drill_count FROM preparedness_drills WHERE state = 'California' GROUP BY state) AS drills GROUP BY state
What is the average size of mines by state in the USA?
CREATE TABLE mines (id INT,name TEXT,state TEXT,size INT); INSERT INTO mines (id,name,state,size) VALUES (1,'Golden Mine','Texas',500),(2,'Silver Mine','Texas',300),(3,'Bronze Mine','California',200),(4,'Platinum Mine','California',400);
SELECT state, AVG(size) as avg_size FROM mines GROUP BY state;
Update the warehouse location for item with ID 42
CREATE TABLE inventory (id INT,item_name VARCHAR(255),warehouse_location VARCHAR(255)); INSERT INTO inventory (id,item_name,warehouse_location) VALUES (42,'Widget','Aisle 3'),(43,'Gizmo','Aisle 5');
UPDATE inventory SET warehouse_location = 'Aisle 7' WHERE id = 42;
What is the total word count of articles by language in 'global_news_articles' table?
CREATE TABLE global_news_articles (id INT,title VARCHAR(100),publication_date DATE,author VARCHAR(50),word_count INT,language VARCHAR(20)); INSERT INTO global_news_articles (id,title,publication_date,author,word_count,language) VALUES (1,'Article 1','2022-01-01','John Doe',500,'English'),(2,'Article 2','2022-01-02','Ja...
SELECT language, SUM(word_count) as total_word_count FROM global_news_articles GROUP BY language;
What is the number of streams per user per day for the "r&b" genre in the African region for the year 2018?
CREATE TABLE StreamsPerUser(id INT,genre VARCHAR(10),region VARCHAR(10),user_id INT,date DATE,streams INT);
SELECT date, user_id, AVG(CAST(streams AS FLOAT)/COUNT(date)) AS streams_per_day FROM StreamsPerUser WHERE genre = 'r&b' AND region = 'African' AND year = 2018 GROUP BY date, user_id;
What is the average value of artworks by Indigenous Australian artists?
CREATE TABLE artist_origin (id INT,artist_name VARCHAR(50),origin VARCHAR(50)); CREATE TABLE artwork_value (id INT,artwork_name VARCHAR(50),artist_id INT,value DECIMAL(10,2));
SELECT AVG(value) as avg_value FROM artwork_value a JOIN artist_origin o ON a.artist_id = o.id WHERE o.origin = 'Indigenous Australian';
What is the minimum daily production rate of gas wells in the Baltic Sea that were drilled after 2015?
CREATE TABLE baltic_sea (id INT,well_name VARCHAR(255),drill_date DATE,daily_production_gas FLOAT);
SELECT MIN(daily_production_gas) as min_daily_production_gas FROM baltic_sea WHERE drill_date > '2015-12-31';
Identify the top 3 candidates who applied for a position, ordered by application date in descending order, for each job title.
CREATE TABLE Applications (ApplicationID INT,CandidateName VARCHAR(50),JobTitle VARCHAR(50),ApplicationDate DATE); INSERT INTO Applications (ApplicationID,CandidateName,JobTitle,ApplicationDate) VALUES (1,'John Doe','Manager','2022-01-01'),(2,'Jane Smith','Manager','2022-01-02'),(3,'Bob Johnson','Developer','2022-01-03...
SELECT JobTitle, CandidateName, ApplicationDate, ROW_NUMBER() OVER (PARTITION BY JobTitle ORDER BY ApplicationDate DESC) AS Rank FROM Applications WHERE Rank <= 3;
What is the trend of mental health scores over the years?
CREATE TABLE student_mental_health (student_id INT,score INT,year INT); INSERT INTO student_mental_health (student_id,score,year) VALUES (1,80,2021),(1,85,2022),(2,70,2021),(2,75,2022),(3,90,2021),(3,95,2022);
SELECT year, AVG(score) as avg_score FROM student_mental_health GROUP BY year ORDER BY year;
Who are the therapists with the least number of sessions in Indonesia and Nigeria?
CREATE TABLE therapists (id INT,name TEXT); CREATE TABLE therapy_sessions (id INT,therapist_id INT,session_date DATE); INSERT INTO therapists (id,name) VALUES (1,'Dewi Suryani'); INSERT INTO therapists (id,name) VALUES (2,'Temitope Johnson'); INSERT INTO therapy_sessions (id,therapist_id,session_date) VALUES (1,1,'2022...
SELECT therapists.name, COUNT(therapy_sessions.id) AS session_count FROM therapists INNER JOIN therapy_sessions ON therapists.id = therapy_sessions.therapist_id WHERE therapists.name IN ('Dewi Suryani', 'Temitope Johnson') GROUP BY therapists.name ORDER BY session_count ASC;
Update the sustainability ratings for cultural tours in New Delhi with a rating below 3.5.
CREATE TABLE cultural_tours (tour_id INT,city VARCHAR(50),sustainability_rating DECIMAL(3,1)); INSERT INTO cultural_tours (tour_id,city,sustainability_rating) VALUES (1,'New Delhi',3.2),(2,'New Delhi',3.8),(3,'Mumbai',4.2),(4,'Bangalore',3.9);
UPDATE cultural_tours SET sustainability_rating = sustainability_rating + 0.5 WHERE city = 'New Delhi' AND sustainability_rating < 3.5;
Find the percentage change in temperature for each continent between 2019 and 2020 in the 'world_temperature' table.
CREATE TABLE world_temperature (country VARCHAR(255),temperature DECIMAL(5,2),measurement_date DATE,continent VARCHAR(255)); INSERT INTO world_temperature (country,temperature,measurement_date,continent) VALUES ('South Africa',25.3,'2019-01-01','Africa'),('Nigeria',28.1,'2019-01-01','Africa'),('Canada',10.5,'2019-01-01...
SELECT a.continent, (a.temperature - b.temperature) * 100.0 / b.temperature as temperature_change_percentage FROM world_temperature a INNER JOIN world_temperature b ON a.continent = b.continent WHERE YEAR(a.measurement_date) = 2020 AND YEAR(b.measurement_date) = 2019;
Add new virtual reality headset records
CREATE TABLE vr_headsets (id INT PRIMARY KEY,name VARCHAR(50),manufacturer VARCHAR(50),release_date DATE);
INSERT INTO vr_headsets (id, name, manufacturer, release_date) VALUES (1, 'Headset A', 'Company X', '2022-10-01'), (2, 'Headset B', 'Company Y', '2023-02-15');
What is the average time to resolve security incidents in the 'Malware' category in the last quarter?
CREATE TABLE incident_resolution (id INT,category VARCHAR(255),resolution_time INT,resolution_date DATE);
SELECT AVG(resolution_time) FROM incident_resolution WHERE category = 'Malware' AND resolution_date >= DATEADD(quarter, -1, GETDATE());
What is the cultural competency score distribution among healthcare providers?
CREATE TABLE HealthcareProviders (ProviderID INT,CulturalCompetencyScore INT); INSERT INTO HealthcareProviders (ProviderID,CulturalCompetencyScore) VALUES (1,85); INSERT INTO HealthcareProviders (ProviderID,CulturalCompetencyScore) VALUES (2,90); INSERT INTO HealthcareProviders (ProviderID,CulturalCompetencyScore) VALU...
SELECT CulturalCompetencyScore, COUNT(*) FROM HealthcareProviders GROUP BY CulturalCompetencyScore;
List the traditional arts practiced in 'North America' since 1990.
CREATE TABLE TraditionalArts (id INT,name VARCHAR(255),region VARCHAR(255),start_year INT); INSERT INTO TraditionalArts (id,name,region,start_year) VALUES (1,'Powwow Dancing','North America',1970);
SELECT name FROM TraditionalArts WHERE region = 'North America' AND start_year >= 1990;
What is the lowest dissolved oxygen level in the Indian Ocean for tilapia farms?
CREATE TABLE Indian_Ocean (id INT,dissolved_oxygen DECIMAL(5,2)); INSERT INTO Indian_Ocean (id,dissolved_oxygen) VALUES (1,6.5),(2,7.2),(3,5.9); CREATE TABLE Tilapia_Farms (id INT,ocean VARCHAR(20)); INSERT INTO Tilapia_Farms (id,ocean) VALUES (1,'Indian'),(2,'Pacific'),(3,'Indian');
SELECT MIN(Indian_Ocean.dissolved_oxygen) FROM Indian_Ocean INNER JOIN Tilapia_Farms ON Indian_Ocean.id = Tilapia_Farms.id WHERE Tilapia_Farms.ocean = 'Indian';
What was the total revenue for 'Dance' concerts in Q2 2021?
CREATE TABLE events (event_id INT,genre VARCHAR(20),revenue FLOAT,event_date DATE); INSERT INTO events (event_id,genre,revenue,event_date) VALUES (1,'Dance',2000,'2021-04-10'); INSERT INTO events (event_id,genre,revenue,event_date) VALUES (2,'Dance',3000,'2021-06-15');
SELECT SUM(revenue) FROM events WHERE genre = 'Dance' AND event_date BETWEEN '2021-04-01' AND '2021-06-30';
List the top 5 donors by total donation amount and the corresponding programs
CREATE TABLE donors (id INT,name VARCHAR,email VARCHAR); CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL,payment_method VARCHAR,program_id INT); CREATE TABLE programs (id INT,name VARCHAR,budget DECIMAL);
SELECT donors.name as top_donors, SUM(donations.amount) as total_donation_amount, programs.name as program_name FROM donors JOIN donations ON donors.id = donations.donor_id JOIN programs ON donations.program_id = programs.id GROUP BY donors.id, programs.id ORDER BY total_donation_amount DESC, top_donors LIMIT 5;
Find the total number of financial wellbeing programs offered in each country?
CREATE TABLE financial_wellbeing_programs (program_id INT,country VARCHAR(20)); INSERT INTO financial_wellbeing_programs (program_id,country) VALUES (101,'USA'),(102,'Canada'),(103,'Mexico'),(104,'USA'),(105,'Canada');
SELECT country, COUNT(*) FROM financial_wellbeing_programs GROUP BY country;
What is the percentage of organic products in each category, ranked in descending order of the percentage?
CREATE TABLE products (product_id INT,category VARCHAR(20),is_organic BOOLEAN); INSERT INTO products (product_id,category,is_organic) VALUES (1,'Natural',false),(2,'Organic',true),(3,'Natural',true),(4,'Conventional',false);
SELECT category, 100.0 * COUNT(*) FILTER (WHERE is_organic) / COUNT(*) as percentage FROM products GROUP BY category ORDER BY percentage DESC;
Who are the customers with Investment accounts and their Investment types?
CREATE TABLE Customers (CustomerId INT,FirstName VARCHAR(20),LastName VARCHAR(20),AccountId INT); INSERT INTO Customers (CustomerId,FirstName,LastName,AccountId) VALUES (1,'John','Doe',1),(2,'Jane','Doe',2); CREATE TABLE Accounts (AccountId INT,AccountType VARCHAR(20)); INSERT INTO Accounts (AccountId,AccountType) VALU...
SELECT C.FirstName, C.LastName, I.InvestmentType FROM Customers C JOIN Accounts A ON C.AccountId = A.AccountId JOIN Investments I ON A.AccountId = I.AccountId WHERE A.AccountType = 'Investment';
How many threat intelligence events were recorded per day in the past week?
CREATE TABLE threat_intelligence (id INT,event_date DATE); INSERT INTO threat_intelligence (id,event_date) VALUES (1,'2022-02-01'),(2,'2022-02-02'),(3,'2022-02-03'),(4,'2022-02-04'),(5,'2022-02-05'),(6,'2022-02-06'),(7,'2022-02-07');
SELECT event_date, COUNT(*) as event_count FROM threat_intelligence WHERE event_date >= DATEADD(day, -7, GETDATE()) GROUP BY event_date;
Show the number of vegan and non-vegan beauty products in the inventory
CREATE TABLE inventory (product VARCHAR(255),is_vegan BOOLEAN); INSERT INTO inventory (product,is_vegan) VALUES ('Vegan Mascara',TRUE),('Non-Vegan Lipstick',FALSE);
SELECT COUNT(*) FROM inventory WHERE is_vegan = TRUE; SELECT COUNT(*) FROM inventory WHERE is_vegan = FALSE;
List the top 3 brands by sales in descending order for the "makeup" category.
CREATE TABLE sales (id INT,brand VARCHAR(100),category VARCHAR(100),revenue FLOAT);
SELECT brand, SUM(revenue) as total_sales FROM sales WHERE category = 'makeup' GROUP BY brand ORDER BY total_sales DESC LIMIT 3;
What is the total revenue generated from each game genre?
CREATE TABLE game (game_id INT,game_title VARCHAR(50),game_genre VARCHAR(20),revenue INT); INSERT INTO game (game_id,game_title,game_genre,revenue) VALUES (1,'League of Legends','MOBA',1000000); INSERT INTO game (game_id,game_title,game_genre,revenue) VALUES (2,'Mario Kart','Racing',500000);
SELECT game_genre, SUM(revenue) FROM game GROUP BY game_genre;
What are the names and locations of warehouses that store chemicals used in the production of pharmaceuticals?
CREATE TABLE warehouses (id INT,name TEXT,location TEXT); INSERT INTO warehouses (id,name,location) VALUES (1,'WH1','New York'),(2,'WH2','Chicago'),(3,'WH3','Los Angeles'); CREATE TABLE chemicals (id INT,name TEXT,type TEXT); INSERT INTO chemicals (id,name,type) VALUES (1,'ChemA','Pharma'),(2,'ChemB','Industrial'),(3,'...
SELECT w.name, w.location FROM warehouses w INNER JOIN inventory i ON w.id = i.warehouse_id INNER JOIN chemicals c ON i.chemical_id = c.id WHERE c.type = 'Pharma';
Which aircraft models in the 'aircraft_manufacturing' table have more than 500 units produced?
CREATE TABLE aircraft_manufacturing (model VARCHAR(50),units_produced INT);
SELECT model FROM aircraft_manufacturing WHERE units_produced > 500;
What is the total cost of commercial projects in New York?
CREATE TABLE Sustainable_Projects (Project_ID INT,Project_Name TEXT,Location TEXT,Cost FLOAT,Sustainable BOOLEAN,Type TEXT); INSERT INTO Sustainable_Projects (Project_ID,Project_Name,Location,Cost,Sustainable,Type) VALUES (1,'Green House','California',500000.00,true,'Residential'),(2,'Eco Office','New York',750000.00,t...
SELECT SUM(Cost) FROM Sustainable_Projects WHERE Location = 'New York' AND Type = 'Commercial';
How many vegan makeup products were sold in Canada in 2021?
CREATE TABLE Makeup_Sales (SaleID int,ProductName varchar(100),SaleDate date,QuantitySold int,IsVegan bit); INSERT INTO Makeup_Sales (SaleID,ProductName,SaleDate,QuantitySold,IsVegan) VALUES (1,'Vegan Lipstick','2021-01-01',500,1); INSERT INTO Makeup_Sales (SaleID,ProductName,SaleDate,QuantitySold,IsVegan) VALUES (2,'C...
SELECT SUM(QuantitySold) FROM Makeup_Sales WHERE IsVegan = 1 AND SaleDate >= '2021-01-01' AND SaleDate <= '2021-12-31';
What is the total revenue generated by hotel bookings in the APAC region in Q1 2022?
CREATE TABLE bookings (booking_id INT,booking_date DATE,region VARCHAR(255),revenue DECIMAL(10,2)); INSERT INTO bookings (booking_id,booking_date,region,revenue) VALUES (1,'2022-01-01','APAC',100),(2,'2022-02-01','APAC',200),(3,'2022-03-01','APAC',300);
SELECT SUM(revenue) FROM bookings WHERE region = 'APAC' AND booking_date >= '2022-01-01' AND booking_date < '2022-04-01';
What is the CO2 emissions rank for each chemical in the past year?
CREATE TABLE co2_emissions (id INT PRIMARY KEY,chemical_name VARCHAR(255),co2_emissions INT,date DATE); INSERT INTO co2_emissions (id,chemical_name,co2_emissions,date) VALUES (7,'Acetic Acid',120,'2022-05-01'); INSERT INTO co2_emissions (id,chemical_name,co2_emissions,date) VALUES (8,'Oxalic Acid',180,'2022-05-02');
SELECT chemical_name, co2_emissions, RANK() OVER(ORDER BY co2_emissions DESC) as co2_rank FROM co2_emissions WHERE date >= DATEADD(year, -1, GETDATE());
Show all suppliers from a specific region
CREATE TABLE regions (id INT PRIMARY KEY,name VARCHAR(255)); CREATE TABLE suppliers (id INT PRIMARY KEY,name VARCHAR(255),region_id INT,country VARCHAR(255));
SELECT suppliers.name FROM suppliers INNER JOIN regions ON suppliers.region_id = regions.id WHERE regions.name = 'South America';
What is the total number of claims for each type of insurance, for policyholders residing in the city of New York?
CREATE TABLE claims (claim_id INT,policy_id INT,claim_amount DECIMAL(10,2),city VARCHAR(50)); CREATE TABLE policies (policy_id INT,policy_holder_id INT,policy_type VARCHAR(50),issue_date DATE);
SELECT p.policy_type, COUNT(c.claim_id) FROM claims c JOIN policies p ON c.policy_id = p.policy_id WHERE city = 'New York' GROUP BY p.policy_type;
What is the maximum salary for employees who were hired in the first quarter of any year?
CREATE TABLE Employees (EmployeeID INT,HireDate DATE,Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,HireDate,Salary) VALUES (1,'2020-01-01',75000.00),(2,'2019-01-01',60000.00),(3,'2020-03-01',80000.00),(4,'2018-04-01',90000.00),(5,'2020-05-01',95000.00),(6,'2019-06-01',65000.00);
SELECT MAX(Salary) FROM Employees WHERE QUARTER(HireDate) = 1;
Identify the top 2 regions with the highest average labor hours per project and their respective averages.
CREATE TABLE project (project_id INT,region VARCHAR(20),labor_hours INT); INSERT INTO project VALUES (1,'Northeast',500); INSERT INTO project VALUES (2,'Southwest',700); INSERT INTO project VALUES (3,'Midwest',600);
SELECT region, AVG(labor_hours) as avg_labor_hours, RANK() OVER (ORDER BY AVG(labor_hours) DESC) as labor_hours_rank FROM project GROUP BY region HAVING labor_hours_rank <= 2;
What is the median age of community health workers in Florida?
CREATE TABLE community_health_workers (id INT,name TEXT,age INT,state TEXT); INSERT INTO community_health_workers (id,name,age,state) VALUES (1,'John Doe',35,'Florida'); INSERT INTO community_health_workers (id,name,age,state) VALUES (2,'Jane Smith',40,'Florida'); INSERT INTO community_health_workers (id,name,age,state...
SELECT AVG(age) FROM (SELECT age FROM community_health_workers WHERE state = 'Florida' ORDER BY age) AS subquery ORDER BY age DESC LIMIT 1;
What is the minimum labor productivity score for mines in South Africa?
CREATE TABLE mines (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),year_opened INT,total_employees INT); INSERT INTO mines (id,name,location,year_opened,total_employees) VALUES (1,'Golden Ridge Mine','South Africa',1992,250); INSERT INTO mines (id,name,location,year_opened,total_employees) VALUES (2,'Emeral...
SELECT MIN(labor_productivity.productivity_score) as min_productivity FROM labor_productivity JOIN mines ON labor_productivity.mine_id = mines.id WHERE mines.location = 'South Africa';
Which organizations received donations from donors residing in the Asia-Pacific region, and what are the total donation amounts for each organization? Join the donors, donations, and organizations tables.
CREATE TABLE donors (id INT,name VARCHAR(255),country VARCHAR(255)); INSERT INTO donors (id,name,country) VALUES (1,'Ravi Sharma','India'),(2,'Siti Nurhaliza','Malaysia'),(3,'John Smith','USA'); CREATE TABLE donations (id INT,donor_id INT,organization_id INT,amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,org...
SELECT o.name, SUM(donations.amount) as total_donation FROM donors d JOIN donations ON d.id = donations.donor_id JOIN organizations o ON donations.organization_id = o.id WHERE d.country LIKE 'Asia%' GROUP BY o.name;
What is the total loan amount disbursed to microfinance institutions in Africa?
CREATE TABLE microfinance_loans (id INT,institution VARCHAR(255),country VARCHAR(255),loan_amount FLOAT);
SELECT SUM(loan_amount) FROM microfinance_loans WHERE country = 'Africa';
What is the average daily step count for all members with a Gold membership in the last week?
CREATE TABLE Members (MemberID INT,Name VARCHAR(50),Age INT,Membership VARCHAR(20)); CREATE TABLE Steps (StepID INT,MemberID INT,Steps INT,Date DATE); INSERT INTO Members (MemberID,Name,Age,Membership) VALUES (1,'John Doe',35,'Platinum'),(2,'Jane Smith',28,'Gold'),(3,'Mike Johnson',22,'Silver'); INSERT INTO Steps (Step...
SELECT AVG(Steps) FROM Members JOIN Steps ON Members.MemberID = Steps.MemberID WHERE Membership = 'Gold' AND Date >= DATEADD(DAY, -7, GETDATE());
Determine the average deaths per match by champion in LoL
CREATE TABLE lolgames (game_id INT,champion VARCHAR(50),deaths INT); INSERT INTO lolgames (game_id,champion,deaths) VALUES (1,'Ashe',4);
SELECT champion, AVG(deaths) as avg_deaths_per_match, RANK() OVER (ORDER BY AVG(deaths) DESC) as rank FROM lolgames GROUP BY champion
What is the total number of visitors from Asian communities who engaged with on-site exhibits in 2021?
CREATE TABLE Communities (id INT,community_type VARCHAR(30)); INSERT INTO Communities (id,community_type) VALUES (1,'Indigenous'),(2,'Settler'),(3,'Immigrant'),(4,'Asian'); CREATE TABLE OnsiteEngagement (id INT,visitor_id INT,community_id INT,year INT); INSERT INTO OnsiteEngagement (id,visitor_id,community_id,year) VAL...
SELECT COUNT(DISTINCT OnsiteEngagement.visitor_id) FROM OnsiteEngagement INNER JOIN Communities ON OnsiteEngagement.community_id = Communities.id WHERE Communities.community_type = 'Asian' AND OnsiteEngagement.year = 2021;
What is the average depth of the mines in the region?
CREATE TABLE region (id INT,name TEXT); CREATE TABLE mine (id INT,name TEXT,region_id INT,depth INT); INSERT INTO region (id,name) VALUES (1,'Region A'),(2,'Region B'),(3,'Region C'); INSERT INTO mine (id,name,region_id,depth) VALUES (1,'Gold Mine 1',1,1000),(2,'Copper Mine 2',1,1500),(3,'Iron Mine 3',2,2000),(4,'Silve...
SELECT region.name, AVG(mine.depth) AS avg_depth FROM region JOIN mine ON region.id = mine.region_id GROUP BY region.name;
Insert a new player 'Lebron James' with jersey number 6 for the 'Los Angeles Lakers'
CREATE TABLE teams (id INT,name VARCHAR(255)); CREATE TABLE players (id INT,name VARCHAR(255),jersey_number INT,team_id INT); INSERT INTO teams (id,name) VALUES (3,'Los Angeles Lakers');
INSERT INTO players (id, name, jersey_number, team_id) VALUES (4, 'Lebron James', 6, 3);
Identify the top 3 threat actors with the most successful attacks against financial institutions in the past year, along with the number of successful attacks.
CREATE TABLE threat_actors (id INT PRIMARY KEY,name VARCHAR(50),target_sector VARCHAR(50),success_count INT); INSERT INTO threat_actors (id,name,target_sector,success_count) VALUES (1,'APT28','Finance',15),(2,'APT33','Finance',10),(3,'Magecart','Finance',20);
SELECT name, success_count FROM threat_actors WHERE target_sector = 'Finance' ORDER BY success_count DESC LIMIT 3;
What is the average daily ridership of public bicycles in Australia?
CREATE TABLE PB_Usage (id INT,system_type VARCHAR(20),country VARCHAR(50),daily_ridership INT); INSERT INTO PB_Usage (id,system_type,country,daily_ridership) VALUES (1,'Melbourne Bike Share','Australia',5000),(2,'Brisbane CityCycle','Australia',4000),(3,'Adelaide Free Bikes','Australia',3000);
SELECT AVG(daily_ridership) as avg_daily_ridership FROM PB_Usage WHERE country = 'Australia';
What is the average energy consumption of buildings in the 'smart_cities' schema, grouped by city?
CREATE TABLE smart_cities.building_data (city VARCHAR(255),energy_consumption FLOAT);
SELECT city, AVG(energy_consumption) FROM smart_cities.building_data GROUP BY city;
List all network investments made in the Latin American region in the past 6 months, including the investment amount and location.
CREATE TABLE network_investments (investment_id INT,investment_amount FLOAT,investment_date DATE,location TEXT); INSERT INTO network_investments (investment_id,investment_amount,investment_date,location) VALUES (1,300000,'2022-01-10','Bogota'); INSERT INTO network_investments (investment_id,investment_amount,investment...
SELECT * FROM network_investments WHERE investment_date >= DATEADD(month, -6, CURRENT_DATE) AND location LIKE 'Latin%';
What is the total donation amount by donor type?
CREATE TABLE Donations (DonorType VARCHAR(20),DonationAmount NUMERIC(12,2)); INSERT INTO Donations (DonorType,DonationAmount) VALUES ('Individual',1500.00),('Corporate',5000.00),('Foundation',3000.00);
SELECT DonorType, SUM(DonationAmount) FROM Donations GROUP BY DonorType;
What is the total amount donated and number of volunteers for each city in the state of California?
CREATE TABLE donations (donor_id INT,donation_date DATE,amount DECIMAL(10,2),city VARCHAR(50),state VARCHAR(50)); INSERT INTO donations (donor_id,donation_date,amount,city,state) VALUES (1,'2021-01-01',50.00,'Los Angeles','California'),(2,'2021-01-15',100.00,'San Francisco','California'),(1,'2021-03-05',200.00,'San Die...
SELECT city, SUM(amount) AS total_donated, COUNT(*) AS num_volunteers FROM (SELECT 'donation' AS type, city, state, amount FROM donations WHERE state = 'California' UNION ALL SELECT 'volunteer' AS type, city, state, 0 AS amount FROM volunteers WHERE state = 'California') AS data GROUP BY city;
Which drugs were tested in clinical trials and failed, grouped by the number of failures?
CREATE TABLE ClinicalTrials (trial_id INT,drug_name VARCHAR(255),trial_status VARCHAR(255)); INSERT INTO ClinicalTrials (trial_id,drug_name,trial_status) VALUES (1,'DrugG','Completed'),(2,'DrugG','Failed'),(3,'DrugH','Failed'),(4,'DrugI','Failed'),(5,'DrugJ','Completed'),(6,'DrugJ','Completed');
SELECT drug_name, COUNT(*) as failure_count FROM ClinicalTrials WHERE trial_status = 'Failed' GROUP BY drug_name;
What is the total value of socially responsible loans disbursed by financial institutions in Canada?
CREATE TABLE canada_institutions (institution_id INT,institution_name TEXT); CREATE TABLE loans_canada (loan_id INT,institution_id INT,loan_amount FLOAT,is_socially_responsible BOOLEAN);
SELECT SUM(loans_canada.loan_amount) FROM loans_canada JOIN canada_institutions ON loans_canada.institution_id = canada_institutions.institution_id WHERE loans_canada.is_socially_responsible = TRUE AND canada_institutions.institution_id IN (SELECT loans_canada.institution_id FROM loans_canada JOIN canada_institutions O...
Number of OTA bookings in 'Europe' in Q1 2022?
CREATE TABLE otas (ota_id INT,ota_name TEXT,booking_date DATE); INSERT INTO otas (ota_id,ota_name,booking_date) VALUES (1,'OTA Europe','2022-03-25'),(2,'OTA Latam','2022-03-28'),(3,'OTA Europe','2022-01-12');
SELECT COUNT(*) FROM otas WHERE booking_date >= '2022-01-01' AND booking_date < '2022-04-01' AND ota_name IN (SELECT ota_name FROM otas WHERE ota_name LIKE '%Europe%');
List the names of all employees who have worked for more than 5 years?
CREATE TABLE employee_history (id INT,name VARCHAR(50),position VARCHAR(50),start_date DATE);
SELECT name FROM employee_history WHERE DATEDIFF(CURRENT_DATE, start_date) > (5 * 365);
Identify the top 3 countries with the most marine species observed in their waters.
CREATE TABLE marine_species_observations (id INT,country VARCHAR(30),species VARCHAR(50),date DATE); INSERT INTO marine_species_observations (id,country,species,date) VALUES (1,'Indonesia','Clownfish','2021-03-11'); INSERT INTO marine_species_observations (id,country,species,date) VALUES (2,'Australia','Blue Ring Octop...
SELECT country, COUNT(*) AS total_species FROM marine_species_observations GROUP BY country ORDER BY total_species DESC LIMIT 3;
What is the percentage of dishes that are gluten-free?
CREATE TABLE Menus (menu_id INT,dish_name VARCHAR(255),is_gluten_free BOOLEAN); INSERT INTO Menus (menu_id,dish_name,is_gluten_free) VALUES (1,'Spaghetti',false),(2,'Gluten-Free Pasta',true),(3,'Chicken Parmesan',false),(4,'Salmon',true),(5,'Risotto',false);
SELECT (COUNT(*) FILTER (WHERE is_gluten_free = true)) * 100.0 / COUNT(*) FROM Menus;
Find the percentage of destinations in Asia with sustainable tourism certifications
CREATE TABLE destinations (name VARCHAR(255),country VARCHAR(255),continent VARCHAR(255),sustainable_certification BOOLEAN); INSERT INTO destinations (name,country,continent,sustainable_certification) VALUES ('City G','Country G','Asia',TRUE),('City H','Country H','Asia',FALSE),('City I','Country I','Asia',TRUE);
SELECT (COUNT(*) / (SELECT COUNT(*) FROM destinations WHERE continent = 'Asia') * 100) AS percentage FROM destinations WHERE continent = 'Asia' AND sustainable_certification = TRUE;
What is the total production cost of sustainable materials in South America in the last year?
CREATE TABLE material_production_samerica (material_id INT,material_name VARCHAR(50),production_date DATE,production_cost DECIMAL(10,2)); INSERT INTO material_production_samerica (material_id,material_name,production_date,production_cost) VALUES (1,'Organic Cotton','2021-08-05',500.00),(2,'Recycled Polyester','2021-07-...
SELECT SUM(production_cost) FROM material_production_samerica WHERE material_name IN ('Organic Cotton', 'Recycled Polyester', 'Hemp') AND production_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND CURDATE();
What are the total number of healthcare access issues reported in urban and rural areas?
CREATE TABLE urban_healthcare (id INT,issue VARCHAR(255)); INSERT INTO urban_healthcare (id,issue) VALUES (1,'Lack of medical specialists'); INSERT INTO urban_healthcare (id,issue) VALUES (2,'Long waiting times'); CREATE TABLE rural_healthcare (id INT,issue VARCHAR(255)); INSERT INTO rural_healthcare (id,issue) VALUES ...
SELECT COUNT(*) FROM urban_healthcare UNION ALL SELECT COUNT(*) FROM rural_healthcare;
What is the average billing amount for cases in California?
CREATE TABLE cases (id INT,state VARCHAR(2),billing_amount DECIMAL(10,2));
SELECT AVG(billing_amount) FROM cases WHERE state = 'CA';
Calculate the total donations for each program, ordered by the total donation amount in descending order.
CREATE TABLE donations (id INT,program_id INT,amount DECIMAL(10,2)); INSERT INTO donations (id,program_id,amount) VALUES (1,1,250.00),(2,1,500.00),(3,2,1000.00),(4,2,300.00),(5,3,750.00); CREATE TABLE programs (id INT,name TEXT); INSERT INTO programs (id,name) VALUES (1,'Feeding the Hungry'),(2,'Tutoring Kids'),(3,'Cle...
SELECT programs.id, programs.name, SUM(donations.amount) AS total_donations FROM donations INNER JOIN programs ON donations.program_id = programs.id GROUP BY programs.id, programs.name ORDER BY total_donations DESC;
What is the average budget of climate mitigation projects in Africa that were implemented after 2015?
CREATE TABLE climate_mitigation (id INT,project_name TEXT,budget INT,start_year INT,location TEXT); INSERT INTO climate_mitigation (id,project_name,budget,start_year,location) VALUES (1,'Tree Planting',50000,2016,'Africa'); INSERT INTO climate_mitigation (id,project_name,budget,start_year,location) VALUES (2,'Energy Ef...
SELECT AVG(budget) FROM climate_mitigation WHERE location = 'Africa' AND start_year > 2015;
What are the contract negotiations with French companies?
CREATE TABLE contract_negotiations (id INT,contractor_id INT,negotiation_date DATE,amount DECIMAL(10,2)); INSERT INTO contract_negotiations (id,contractor_id,negotiation_date,amount) VALUES (2,2,'2021-07-16',2000000.00);
SELECT * FROM contract_negotiations WHERE contractor_id IN (SELECT id FROM contractors WHERE country = 'France');
How many marine conservation initiatives were launched in Africa in the last decade?
CREATE TABLE marine_conservation_initiatives (id INT,initiative_name VARCHAR(255),launch_year INT,location VARCHAR(255)); INSERT INTO marine_conservation_initiatives (id,initiative_name,launch_year,location) VALUES (1,'Initiative 1',2012,'Africa'),(2,'Initiative 2',2015,'Asia'),(3,'Initiative 3',2018,'Africa'),(4,'Init...
SELECT COUNT(*) FROM marine_conservation_initiatives WHERE launch_year >= YEAR(CURRENT_DATE) - 10 AND location = 'Africa';
How many local businesses have benefited from the 'Support Local' program in New York?
CREATE TABLE businesses (id INT,name VARCHAR(255),city VARCHAR(255),category VARCHAR(255),supported BOOLEAN); INSERT INTO businesses (id,name,city,category,supported) VALUES (1,'Eco-Friendly Cafe','New York','Food',TRUE),(2,'Sustainable Clothing Store','New York','Retail',TRUE);
SELECT COUNT(*) FROM businesses WHERE city = 'New York' AND supported = TRUE;
Identify the top 5 ZIP codes with the highest number of reported food insecurity cases, partitioned by month?
CREATE TABLE food_insecurity (id INT,zip TEXT,cases INT,date DATE); INSERT INTO food_insecurity (id,zip,cases,date) VALUES (1,'12345',100,'2020-01-01'),(2,'67890',120,'2020-01-02');
SELECT zip, SUM(cases) OVER (PARTITION BY EXTRACT(MONTH FROM date)) as monthly_cases, DENSE_RANK() OVER (ORDER BY SUM(cases) DESC) as rank FROM food_insecurity WHERE EXTRACT(YEAR FROM date) = 2020 GROUP BY zip, EXTRACT(MONTH FROM date) ORDER BY monthly_cases DESC LIMIT 5;
What is the daily water consumption of the mining operation with the lowest daily water consumption?
CREATE TABLE daily_water_consumption (operation TEXT,date DATE,consumption FLOAT); INSERT INTO daily_water_consumption (operation,date,consumption) VALUES ('Operation A','2021-01-01',5000),('Operation B','2021-01-01',6000),('Operation A','2021-01-02',5500),('Operation B','2021-01-02',6500);
SELECT operation, MIN(consumption) FROM daily_water_consumption GROUP BY operation;
Which designers have the highest and lowest average garment prices for plus-size clothing?
CREATE TABLE designers (designer_id INT,designer_name VARCHAR(255));CREATE TABLE garments (garment_id INT,garment_name VARCHAR(255),designer_id INT,price DECIMAL(10,2),size VARCHAR(10));
SELECT d.designer_name, AVG(g.price) AS avg_price FROM garments g JOIN designers d ON g.designer_id = d.designer_id WHERE g.size = 'plus-size' GROUP BY d.designer_name ORDER BY avg_price DESC, d.designer_name ASC LIMIT 1; SELECT d.designer_name, AVG(g.price) AS avg_price FROM garments g JOIN designers d ON g.designer_...
What's the average viewership of late-night talk shows in 2021?
CREATE TABLE talk_shows (id INT,title VARCHAR(255),year INT,average_viewership INT); INSERT INTO talk_shows (id,title,year,average_viewership) VALUES (1,'The Late Show with Stephen Colbert',2021,3200000),(2,'The Tonight Show Starring Jimmy Fallon',2021,2800000);
SELECT AVG(average_viewership) FROM talk_shows WHERE year = 2021;
What is the maximum number of visitors in a day for Sydney, Australia, in the last 6 months?
CREATE TABLE if not exists cities (city_id INT,name TEXT,country TEXT); INSERT INTO cities (city_id,name,country) VALUES (1,'Sydney','Australia'); CREATE TABLE if not exists visit_logs (log_id INT,visitor_id INT,city_id INT,visit_date DATE); INSERT INTO visit_logs (log_id,visitor_id,city_id,visit_date) VALUES (1,1,1,'2...
SELECT MAX(visits_per_day) FROM (SELECT visit_date, COUNT(DISTINCT visitor_id) AS visits_per_day FROM visit_logs JOIN cities ON visit_logs.city_id = cities.city_id WHERE cities.name = 'Sydney' AND visit_date >= (CURRENT_DATE - INTERVAL '6 months') GROUP BY visit_date) AS subquery;
What is the average productivity of workers per mining site, grouped by country, for gold mines that have more than 50 employees?
CREATE TABLE gold_mine (site_id INT,country VARCHAR(50),num_employees INT); INSERT INTO gold_mine (site_id,country,num_employees) VALUES (1,'Canada',60),(2,'USA',75),(3,'Mexico',40),(4,'Canada',80),(5,'USA',35);
SELECT country, AVG(productivity) as avg_productivity FROM gold_mine WHERE num_employees > 50 GROUP BY country;