instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Show the minimum quantity of products in the 'gifts' category
CREATE TABLE products (product_id INT,category VARCHAR(20),quantity INT); INSERT INTO products (product_id,category,quantity) VALUES (1,'gifts',5),(2,'gifts',10),(3,'gifts',15);
SELECT MIN(quantity) FROM products WHERE category = 'gifts';
What is the average number of satellites owned by countries with space programs?
CREATE TABLE countries (id INTEGER,name TEXT,num_satellites INTEGER); INSERT INTO countries (id,name,num_satellites) VALUES (1,'USA',1500),(2,'Russia',1200),(3,'China',800),(4,'India',300),(5,'Japan',250),(6,'Germany',150),(7,'France',120),(8,'Italy',100); CREATE TABLE space_programs (id INTEGER,country TEXT); INSERT INTO space_programs (id,country) VALUES (1,'USA'),(2,'Russia'),(3,'China'),(4,'India'),(5,'Japan'),(6,'Germany'),(7,'France'),(8,'Italy');
SELECT AVG(num_satellites) FROM countries INNER JOIN space_programs ON countries.name = space_programs.country;
What is the maximum number of space missions by astronauts from Japan?
CREATE TABLE Astronauts (AstronautId INT,Name VARCHAR(50),Age INT,Nationality VARCHAR(50),SpaceMissions INT); INSERT INTO Astronauts (AstronautId,Name,Age,Nationality,SpaceMissions) VALUES (5,'Soichi Noguchi',55,'Japan',6);
SELECT Nationality, MAX(SpaceMissions) FROM Astronauts WHERE Nationality = 'Japan';
What is the total mass of space debris larger than 10 cm in Low Earth Orbit (LEO)?
CREATE TABLE space_debris(id INT,name VARCHAR(255),launch_date DATE,launch_site VARCHAR(255),orbit VARCHAR(255),mass FLOAT); INSERT INTO space_debris VALUES (1,'Fengyun 1C','1999-11-15','Xichang','LEO',1500); INSERT INTO space_debris VALUES (2,'COSMOS 2421','2001-11-25','Plesetsk','LEO',850); INSERT INTO space_debris VALUES (3,'COSMOS 2251','1993-07-16','Plesetsk','LEO',900);
SELECT SUM(mass) FROM space_debris WHERE orbit = 'LEO' AND mass > 10;
Which spacecraft have astronauts with Texas residency flown?
CREATE TABLE Spacecraft (Id INT,Name VARCHAR(50),ManufacturerId INT); CREATE TABLE Astronaut (Id INT,Name VARCHAR(50),SpacecraftId INT,Residence VARCHAR(50));
SELECT DISTINCT s.Name FROM Spacecraft s JOIN Astronaut a ON s.Id = a.SpacecraftId WHERE a.Residence = 'Texas';
Calculate the average ticket price for each sports team
CREATE TABLE sports_teams (team_id INT,team_name VARCHAR(50)); INSERT INTO sports_teams (team_id,team_name) VALUES (1,'TeamA'),(2,'TeamB'); CREATE TABLE ticket_sales (ticket_id INT,team_id INT,price DECIMAL(5,2)); INSERT INTO ticket_sales (ticket_id,team_id,price) VALUES (1,1,75.50),(2,1,85.20),(3,2,65.00),(4,2,75.00);
SELECT s.team_name, AVG(t.price) FROM sports_teams s INNER JOIN ticket_sales t ON s.team_id = t.team_id GROUP BY s.team_name;
What are the total ticket sales for the warriors in the ticket_sales table?
CREATE TABLE ticket_sales (team_name TEXT,sale_date DATE,quantity_sold INTEGER);
SELECT SUM(quantity_sold) FROM ticket_sales WHERE team_name = 'warriors';
Which electric vehicles have the highest and lowest adoption rates in 'london'?
CREATE TABLE if not exists vehicle_types (vehicle_type varchar(20)); INSERT INTO vehicle_types (vehicle_type) VALUES ('tesla'),('nissan'),('bmw'); CREATE TABLE if not exists adoption_rates (vehicle_type varchar(20),city varchar(20),adoption_rate float); INSERT INTO adoption_rates (vehicle_type,city,adoption_rate) VALUES ('tesla','london',45.2),('nissan','london',30.1),('bmw','london',24.7),('tesla','london',45.5),('nissan','london',30.3),('bmw','london',24.9);
SELECT vehicle_type, MAX(adoption_rate) as highest_rate, MIN(adoption_rate) as lowest_rate FROM adoption_rates WHERE city = 'london' GROUP BY vehicle_type;
What is the total revenue for eco-friendly footwear in Germany in Q2 2021?
CREATE TABLE sales (item_code VARCHAR(20),item_name VARCHAR(50),category VARCHAR(50),country VARCHAR(50),sale_date DATE,revenue DECIMAL(10,2),is_eco_friendly BOOLEAN);
SELECT SUM(revenue) as total_revenue FROM sales WHERE category LIKE '%footwear%' AND country = 'Germany' AND is_eco_friendly = TRUE AND sale_date BETWEEN '2021-04-01' AND '2021-06-30';
What is the average policy duration for policyholders in the West region with a risk score between 600 and 800?
CREATE TABLE Policyholders (PolicyID INT,RiskScore INT,Region VARCHAR(10),PolicyDuration INT); INSERT INTO Policyholders VALUES (1,700,'West',36); INSERT INTO Policyholders VALUES (2,400,'East',24);
SELECT AVG(p.PolicyDuration) as AvgPolicyDuration FROM Policyholders p WHERE p.Region = 'West' AND p.RiskScore BETWEEN 600 AND 800;
What is the total number of members in 'manufacturing_unions'?
CREATE TABLE manufacturing_unions.members (id INT,name TEXT,union_member BOOLEAN);
SELECT COUNT(*) FROM manufacturing_unions.members WHERE union_member = TRUE;
What is the total number of workers in each industry?
CREATE TABLE if not exists industry (industry_id INT,industry_name TEXT,total_workers INT); INSERT INTO industry (industry_id,industry_name,total_workers) VALUES (1,'manufacturing',5000),(2,'technology',7000),(3,'healthcare',6000),(4,'finance',4000),(5,'retail',3000);
SELECT industry_name, SUM(total_workers) FROM industry GROUP BY industry_name;
What is the number of gasoline vehicles sold in 'Florida' in the 'sales' table?
CREATE TABLE sales (region VARCHAR(10),vehicle_type VARCHAR(10),vehicle_count INT); INSERT INTO sales VALUES ('California','electric',5000),('Texas','gasoline',6000),('Florida','gasoline',3000),('California','hybrid',5500),('Texas','electric',6500),('Florida','electric',2500);
SELECT SUM(vehicle_count) FROM sales WHERE region = 'Florida' AND vehicle_type = 'gasoline';
List all unique types of cargo loaded onto vessels in the Atlantic region.
CREATE TABLE vessels (id INT,name VARCHAR(255),region VARCHAR(255)); INSERT INTO vessels (id,name,region) VALUES (1,'VesselA','Pacific'),(2,'VesselB','Atlantic'),(3,'VesselC','Pacific'); CREATE TABLE cargo (id INT,vessel_id INT,cargo_type VARCHAR(255)); INSERT INTO cargo (id,vessel_id,cargo_type) VALUES (1,1,'Fuel'),(2,1,'Containers'),(3,2,'Fuel'),(4,3,'Containers');
SELECT DISTINCT cargo_type FROM cargo c JOIN vessels v ON c.vessel_id = v.id WHERE v.region = 'Atlantic';
What is the average cargo quantity per vessel for each vessel type?
CREATE TABLE Vessels (Id INT,Name VARCHAR(50),Type VARCHAR(50),Flag VARCHAR(50)); INSERT INTO Vessels (Id,Name,Type,Flag) VALUES (1,'Aurelia','Tanker','Panama'); INSERT INTO Vessels (Id,Name,Type,Flag) VALUES (2,'Barracuda','Bulk Carrier','Marshall Islands'); CREATE TABLE Cargo (Id INT,VesselId INT,CargoType VARCHAR(50),Quantity INT); INSERT INTO Cargo (Id,VesselId,CargoType,Quantity) VALUES (1,1,'Oil',5000); INSERT INTO Cargo (Id,VesselId,CargoType,Quantity) VALUES (2,2,'Coal',8000);
SELECT Vessels.Type, AVG(Cargo.Quantity) as AverageCargoQuantity FROM Cargo JOIN Vessels ON Cargo.VesselId = Vessels.Id GROUP BY Vessels.Type;
What was the average speed for vessels in the Arctic Circle in July 2020?
CREATE TABLE vessels(id INT,name VARCHAR(100),region VARCHAR(50));CREATE TABLE speeds(id INT,vessel_id INT,speed FLOAT,speed_date DATE);
SELECT AVG(speed) FROM speeds JOIN vessels ON speeds.vessel_id = vessels.id WHERE region = 'Arctic Circle' AND speed_date BETWEEN '2020-07-01' AND '2020-07-31';
How many recycling plants in Canada process exactly 5 types of waste?
CREATE TABLE recycling_plants (name TEXT,country TEXT,waste_types INTEGER); INSERT INTO recycling_plants (name,country,waste_types) VALUES ('Recycling Plant 1','Canada',6),('Recycling Plant 2','Canada',4),('Recycling Plant 3','Canada',5),('Recycling Plant 4','Canada',5),('Recycling Plant 5','Canada',3);
SELECT COUNT(*) FROM recycling_plants WHERE country = 'Canada' AND waste_types = 5;
What is the quarterly recycling rate for 'Plastic' in 'Australia' from Q1 2020 to Q2 2020?
CREATE TABLE australia_recycling_rates (quarter VARCHAR(10),year INT,material VARCHAR(20),recycling_rate DECIMAL(5,2)); INSERT INTO australia_recycling_rates (quarter,year,material,recycling_rate) VALUES ('Q1',2020,'Plastic',0.35),('Q2',2020,'Plastic',0.40);
SELECT quarter, recycling_rate FROM australia_recycling_rates WHERE material = 'Plastic' AND (year = 2020 AND quarter IN ('Q1', 'Q2'));
Add a new record for a member with id 27, name 'Fatima Ahmed' and email '[email protected]' into the members table if no such member already exists
CREATE TABLE members (id INT,name VARCHAR(50),email VARCHAR(50));
INSERT INTO members (id, name, email) SELECT 27, 'Fatima Ahmed', '[email protected]' FROM dual WHERE NOT EXISTS (SELECT * FROM members WHERE id = 27);
Calculate the total number of steps taken by users in January 2021.
CREATE TABLE DailySteps (user_id INT,steps INT,activity_date DATE); INSERT INTO DailySteps (user_id,steps,activity_date) VALUES (1,12000,'2021-01-01'),(2,8000,'2021-01-02'),(3,15000,'2021-01-03');
SELECT SUM(steps) FROM DailySteps WHERE activity_date BETWEEN '2021-01-01' AND '2021-01-31';
How many creative AI applications were developed in the 'americas' region in 2022?
CREATE TABLE creative_ai (region TEXT,year INTEGER,applications INTEGER); INSERT INTO creative_ai (region,year,applications) VALUES ('americas',2022,25),('europe',2022,30),('asia',2022,35);
SELECT SUM(applications) FROM creative_ai WHERE region = 'americas' AND year = 2022;
How many agricultural innovation projects were completed in India between 2015 and 2019?'
CREATE TABLE agricultural_innovation_projects (id INT,country VARCHAR(255),start_year INT,end_year INT,completed INT); INSERT INTO agricultural_innovation_projects (id,country,start_year,end_year,completed) VALUES (1,'India',2015,2019,1);
SELECT COUNT(*) FROM agricultural_innovation_projects WHERE country = 'India' AND start_year <= 2019 AND end_year >= 2015 AND completed = 1;
What is the minimum investment per project in the 'infrastructure_projects' table?
CREATE TABLE infrastructure_projects (id INT,project VARCHAR(50),investment FLOAT); INSERT INTO infrastructure_projects (id,project,investment) VALUES (1,'Road Construction',25000.0); INSERT INTO infrastructure_projects (id,project,investment) VALUES (2,'Water Supply',30000.0); INSERT INTO infrastructure_projects (id,project,investment) VALUES (3,'Electricity Grid',40000.0);
SELECT MIN(investment) FROM infrastructure_projects;
How many tickets were sold for cultural events in Q1 2022?
CREATE TABLE Events (EventID INT,EventType VARCHAR(50),StartDate DATE,EndDate DATE); INSERT INTO Events (EventID,EventType,StartDate,EndDate) VALUES (1,'Dance Performance','2022-04-01','2022-04-03'),(2,'Theater Performance','2022-01-01','2022-01-31'),(3,'Cultural Festival','2022-01-15','2022-01-30'); CREATE TABLE Tickets (TicketID INT,EventID INT,Quantity INT); INSERT INTO Tickets (TicketID,EventID,Quantity) VALUES (1,1,100),(2,2,200),(3,3,150);
SELECT SUM(Quantity) FROM Events INNER JOIN Tickets ON Events.EventID = Tickets.EventID WHERE Events.EventType = 'Cultural Festival' AND QUARTER(StartDate) = 1;
What is the maximum marketing cost for TV shows in the 'Drama' genre?
CREATE TABLE TVShowMarketing (show_id INT,genre VARCHAR(255),marketing_cost DECIMAL(5,2)); INSERT INTO TVShowMarketing (show_id,genre,marketing_cost) VALUES (1,'Drama',1000000.00),(2,'Comedy',750000.00),(3,'Drama',1500000.00);
SELECT MAX(marketing_cost) FROM TVShowMarketing WHERE genre = 'Drama';
Delete the permit with number 2021-020
CREATE TABLE building_permits (permit_number TEXT,contractor TEXT); INSERT INTO building_permits (permit_number,contractor) VALUES ('2021-020','Contractor Name');
WITH cte AS (DELETE FROM building_permits WHERE permit_number = '2021-020') SELECT * FROM cte;
How many construction projects were completed in each month of 2021?
CREATE TABLE project_timeline (id INT,project VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO project_timeline (id,project,start_date,end_date) VALUES (1,'Office Building','2021-01-01','2021-04-30'),(2,'Residential Apartments','2021-03-01','2021-08-01'),(3,'School','2021-06-15','2021-10-15');
SELECT MONTH(start_date) AS month, COUNT(*) AS projects FROM project_timeline WHERE YEAR(start_date) = 2021 AND end_date IS NOT NULL GROUP BY month;
What is the total revenue for the top 5 dispensaries in Colorado in Q1 of 2023?
CREATE TABLE dispensary_sales (id INT,dispensary_name VARCHAR(255),state VARCHAR(255),revenue DECIMAL(10,2),sale_date DATE);
SELECT SUM(revenue) FROM dispensary_sales WHERE state = 'Colorado' AND sale_date BETWEEN '2023-01-01' AND '2023-03-31' AND dispensary_name IN (SELECT dispensary_name FROM dispensary_sales WHERE state = 'Colorado' AND sale_date BETWEEN '2023-01-01' AND '2023-03-31' GROUP BY dispensary_name ORDER BY SUM(revenue) DESC LIMIT 5);
Which strain was the best seller in Colorado in 2021?
CREATE TABLE sales (id INT,state VARCHAR(50),year INT,strain VARCHAR(50),quantity INT); INSERT INTO sales (id,state,year,strain,quantity) VALUES (1,'Colorado',2021,'Blue Dream',500),(2,'Colorado',2021,'Gorilla Glue',700),(3,'Colorado',2022,'Blue Dream',800);
SELECT strain, SUM(quantity) as total_quantity FROM sales WHERE state = 'Colorado' AND year = 2021 GROUP BY strain ORDER BY total_quantity DESC LIMIT 1;
What is the success rate of cases handled by attorneys who have passed the bar exam in the state where they practice?
CREATE TABLE Cases (CaseID int,AttorneyID int,Outcome text); INSERT INTO Cases (CaseID,AttorneyID,Outcome) VALUES (1,1,'won'); CREATE TABLE Attorneys (AttorneyID int,State text,BarPassed text); INSERT INTO Attorneys (AttorneyID,State,BarPassed) VALUES (1,'California','yes');
SELECT AVG(CASE WHEN Outcome = 'won' THEN 1.0 ELSE 0.0 END) as SuccessRate FROM Cases C INNER JOIN Attorneys A ON C.AttorneyID = A.AttorneyID WHERE A.BarPassed = 'yes';
What is the total number of clients for each attorney?
CREATE TABLE clients (client_id INT PRIMARY KEY,attorney_id INT,client_name VARCHAR(50),case_opened_date DATE);
SELECT attorney_id, COUNT(client_id) FROM clients GROUP BY attorney_id;
Update the climate communication ROI for projects in Oceania with the latest regional average.
CREATE TABLE climate_communication (project VARCHAR(50),country VARCHAR(50),roi FLOAT,date DATE); CREATE TABLE regional_roi (region VARCHAR(50),roi FLOAT,date DATE); INSERT INTO climate_communication (project,country,roi,date) VALUES ('Climate Change Guide','Australia',1.3,'2021-01-01'); INSERT INTO climate_communication (project,country,roi,date) VALUES ('Ocean Conservation','New Zealand',1.2,'2021-01-01'); INSERT INTO regional_roi (region,roi,date) VALUES ('Oceania',1.25,'2021-01-01');
UPDATE climate_communication SET roi = (SELECT roi FROM regional_roi WHERE region = 'Oceania' AND climate_communication.date = regional_roi.date) WHERE country IN ('Australia', 'New Zealand');
What is the average annual rainfall in Asia for the last 5 years?
CREATE TABLE rainfall_asia (country VARCHAR(20),year INT,rainfall DECIMAL(5,2)); INSERT INTO rainfall_asia VALUES ('AS',2015,12.1),('AS',2016,12.3),('AS',2017,12.5),('AS',2018,12.7),('AS',2019,12.9);
SELECT AVG(rainfall) FROM rainfall_asia WHERE country = 'AS' AND year BETWEEN 2015 AND 2019;
What is the number of 'climate communication' campaigns launched in 'Asia' in '2023' from the 'communication' table?
CREATE TABLE communication (region VARCHAR(255),campaigns INT,year INT);
SELECT COUNT(*) FROM communication WHERE region = 'Asia' AND year = 2023;
What is the maximum age of patients with HIV in Australia?
CREATE TABLE Patients (ID INT,Gender VARCHAR(10),Age INT,Disease VARCHAR(20),Country VARCHAR(30),Diagnosis_Date DATE); INSERT INTO Patients (ID,Gender,Age,Disease,Country,Diagnosis_Date) VALUES (1,'Male',50,'HIV','Australia','2020-02-01');
SELECT MAX(Age) FROM Patients WHERE Disease = 'HIV' AND Country = 'Australia';
What is the sum of funding amounts for companies founded in the last 5 years that have a female CEO?
CREATE TABLE companies (id INT,name TEXT,founding_date DATE,CEO_gender TEXT); INSERT INTO companies (id,name,founding_date,CEO_gender) VALUES (1,'BioHealth','2019-01-01','Female');
SELECT SUM(funding_amount) FROM funding_records JOIN companies ON funding_records.company_id = companies.id WHERE companies.founding_date >= DATEADD(year, -5, CURRENT_DATE) AND companies.CEO_gender = 'Female';
List all startups that have not raised any funding
CREATE TABLE startups (id INT,name TEXT,funding_raised INT); CREATE TABLE investments (id INT,startup_id INT,funding_amount INT);
SELECT startups.name FROM startups LEFT JOIN investments ON startups.id = investments.startup_id WHERE investments.funding_amount IS NULL;
Get the total number of inclusion efforts in the InclusionEfforts table for a specific location.
CREATE TABLE InclusionEfforts (effortID INT,effortType VARCHAR(50),location VARCHAR(50),effortStatus VARCHAR(50));
SELECT location, COUNT(*) FROM InclusionEfforts WHERE effortStatus = 'Completed' GROUP BY location;
List all instructors and number of students they support with accommodations.
CREATE TABLE Instructors (id INT,name VARCHAR(50),title VARCHAR(50));
SELECT i.name, COUNT(a.student_id) as supported_students FROM Instructors i JOIN Accommodations a ON i.id = a.instructor_id GROUP BY i.name;
What is the total number of museum visitors from historically underrepresented communities in the last 2 years?
CREATE TABLE MuseumVisitors (visit_date DATE,community_type VARCHAR(50),num_visitors INT); INSERT INTO MuseumVisitors (visit_date,community_type,num_visitors) VALUES ('2020-01-01','African American',120),('2020-01-02','African American',150),('2020-01-03','Latinx',80),('2021-01-04','Latinx',90),('2021-02-01','Native American',120),('2021-02-02','Native American',150),('2021-03-03','Asian Pacific Islander',80),('2021-03-04','Asian Pacific Islander',90);
SELECT SUM(num_visitors) FROM MuseumVisitors WHERE community_type IN ('African American', 'Latinx', 'Native American', 'Asian Pacific Islander') AND visit_date >= DATEADD(YEAR, -2, GETDATE());
Generate a table 'threat_analysis' to store detailed analysis of threat intelligence metrics
CREATE TABLE threat_analysis (id INT PRIMARY KEY,analysis_date DATE,threat_level VARCHAR(10),analysis TEXT);
CREATE TABLE threat_analysis (id INT PRIMARY KEY, analysis_date DATE, threat_level VARCHAR(10), analysis TEXT);
What is the total defense spending by the United States for each year from 2015 to 2020?
CREATE TABLE defense_spending (year INT,amount DECIMAL); INSERT INTO defense_spending (year,amount) VALUES (2015,600),(2016,610),(2017,620),(2018,630),(2019,640),(2020,650);
SELECT year, SUM(amount) FROM defense_spending WHERE year BETWEEN 2015 AND 2020 GROUP BY year;
Show the total assets under management (AUM) for each investment strategy.
CREATE TABLE investment_strategies (strategy_id INT,strategy VARCHAR(20)); INSERT INTO investment_strategies (strategy_id,strategy) VALUES (1,'Conservative'),(2,'Moderate'),(3,'Aggressive'); CREATE TABLE client_strategy (client_id INT,strategy_id INT); INSERT INTO client_strategy (client_id,strategy_id) VALUES (1,2),(2,3),(3,1);
SELECT cs.strategy, SUM(value) AS total_aum FROM client_strategy cs JOIN clients c ON cs.client_id = c.client_id JOIN assets a ON c.client_id = a.client_id GROUP BY cs.strategy;
Compare the prevalence of diabetes among Indigenous populations in rural and urban areas.
CREATE TABLE patients (id INT,age INT,diagnosis VARCHAR(20),ethnicity VARCHAR(20),residence VARCHAR(10)); INSERT INTO patients (id,age,diagnosis,ethnicity,residence) VALUES (1,65,'diabetes','Indigenous','rural'),(2,45,'asthma','Latino','urban'),(3,70,'diabetes','Indigenous','urban');
SELECT (SELECT COUNT(*) FROM patients WHERE diagnosis = 'diabetes' AND ethnicity = 'Indigenous' AND residence = 'rural') / (SELECT COUNT(*) FROM patients WHERE ethnicity = 'Indigenous' AND residence = 'rural') AS rural_diabetes_prevalence, (SELECT COUNT(*) FROM patients WHERE diagnosis = 'diabetes' AND ethnicity = 'Indigenous' AND residence = 'urban') / (SELECT COUNT(*) FROM patients WHERE ethnicity = 'Indigenous' AND residence = 'urban') AS urban_diabetes_prevalence;
What is the average number of military personnel per base in 'Africa' and 'South America'?
CREATE TABLE MilitaryBases (ID INT,BaseName VARCHAR(50),Country VARCHAR(50),Personnel INT); INSERT INTO MilitaryBases (ID,BaseName,Country,Personnel) VALUES (1,'Base1','Africa',500); INSERT INTO MilitaryBases (ID,BaseName,Country,Personnel) VALUES (2,'Base2','South America',700); INSERT INTO MilitaryBases (ID,BaseName,Country,Personnel) VALUES (3,'Base3','Africa',600);
SELECT AVG(Personnel) FROM MilitaryBases WHERE Country IN ('Africa', 'South America');
What is the total revenue for each genre of music in the United States for the year 2020?
CREATE TABLE music_genres (genre VARCHAR(255),country VARCHAR(255),revenue FLOAT); INSERT INTO music_genres (genre,country,revenue) VALUES ('Pop','USA',10000.0),('Rock','USA',8000.0),('Jazz','USA',5000.0);
SELECT genre, SUM(revenue) as total_revenue FROM music_genres WHERE country = 'USA' AND YEAR(event_date) = 2020 GROUP BY genre;
How many programs were successfully completed in the 'Programs' table?
CREATE TABLE Programs (ProgramID INT,ProgramName VARCHAR(50),Status VARCHAR(10)); INSERT INTO Programs (ProgramID,ProgramName,Status) VALUES (1,'Education','Completed'),(2,'Health','In-Progress');
SELECT COUNT(*) FROM Programs WHERE Status = 'Completed';
What is the total budget allocated for each program in the year 2021?
CREATE TABLE Programs (ProgramID int,ProgramName varchar(255),Budget decimal(10,2)); INSERT INTO Programs VALUES (1,'Education',50000),(2,'Healthcare',75000),(3,'Environment',60000);
SELECT ProgramName, SUM(Budget) OVER (PARTITION BY ProgramName) as TotalBudget FROM Programs WHERE YEAR(ProgramStartDate) = 2021;
What is the total number of volunteer signups in each region in 2028, including any duplicates?
CREATE TABLE Volunteers (VolunteerID INT,Name TEXT,Region TEXT);CREATE TABLE VolunteerSignups (SignupID INT,VolunteerID INT,SignupDate DATE);
SELECT V.Region, COUNT(V.VolunteerID) as TotalSignups FROM Volunteers V JOIN VolunteerSignups S ON V.VolunteerID = S.VolunteerID WHERE YEAR(SignupDate) = 2028 GROUP BY V.Region;
What is the percentage of teachers who have completed more than 20 hours of professional development?
CREATE TABLE teachers (teacher_id INT,teacher_name TEXT,hours INT); INSERT INTO teachers VALUES (1,'Jane Doe',30); INSERT INTO teachers VALUES (2,'John Smith',15); INSERT INTO teachers VALUES (3,'Mary Johnson',40); INSERT INTO teachers VALUES (4,'David Kim',25);
SELECT 100.0 * AVG(CASE WHEN hours > 20 THEN 1 ELSE 0 END) as percentage FROM teachers;
What is the minimum salary for employees who joined the company in the summer?
CREATE TABLE Employees (EmployeeID int,HireDate date,Salary decimal(10,2)); INSERT INTO Employees (EmployeeID,HireDate,Salary) VALUES (1,'2021-06-01',70000.00),(2,'2021-07-15',75000.00),(3,'2021-08-31',65000.00);
SELECT MIN(Salary) FROM Employees WHERE MONTH(HireDate) IN (6, 7, 8);
What is the average age of cricket players in the 'cricket_players' table?
CREATE TABLE cricket_players (player_id INT,name VARCHAR(50),age INT,country VARCHAR(50)); INSERT INTO cricket_players (player_id,name,age,country) VALUES (1,'Virat Kohli',33,'India'); INSERT INTO cricket_players (player_id,name,age,country) VALUES (2,'Joe Root',31,'England');
SELECT AVG(age) FROM cricket_players;
Who are the top 3 goal scorers in the FIFA World Cup?
CREATE TABLE world_cup_goals (player_name TEXT,goals INT); INSERT INTO world_cup_goals (player_name,goals) VALUES ('Miroslav Klose',16),('Ronaldo',15),('Gerd Muller',14);
SELECT player_name, goals FROM world_cup_goals ORDER BY goals DESC LIMIT 3;
Who has the highest number of wins as a coach for each team in a season?
CREATE TABLE Coach (CoachID int,CoachName varchar(50),TeamID int); CREATE TABLE Match (MatchID int,HomeTeamID int,AwayTeamID int,HomeTeamResult varchar(5)); INSERT INTO Coach (CoachID,CoachName,TeamID) VALUES (1,'Jose Mourinho',1),(2,'Pep Guardiola',1),(3,'Jurgen Klopp',2),(4,'Mauricio Pochettino',2); INSERT INTO Match (MatchID,HomeTeamID,AwayTeamID,HomeTeamResult) VALUES (1,1,2,'Win'),(2,2,1,'Loss'),(3,1,2,'Draw'),(4,2,1,'Win'),(5,1,3,'Win');
SELECT c.TeamID, c.CoachName, COUNT(CASE WHEN h.HomeTeamResult = 'Win' THEN 1 END) + COUNT(CASE WHEN a.HomeTeamResult = 'Win' THEN 1 END) AS Wins FROM Coach c LEFT JOIN Match h ON c.TeamID = h.HomeTeamID AND h.HomeTeamResult = 'Win' LEFT JOIN Match a ON c.TeamID = a.AwayTeamID AND a.HomeTeamResult = 'Win' GROUP BY c.TeamID, c.CoachName ORDER BY Wins DESC;
What is the average donation amount for each age group?
CREATE TABLE DonorAges (Id INT,AgeGroup VARCHAR(20),DonationAmount DECIMAL(10,2)); INSERT INTO DonorAges (Id,AgeGroup,DonationAmount) VALUES (1,'18-35',100.00),(2,'36-50',150.00),(3,'51-65',75.00),(4,'18-35',50.00);
SELECT AgeGroup, AVG(DonationAmount) FROM DonorAges GROUP BY AgeGroup;
List all social good technology programs launched in the first half of the year 2022.
CREATE TABLE Social_Good_Tech (Month INT,Program VARCHAR(255)); INSERT INTO Social_Good_Tech (Month,Program) VALUES (1,'EduTech'),(2,'HealthTech'),(3,'AgriTech'),(4,'FinTech'),(5,'EduTech'),(6,'HealthTech');
SELECT DISTINCT Program FROM Social_Good_Tech WHERE Month BETWEEN 1 AND 6;
What is the average fare collected per trip for buses in the city of Seattle?
CREATE TABLE buses (id INT,city VARCHAR(20)); INSERT INTO buses (id,city) VALUES (1,'Seattle'),(2,'New York'); CREATE TABLE fares (id INT,bus_id INT,fare DECIMAL(5,2)); INSERT INTO fares (id,bus_id,fare) VALUES (1,1,3.50),(2,1,3.75),(3,2,2.00);
SELECT AVG(f.fare) FROM fares f JOIN buses b ON f.bus_id = b.id WHERE b.city = 'Seattle';
What are the top 5 most active cities in terms of user posts on the social media platform, MyTweet?
CREATE TABLE cities (city_id INT,city_name VARCHAR(255));CREATE TABLE user_posts (post_id INT,user_id INT,city_id INT,post_text VARCHAR(255)); INSERT INTO cities VALUES (1,'New York'),(2,'Los Angeles'),(3,'Chicago'),(4,'Houston'),(5,'Phoenix'); INSERT INTO user_posts VALUES (1,1,1,'Hello from NY'),(2,2,2,'LA is amazing'),(3,3,3,'Chicago deep dish is the best'),(4,4,4,'I love Houston'),(5,5,5,'Phoenix is hot');
SELECT c.city_name, COUNT(up.city_id) as post_count FROM cities c INNER JOIN user_posts up ON c.city_id = up.city_id GROUP BY c.city_name ORDER BY post_count DESC LIMIT 5;
Who were the top 3 content creators in terms of likes received on their posts in January 2022?
CREATE SCHEMA content; CREATE TABLE creators(creator_id INT,name VARCHAR(255),total_likes INT); INSERT INTO creators (creator_id,name,total_likes) VALUES (1,'Alice',5000); INSERT INTO creators (creator_id,name,total_likes) VALUES (2,'Bob',7000);
SELECT name, SUM(total_likes) AS total_likes_january FROM content.creators WHERE MONTH(created_date) = 1 GROUP BY name ORDER BY total_likes_january DESC LIMIT 3;
What is the average financial wellbeing score in Q2 2022 for customers with a Shariah-compliant finance account?
CREATE TABLE shariah_compliant_customers (customer_id INT,shariah_compliant_account BOOLEAN,financial_wellbeing_score INT,wellbeing_assessment_date DATE); INSERT INTO shariah_compliant_customers (customer_id,shariah_compliant_account,financial_wellbeing_score,wellbeing_assessment_date) VALUES (1,true,70,'2022-04-01'),(2,false,65,'2022-04-05'),(3,true,80,'2022-05-01'),(4,false,60,'2022-05-10');
SELECT AVG(financial_wellbeing_score) FROM shariah_compliant_customers WHERE shariah_compliant_account = true AND wellbeing_assessment_date BETWEEN '2022-04-01' AND '2022-06-30';
What is the maximum amount invested by a client in Shariah-compliant funds?
CREATE TABLE shariah_compliant_funds_investments (investment_id INT,client_id INT,amount_invested INT); INSERT INTO shariah_compliant_funds_investments (investment_id,client_id,amount_invested) VALUES (1,1,5000),(2,2,7000),(3,3,8000); CREATE TABLE clients (client_id INT,client_name TEXT); INSERT INTO clients (client_id,client_name) VALUES (1,'Ahmed'),(2,'Fatima'),(3,'Hamza');
SELECT clients.client_name, MAX(shariah_compliant_funds_investments.amount_invested) FROM clients JOIN shariah_compliant_funds_investments ON clients.client_id = shariah_compliant_funds_investments.client_id;
What is the total quantity of dairy products sold in each country?
CREATE TABLE Countries (CountryID INT,CountryName VARCHAR(50));CREATE TABLE Products (ProductID INT,ProductName VARCHAR(50),Dairy BOOLEAN,QuantitySold INT); INSERT INTO Countries VALUES (1,'USA'),(2,'Canada'); INSERT INTO Products VALUES (1,'Cheese',true,100),(2,'Milk',true,150),(3,'Eggs',true,200),(4,'Tofu',false,50);
SELECT c.CountryName, p.ProductName, SUM(p.QuantitySold) as TotalQuantitySold FROM Countries c JOIN Products p ON c.CountryID = 1 GROUP BY c.CountryName, p.ProductName HAVING p.Dairy = true;
What are the total sales and quantity of goods sold by each salesperson, grouped by city?
CREATE TABLE salesperson (id INT,name TEXT,city TEXT); CREATE TABLE sales (id INT,salesperson_id INT,product TEXT,quantity INT,total_sales FLOAT);
SELECT s.name, s.city, SUM(s.total_sales) as total_sales, SUM(s.quantity) as total_quantity FROM sales s JOIN salesperson sp ON s.salesperson_id = sp.id GROUP BY s.city, s.name;
Delete all records in the public_parks table where the number of visitors is less than 5000000?
CREATE TABLE public_parks (park_name TEXT,state TEXT,visitors INT); INSERT INTO public_parks VALUES ('Central Park','New York',40000000); INSERT INTO public_parks VALUES ('Golden Gate Park','California',13000000); INSERT INTO public_parks VALUES ('Lincoln Park','Illinois',20000000); INSERT INTO public_parks VALUES ('Balboa Park','California',12000000); INSERT INTO public_parks VALUES ('Lake Park','Wisconsin',3000000);
DELETE FROM public_parks WHERE visitors < 5000000;
What is the total number of open data initiatives in the healthcare sector?
CREATE TABLE open_data_initiatives (id INT,sector TEXT); INSERT INTO open_data_initiatives (id,sector) VALUES (1,'Education'),(2,'Healthcare'),(3,'Healthcare'),(4,'Education');
SELECT COUNT(*) FROM open_data_initiatives WHERE sector = 'Healthcare';
What is the average GPA of graduate students in the Computer Science department?
CREATE TABLE students (id INT,department VARCHAR(255),GPA DECIMAL(3,2)); INSERT INTO students (id,department,GPA) VALUES (1,'Computer Science',3.8),(2,'Computer Science',3.6),(3,'Mathematics',3.9);
SELECT AVG(GPA) FROM students WHERE department = 'Computer Science';
List the number of mental health appointments for each gender, in descending order.
CREATE TABLE Gender (ID INT,Gender TEXT); INSERT INTO Gender (ID,Gender) VALUES (1,'Male'); INSERT INTO Gender (ID,Gender) VALUES (2,'Female'); INSERT INTO Gender (ID,Gender) VALUES (3,'Non-binary'); CREATE TABLE MentalHealthAppointment (AppointmentID INT,GenderID INT);
SELECT GenderID, COUNT(AppointmentID) as NumAppointments FROM MentalHealthAppointment GROUP BY GenderID ORDER BY NumAppointments DESC;
What is the percentage of community health workers who speak Spanish, and how does this vary by state?
CREATE TABLE community_health_workers_lang (worker_id INT,state VARCHAR(2),speaks_spanish BOOLEAN); INSERT INTO community_health_workers_lang (worker_id,state,speaks_spanish) VALUES (1,'CA',TRUE),(2,'NY',FALSE),(3,'TX',TRUE);
SELECT c.state, (COUNT(*) FILTER (WHERE c.speaks_spanish = TRUE)) * 100.0 / COUNT(*) as pct_spanish_speakers FROM community_health_workers_lang c GROUP BY c.state;
What is the total number of community health workers in New York and California?
CREATE TABLE community_health_workers (id INT,name TEXT,state TEXT); INSERT INTO community_health_workers (id,name,state) VALUES (1,'John Doe','California'); INSERT INTO community_health_workers (id,name,state) VALUES (2,'Jane Smith','California'); INSERT INTO community_health_workers (id,name,state) VALUES (3,'Maria Garcia','New York'); INSERT INTO community_health_workers (id,name,state) VALUES (4,'David Kim','California');
SELECT COUNT(*) FROM community_health_workers WHERE state IN ('New York', 'California');
What is the name and location of the top 3 most donated heritage sites?
CREATE TABLE HeritageSites (SiteID int,Name varchar(100),Location varchar(100),TotalDonations decimal(10,2)); INSERT INTO HeritageSites (SiteID,Name,Location,TotalDonations) VALUES (1,'Machu Picchu','Peru',500000.00),(2,'Great Wall','China',700000.00),(3,'Petra','Jordan',600000.00);
SELECT Name, Location FROM (SELECT Name, Location, ROW_NUMBER() OVER (ORDER BY TotalDonations DESC) as rn FROM HeritageSites) t WHERE rn <= 3;
Which heritage sites have the most and least visitor reviews?
CREATE TABLE HeritageSites (ID INT,SiteName VARCHAR(100),Location VARCHAR(100),Category VARCHAR(50),Reviews INT); INSERT INTO HeritageSites (ID,SiteName,Location,Category,Reviews) VALUES (1,'Machu Picchu','Peru','Archaeological',5000); INSERT INTO HeritageSites (ID,SiteName,Location,Category,Reviews) VALUES (2,'Angkor Wat','Cambodia','Archaeological',7000);
SELECT SiteName, Reviews, ROW_NUMBER() OVER (ORDER BY Reviews DESC) AS Rank, COUNT(*) OVER () AS TotalSites FROM HeritageSites;
List the unique species of marine life in the 'Marine Life Species' table.
CREATE TABLE marine_life_species (id INT,species_name VARCHAR(255),classification TEXT,habitat TEXT,conservation_status TEXT);
SELECT DISTINCT species_name FROM marine_life_species;
What are the names and specializations of researchers who have published reports on cetacean species?
CREATE TABLE Researchers (id INT PRIMARY KEY,name VARCHAR(255),age INT,specialization VARCHAR(255)); CREATE TABLE Reports (id INT PRIMARY KEY,researcher_id INT,species_id INT,title VARCHAR(255)); CREATE TABLE Species (id INT PRIMARY KEY,name VARCHAR(255),family VARCHAR(255),population INT);
SELECT Researchers.name, Researchers.specialization FROM Researchers JOIN Reports ON Researchers.id = Reports.researcher_id JOIN Species ON Reports.species_id = Species.id WHERE Species.family = 'Cetacean';
What are the top 5 most frequently ordered dishes by customers in NY?
CREATE TABLE customer (customer_id INT,name VARCHAR(50),zip VARCHAR(10));CREATE TABLE orders (order_id INT,customer_id INT,dish VARCHAR(50),price DECIMAL(5,2));
SELECT o.dish, COUNT(*) as count FROM customer c JOIN orders o ON c.customer_id = o.customer_id WHERE c.zip = '10001' GROUP BY o.dish ORDER BY count DESC LIMIT 5;
What is the average price of menu items in each category, excluding items with inventory_count = 0?
CREATE TABLE menu (menu_id INT,item_name VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2),inventory_count INT,last_updated TIMESTAMP);
SELECT category, AVG(price) as avg_price FROM menu WHERE inventory_count > 0 GROUP BY category;
Calculate the average sales of each military equipment type in the Middle East.
CREATE TABLE EquipmentTypes (id INT,product VARCHAR(50)); CREATE TABLE EquipmentSales (id INT,equipment_type_id INT,region VARCHAR(50),year INT,sales FLOAT); INSERT INTO EquipmentTypes (id,product) VALUES (1,'Tank'); INSERT INTO EquipmentTypes (id,product) VALUES (2,'Fighter Jet'); INSERT INTO EquipmentSales (id,equipment_type_id,region,year,sales) VALUES (1,1,'Middle East',2020,2500000); INSERT INTO EquipmentSales (id,equipment_type_id,region,year,sales) VALUES (2,2,'Middle East',2020,6000000);
SELECT EquipmentTypes.product, AVG(EquipmentSales.sales) FROM EquipmentTypes INNER JOIN EquipmentSales ON EquipmentTypes.id = EquipmentSales.equipment_type_id WHERE EquipmentSales.region = 'Middle East' GROUP BY EquipmentTypes.product;
Determine the average monthly data usage for customers in each region.
CREATE TABLE subscribers_2 (id INT,region VARCHAR(20),data_usage FLOAT); INSERT INTO subscribers_2 (id,region,data_usage) VALUES (1,'western',8000); INSERT INTO subscribers_2 (id,region,data_usage) VALUES (2,'eastern',10000);
SELECT region, AVG(data_usage) FROM subscribers_2 GROUP BY region;
Show the number of rock songs released in the 1990s.
CREATE TABLE Songs (song_id INT,artist_id INT,title VARCHAR(100),release_year INT);
SELECT COUNT(song_id) FROM Songs WHERE release_year BETWEEN 1990 AND 1999 AND genre = 'rock';
Identify the top 3 regions with the highest average donation per volunteer, from the 'Volunteer_Donation' table, grouped by Region.
CREATE TABLE Volunteer_Donation (VolunteerID INT,Region VARCHAR(50),Donation DECIMAL(10,2));
SELECT Region, AVG(Donation) AS Average_Donation, ROW_NUMBER() OVER (ORDER BY AVG(Donation) DESC) AS Rank FROM Volunteer_Donation GROUP BY Region HAVING COUNT(*) > 5 ORDER BY Rank;
What is the total number of marine species in the Atlantic Ocean that are affected by ocean acidification?
CREATE TABLE marine_species (id INT,species_name VARCHAR(255),ocean VARCHAR(255),affected_by_acidification BOOLEAN); INSERT INTO marine_species (id,species_name,ocean,affected_by_acidification) VALUES (1,'Species 1','Atlantic',TRUE),(2,'Species 2','Atlantic',FALSE),(3,'Species 3','Pacific',TRUE),(4,'Species 4','Indian',FALSE);
SELECT COUNT(*) FROM marine_species WHERE ocean = 'Atlantic' AND affected_by_acidification = TRUE;
Which causes have received the most funding from donors aged 25-34 in the effective altruism movement?
CREATE TABLE donor_demographics (donor_id INT,age INT,cause VARCHAR(50),donation DECIMAL(10,2)); INSERT INTO donor_demographics (donor_id,age,cause,donation) VALUES (1,27,'Global Health',2000.00),(2,29,'Education',3000.00),(3,31,'Environment',2500.00),(4,26,'Animal Welfare',1500.00),(5,32,'Human Rights',4000.00);
SELECT cause, SUM(donation) FROM donor_demographics WHERE age BETWEEN 25 AND 34 GROUP BY cause ORDER BY SUM(donation) DESC;
Display the number of players who earned an achievement on '2022-01-01' in 'player_achievements' table
CREATE TABLE player_achievements (player_id INT,achievement_name VARCHAR(255),date_earned DATE);
SELECT COUNT(player_id) FROM player_achievements WHERE date_earned = '2022-01-01';
How many players in each country are part of the "InternationalGamers" community?
CREATE TABLE Players (PlayerID INT PRIMARY KEY,Name VARCHAR(50),GamingCommunity VARCHAR(50),Country VARCHAR(50)); INSERT INTO Players (PlayerID,Name,GamingCommunity,Country) VALUES (1,'John Doe','InternationalGamers','USA'),(2,'Jane Smith','InternationalGamers','Canada'),(3,'Alice Johnson','InternationalGamers','Mexico'),(4,'Peter Kim','InternationalGamers','South Korea');
SELECT Country, COUNT(DISTINCT PlayerID) FROM Players WHERE GamingCommunity = 'InternationalGamers' GROUP BY Country;
Add new satellite imagery for farm_id 222
CREATE TABLE satellite_imagery (id INT,farm_id INT,image_url VARCHAR(255),capture_date DATE);
INSERT INTO satellite_imagery (id, farm_id, image_url, capture_date) VALUES (7, 222, 'https://example.com/image1.jpg', '2022-05-30');
Insert new records into the 'livestock_health' table with values (1, 'cow', 'healthy', '2022-06-15 15:20:00')
CREATE TABLE livestock_health (health_id INT,animal_type VARCHAR(20),health_status VARCHAR(20),timestamp TIMESTAMP);
INSERT INTO livestock_health (health_id, animal_type, health_status, timestamp) VALUES (1, 'cow', 'healthy', '2022-06-15 15:20:00');
What is the maximum property price in wheelchair-accessible neighborhoods in Singapore?
CREATE TABLE Singapore_Neighborhoods (Neighborhood_Name TEXT,Wheelchair_Accessibility BOOLEAN); INSERT INTO Singapore_Neighborhoods (Neighborhood_Name,Wheelchair_Accessibility) VALUES ('Orchard',true),('Marina Bay',true),('Chinatown',false),('Little India',false),('Bugis',true); CREATE TABLE Singapore_Properties (Neighborhood_Name TEXT,Property_Price INTEGER); INSERT INTO Singapore_Properties (Neighborhood_Name,Property_Price) VALUES ('Orchard',2000000),('Marina Bay',3000000),('Chinatown',1500000),('Little India',1200000),('Bugis',1800000);
SELECT MAX(Singapore_Properties.Property_Price) FROM Singapore_Properties INNER JOIN Singapore_Neighborhoods ON Singapore_Properties.Neighborhood_Name = Singapore_Neighborhoods.Neighborhood_Name WHERE Singapore_Neighborhoods.Wheelchair_Accessibility = true;
What is the average price for vegetarian menu items in 'Gourmet G'?
CREATE TABLE Menu (Restaurant VARCHAR(255),Item VARCHAR(255),Vegan BOOLEAN,Price DECIMAL(5,2)); INSERT INTO Menu (Restaurant,Item,Vegan,Price) VALUES ('Gourmet G','Steak',FALSE,25.99),('Gourmet G','Chicken Parmesan',FALSE,21.99),('Gourmet G','Vegetable Lasagna',TRUE,18.99),('Gourmet G','Portobello Burger',TRUE,17.99);
SELECT AVG(Price) FROM Menu WHERE Restaurant = 'Gourmet G' AND Vegan = TRUE;
What's the average age of athletes in 'athlete_details' table, grouped by their sport?
CREATE TABLE athlete_details (athlete_id INT,name VARCHAR(50),sport VARCHAR(20),age INT); INSERT INTO athlete_details (athlete_id,name,sport,age) VALUES (1,'John Doe','Basketball',25),(2,'Jane Smith','Soccer',30);
SELECT sport, AVG(age) FROM athlete_details GROUP BY sport;
How many security incidents were there per month in the last year, broken down by severity level?
CREATE TABLE security_incidents (id INT,incident_date DATE,severity INT); INSERT INTO security_incidents (id,incident_date,severity) VALUES (1,'2021-01-01',3),(2,'2021-02-01',2);
SELECT DATEPART(year, incident_date) as year, DATEPART(month, incident_date) as month, severity, COUNT(*) as count FROM security_incidents WHERE incident_date >= DATEADD(year, -1, GETDATE()) GROUP BY DATEPART(year, incident_date), DATEPART(month, incident_date), severity ORDER BY year, month, severity;
What was the total revenue for each category of accessories in the United Kingdom in Q3 2021?
CREATE TABLE sales (item_code VARCHAR(20),item_name VARCHAR(50),category VARCHAR(50),country VARCHAR(50),sale_date DATE,revenue DECIMAL(10,2));
SELECT category, SUM(revenue) as total_revenue FROM sales WHERE country = 'United Kingdom' AND category LIKE '%accessories%' AND sale_date BETWEEN '2021-07-01' AND '2021-09-30' GROUP BY category;
Find the total number of policies issued by 'Department A' and 'Department B'?
CREATE TABLE policies (id INT,policy_number TEXT,department TEXT); INSERT INTO policies (id,policy_number,department) VALUES (1,'P1234','Department A'); INSERT INTO policies (id,policy_number,department) VALUES (2,'P5678','Department B'); INSERT INTO policies (id,policy_number,department) VALUES (3,'P9012','Department C');
SELECT COUNT(*) FROM policies WHERE department IN ('Department A', 'Department B');
List the top 2 countries with the highest water consumption in the current month.
CREATE TABLE water_consumption (country VARCHAR(255),consumption FLOAT,date DATE); INSERT INTO water_consumption (country,consumption,date) VALUES ('Brazil',20000,'2022-05-01'); INSERT INTO water_consumption (country,consumption,date) VALUES ('Egypt',25000,'2022-05-01');
SELECT country, consumption FROM (SELECT country, consumption, ROW_NUMBER() OVER (ORDER BY consumption DESC) as rank FROM water_consumption WHERE date >= '2022-05-01' GROUP BY country, consumption) subquery WHERE rank <= 2;
What is the average monthly water consumption per household in Arizona for the months of June, July, and August?
CREATE TABLE arizona_households (id INT,water_consumption FLOAT,month VARCHAR(10)); INSERT INTO arizona_households (id,water_consumption,month) VALUES (1,1500,'June'),(2,1800,'July'),(3,1200,'August');
SELECT AVG(water_consumption) FROM arizona_households WHERE month IN ('June', 'July', 'August') GROUP BY month;
What is the maximum number of AI ethics complaints received by organizations in South Asia, and which organization received it?
CREATE TABLE south_asia_ethics_complaints (organization VARCHAR(255),region VARCHAR(255),year INT,num_complaints INT); INSERT INTO south_asia_ethics_complaints (organization,region,year,num_complaints) VALUES ('Organization A','India',2018,50),('Organization B','Pakistan',2019,60),('Organization C','Bangladesh',2020,70);
SELECT MAX(num_complaints) as max_complaints, organization FROM south_asia_ethics_complaints WHERE region = 'South Asia' GROUP BY organization HAVING max_complaints = (SELECT MAX(num_complaints) FROM south_asia_ethics_complaints WHERE region = 'South Asia');
What is the average age of male and female farmers in the 'rural_development' schema?
CREATE TABLE farmers(id INT,name VARCHAR(50),age INT,gender VARCHAR(50)); INSERT INTO farmers VALUES (1,'John Doe',45,'Male'); INSERT INTO farmers VALUES (2,'Jane Smith',35,'Female');
SELECT gender, AVG(age) as avg_age FROM farmers GROUP BY gender;
Who are the top 5 countries with the highest economic diversification index for agricultural projects?
CREATE TABLE Projects (id INT,project_id INT,project_type VARCHAR(20),economic_diversification_index DECIMAL(5,2),country VARCHAR(20)); INSERT INTO Projects (id,project_id,project_type,economic_diversification_index,country) VALUES (1,3001,'Agricultural',78.90,'Mexico'),(2,3002,'Infrastructure',67.56,'Colombia'),(3,3003,'Agricultural',85.21,'Peru'),(4,3004,'Agricultural',92.34,'Ecuador'),(5,3005,'Agricultural',65.89,'Bolivia');
SELECT country, economic_diversification_index FROM Projects WHERE project_type = 'Agricultural' ORDER BY economic_diversification_index DESC LIMIT 5;
Determine the number of animals in the animal_population table, partitioned by animal_species and ordered by the animal count in descending order.
CREATE TABLE animal_population (id INT,animal_species VARCHAR(255),animal_age VARCHAR(255)); INSERT INTO animal_population (id,animal_species,animal_age) VALUES (1,'Giraffe','Juvenile'),(2,'Panda','Adult'),(3,'Panda','Adult'),(4,'Lion','Cub'),(5,'Lion','Cub'),(6,'Zebra','Juvenile');
SELECT animal_species, COUNT(*) AS animal_count, RANK() OVER (ORDER BY COUNT(*) DESC) AS rank FROM animal_population GROUP BY animal_species;
What is the average water temperature for the Shrimp farm for the last 30 days?
CREATE TABLE FarmTemperature (farm_id INT,date DATE,temperature DECIMAL(5,2)); INSERT INTO FarmTemperature (farm_id,date,temperature) VALUES (3,'2022-03-01',24.8),(3,'2022-03-02',24.9);
SELECT AVG(temperature) avg_temp FROM FarmTemperature WHERE farm_id = 3 AND date >= (SELECT DATEADD(day, -30, GETDATE()));
What is the minimum biomass of fish in each species in the fish_stock table?
CREATE TABLE fish_stock (species VARCHAR(50),biomass INT); INSERT INTO fish_stock (species,biomass) VALUES ('Tilapia',500),('Tilapia',700),('Salmon',800);
SELECT species, MIN(biomass) FROM fish_stock GROUP BY species;
What is the maximum labor cost per square foot for construction projects in Florida over $6,000,000?
CREATE TABLE Labor_Cost_Per_Square_Foot (id INT,project_name TEXT,state TEXT,budget INT,labor_cost_per_square_foot FLOAT); INSERT INTO Labor_Cost_Per_Square_Foot (id,project_name,state,budget,labor_cost_per_square_foot) VALUES (1,'Mega Mall','Florida',7000000,65.0),(2,'Apartment Complex','Florida',5500000,50.0);
SELECT MAX(labor_cost_per_square_foot) FROM Labor_Cost_Per_Square_Foot WHERE state = 'Florida' AND budget > 6000000;