instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many market access strategies were implemented for drugs approved in each year, and what was the average R&D expenditure for those drugs?
CREATE TABLE market_access_3(strategy_name TEXT,drug_name TEXT,approval_year INT,rd_expenditure FLOAT); INSERT INTO market_access_3(strategy_name,drug_name,approval_year,rd_expenditure) VALUES('Strategy1','Drug1',2018,8000000),('Strategy2','Drug2',2019,9000000),('Strategy3','Drug3',2020,7000000),('Strategy4','Drug4',2018,6000000); CREATE TABLE drugs_5(drug_name TEXT,approval_year INT,rd_expenditure FLOAT); INSERT INTO drugs_5(drug_name,approval_year,rd_expenditure) VALUES('Drug1',2018,8000000),('Drug2',2019,9000000),('Drug3',2020,7000000),('Drug4',2018,6000000),('Drug5',2019,8500000),('Drug6',2020,9500000);
SELECT approval_year, AVG(rd_expenditure) AS avg_rd_expenditure, COUNT(DISTINCT drug_name) AS strategy_count FROM market_access_3 GROUP BY approval_year;
How many marine species have a population of less than 1000 in the Pacific Ocean?
CREATE TABLE marine_life (id INT PRIMARY KEY,species VARCHAR(255),population INT,habitat VARCHAR(255));
SELECT COUNT(*) FROM marine_life WHERE population < 1000 AND habitat LIKE '%Pacific%';
Which policies have been updated in the last month?
CREATE TABLE CybersecurityPolicies (id INT,policy_name VARCHAR(255),last_updated DATE);
SELECT policy_name FROM CybersecurityPolicies WHERE last_updated >= DATEADD(month, -1, GETDATE());
What is the total number of sustainable fashion items produced in the US and Mexico?
CREATE TABLE SustainableItems (id INT,item VARCHAR(255),country VARCHAR(255),price DECIMAL(5,2)); INSERT INTO SustainableItems (id,item,country,price) VALUES (1,'Organic Cotton T-Shirt','US',30.00),(2,'Recycled Polyester Hoodie','Mexico',60.00),(3,'Bamboo Viscose Pants','US',50.00),(4,'Fair Trade Socks','Mexico',15.00);
SELECT COUNT(*) FROM SustainableItems WHERE country IN ('US', 'Mexico');
What is the maximum number of visitors for an exhibition in Paris and Rome?
CREATE TABLE Exhibitions (ExhibitionID INT,Title VARCHAR(50),City VARCHAR(50),MaxVisitors INT); INSERT INTO Exhibitions (ExhibitionID,Title,City,MaxVisitors) VALUES (1,'Art of the 20th Century','Paris',100); INSERT INTO Exhibitions (ExhibitionID,Title,City,MaxVisitors) VALUES (2,'Impressionist Masters','Rome',150);
SELECT MAX(Exhibitions.MaxVisitors) FROM Exhibitions WHERE Exhibitions.City IN ('Paris', 'Rome');
What is the maximum number of attempts before a lockout for the marketing department?
CREATE TABLE lockout_policies (department VARCHAR(255),max_attempts INT); INSERT INTO lockout_policies (department,max_attempts) VALUES ('IT',5),('marketing',3),('HR',7);
SELECT MAX(max_attempts) FROM lockout_policies WHERE department = 'marketing';
What is the total number of art pieces in the 'Pop Art' category that were created in the 21st century?
CREATE TABLE ArtPieces (id INT,category VARCHAR(20),year INT); INSERT INTO ArtPieces (id,category,year) VALUES (1,'Pop Art',2005),(2,'Cubism',1920),(3,'Pop Art',2015);
SELECT COUNT(*) FROM ArtPieces WHERE category = 'Pop Art' AND year >= 2000;
List the threat actors that have been active in the last 60 days, ordered by their latest activity.
CREATE TABLE ThreatActors (id INT,actor_name VARCHAR(255),last_seen DATE); INSERT INTO ThreatActors (id,actor_name,last_seen) VALUES (1,'APT29','2022-03-10'),(2,'Lazarus Group','2022-03-05'),(3,'Cozy Bear','2022-03-01'),(4,'Fancy Bear','2022-02-25'),(5,'WannaCry','2022-02-20'),(6,'Carbanak','2022-01-10'),(7,'OceanLotus','2022-01-05'),(8,'Gamaredon','2021-12-28');
SELECT actor_name, last_seen, ROW_NUMBER() OVER (ORDER BY last_seen DESC) AS rank FROM ThreatActors WHERE last_seen >= DATEADD(day, -60, GETDATE());
What was the total amount donated by each donor type in the year 2020?
CREATE TABLE donor_type (id INT,donor_type VARCHAR(20),total_donation DECIMAL(10,2)); INSERT INTO donor_type (id,donor_type,total_donation) VALUES (1,'Individual',15000.00),(2,'Corporation',35000.00),(3,'Foundation',50000.00);
SELECT donor_type, SUM(total_donation) as total_donation FROM donor_type WHERE YEAR(donation_date) = 2020 GROUP BY donor_type;
What was the average program outcome score for programs in the Arts and Culture category in 2018, grouped by country?
CREATE TABLE Programs (ProgramID INT,Category TEXT,OutcomeScore INT,StartYear INT,Country TEXT); INSERT INTO Programs (ProgramID,Category,OutcomeScore,StartYear,Country) VALUES (1,'Arts and Culture',85,2018,'USA'),(2,'Healthcare',90,2019,'Canada'),(3,'Arts and Culture',80,2018,'Mexico');
SELECT Country, AVG(OutcomeScore) as 'Average Outcome Score' FROM Programs WHERE Category = 'Arts and Culture' AND StartYear = 2018 GROUP BY Country;
What is the total revenue generated by restaurants in the "organic" category?
CREATE TABLE restaurants (id INT,name TEXT,category TEXT,revenue FLOAT); INSERT INTO restaurants (id,name,category,revenue) VALUES (1,'Restaurant A','organic',50000.00),(2,'Restaurant B','conventional',45000.00),(3,'Restaurant C','organic',60000.00);
SELECT SUM(revenue) FROM restaurants WHERE category = 'organic';
What is the total number of volunteers for each program in the 'programs' and 'volunteers' tables?
CREATE TABLE programs (program_id INT,program_name TEXT); CREATE TABLE volunteers (volunteer_id INT,volunteer_name TEXT,program_id INT); INSERT INTO programs (program_id,program_name) VALUES (1,'Education'),(2,'Health'),(3,'Environment'); INSERT INTO volunteers (volunteer_id,volunteer_name,program_id) VALUES (1,'John Doe',1),(2,'Jane Smith',1),(3,'Alice Johnson',2);
SELECT p.program_name, COUNT(v.volunteer_id) as num_volunteers FROM programs p JOIN volunteers v ON p.program_id = v.program_id GROUP BY p.program_name;
Find the number of destinations with sustainable tourism certifications in the European Union
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 A','Country A','Europe',TRUE),('City B','Country B','Europe',FALSE),('City C','Country C','Europe',TRUE);
SELECT COUNT(*) FROM destinations WHERE continent = 'Europe' AND sustainable_certification = TRUE;
What is the average well-being score for athletes in each team?
CREATE TABLE teams (team_id INT,team_name VARCHAR(50));CREATE TABLE athletes (athlete_id INT,athlete_name VARCHAR(50),team_id INT,well_being_score INT); INSERT INTO teams (team_id,team_name) VALUES (1,'Atlanta Hawks'),(2,'Boston Celtics'); INSERT INTO athletes (athlete_id,athlete_name,team_id,well_being_score) VALUES (1,'Player1',1,8),(2,'Player2',1,9),(3,'Player3',2,7),(4,'Player4',2,8);
SELECT t.team_name, AVG(a.well_being_score) FROM teams t JOIN athletes a ON t.team_id = a.team_id GROUP BY t.team_id;
What is the total number of defense projects and their total cost for region Y?
CREATE TABLE DefenseProjects (project_id INT,region VARCHAR(50),project_cost DECIMAL(10,2)); INSERT INTO DefenseProjects (project_id,region,project_cost) VALUES (1,'Y',1000000.00); INSERT INTO DefenseProjects (project_id,region,project_cost) VALUES (2,'Y',2000000.00);
SELECT region, COUNT(*) as total_projects, SUM(project_cost) as total_cost FROM DefenseProjects WHERE region = 'Y' GROUP BY region;
Delete the fabric with id 3 from the fabrics table.
CREATE TABLE fabrics (id INT,name VARCHAR(255),sustainability_rating FLOAT); INSERT INTO fabrics (id,name,sustainability_rating) VALUES (1,'Organic Cotton',4.3),(2,'Recycled Polyester',3.8),(3,'Hemp',4.5),(4,'Bamboo',4.7),(5,'Linen',4.4);
DELETE FROM fabrics WHERE id = 3;
What is the maximum funding amount received by Asian founders in the SaaS sector?
CREATE TABLE InvestmentRounds (id INT,founder_id INT,funding_amount INT); INSERT INTO InvestmentRounds VALUES (1,2,5000000);
SELECT MAX(InvestmentRounds.funding_amount) FROM InvestmentRounds JOIN Founders ON InvestmentRounds.founder_id = Founders.id WHERE Founders.ethnicity = 'Asian' AND Founders.industry = 'SaaS';
What is the average budget for climate projects in Oceania that were started after 2016?
CREATE TABLE climate_projects (project_name VARCHAR(50),location VARCHAR(50),start_year INT,budget INT,sector VARCHAR(50)); INSERT INTO climate_projects (project_name,location,start_year,budget,sector) VALUES ('Solar Farm A','Australia',2018,1000000,'Solar'),('Wind Farm B','New Zealand',2019,1500000,'Wind');
SELECT AVG(budget) FROM climate_projects WHERE location IN ('Oceania') AND start_year > 2016;
How many debris objects were detected in the last 3 months?
CREATE TABLE Debris (id INT,object_id INT,location VARCHAR(50),detection_date DATE); INSERT INTO Debris (id,object_id,location,detection_date) VALUES (1,234,'LEO','2022-01-01');
SELECT COUNT(object_id) FROM Debris WHERE detection_date BETWEEN DATE_SUB(NOW(), INTERVAL 3 MONTH) AND NOW();
What is the cultural competency score distribution among health care providers?
CREATE TABLE healthcare_providers (provider_id INT,cultural_competency_score INT); INSERT INTO healthcare_providers (provider_id,cultural_competency_score) VALUES (1,80),(2,90),(3,70),(4,85),(5,95);
SELECT cultural_competency_score, COUNT(provider_id) as num_providers FROM healthcare_providers GROUP BY cultural_competency_score;
How many solar power installations are there in Australia that have a capacity of at least 100 MW?
CREATE TABLE solar_installations (name TEXT,country TEXT,capacity_mw REAL); INSERT INTO solar_installations (name,country,capacity_mw) VALUES ('Solar Farm A','Australia',120),('Solar Farm B','Australia',150);
SELECT COUNT(*) FROM solar_installations WHERE country = 'Australia' AND capacity_mw >= 100;
What is the total revenue generated from digital music sales by female artists?
CREATE TABLE MusicSales (SaleID INT,ArtistGender VARCHAR(6),Genre VARCHAR(10),SalesAmount DECIMAL(10,2)); INSERT INTO MusicSales (SaleID,ArtistGender,Genre,SalesAmount) VALUES (1,'Female','Jazz',12.99),(2,'Male','Rock',15.00),(3,'Female','Pop',19.45);
SELECT SUM(SalesAmount) FROM MusicSales WHERE ArtistGender = 'Female';
What is the number of employees in the 'construction' industry?
CREATE TABLE if not exists employment (id INT,industry VARCHAR,number_of_employees INT); INSERT INTO employment (id,industry,number_of_employees) VALUES (1,'manufacturing',5000),(2,'technology',8000),(3,'healthcare',7000),(4,'retail',6000),(5,'education',9000),(6,'finance',10000),(7,'government',11000),(9,'construction',13000);
SELECT SUM(number_of_employees) FROM employment WHERE industry = 'construction';
How many students have achieved a mental health score improvement of at least 10 points?
CREATE TABLE students (student_id INT,name VARCHAR(20),assessment_id INT,mental_health_score INT); INSERT INTO students (student_id,name,assessment_id,mental_health_score) VALUES (1,'James',1,75),(1,'James',2,85),(2,'Emily',1,80),(2,'Emily',2,80),(3,'Michael',1,70),(3,'Michael',2,80),(4,'Olivia',1,60),(4,'Olivia',2,70);
SELECT COUNT(*) as students_with_improvement FROM (SELECT student_id, assessment_id, mental_health_score, LAG(mental_health_score) OVER (PARTITION BY student_id ORDER BY assessment_id) as previous_mental_health_score FROM students) as subquery WHERE mental_health_score - previous_mental_health_score >= 10;
What is the average age of vessels that have had safety incidents in the Mediterranean in 2021?
CREATE TABLE Region (region_id INT PRIMARY KEY,region_name VARCHAR(255)); INSERT INTO Region (region_id,region_name) VALUES (1,'Mediterranean'); CREATE TABLE Vessel (vessel_id INT PRIMARY KEY,vessel_name VARCHAR(255),region_id INT,build_date DATE); CREATE TABLE Safety_Incident (incident_id INT PRIMARY KEY,vessel_id INT,incident_date DATE);
SELECT AVG(DATEDIFF('day', V.build_date, GETDATE())) FROM Vessel V JOIN Safety_Incident SI ON V.vessel_id = SI.vessel_id WHERE SI.incident_date >= '2021-01-01' AND SI.incident_date < '2022-01-01' AND V.region_id = (SELECT region_id FROM Region WHERE region_name = 'Mediterranean');
What are the names and quantities of raw materials used in the production of product 'B302'?
CREATE TABLE Raw_Materials (raw_material_code TEXT,raw_material_name TEXT,quantity INTEGER); INSERT INTO Raw_Materials (raw_material_code,raw_material_name,quantity) VALUES ('M123','Hydrochloric Acid',500),('M234','Sodium Hydroxide',800),('M345','Acetic Acid',300),('M456','B302',1000);
SELECT rm.raw_material_name, rm.quantity FROM Raw_Materials rm WHERE rm.raw_material_code = (SELECT p.raw_material_code FROM Products p WHERE p.product_name = 'B302');
What is the daily water consumption of the mining operation with the highest 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, MAX(consumption) FROM daily_water_consumption GROUP BY operation;
Update the faculty_diversity table to change the gender of the faculty member with ID 1
CREATE TABLE faculty_diversity (id INT,name TEXT,gender TEXT); INSERT INTO faculty_diversity (id,name,gender) VALUES (1,'Alice','Female'),(2,'Bob','Male'),(3,'Charlie','Non-binary');
UPDATE faculty_diversity SET gender = 'Non-binary' WHERE id = 1;
What is the total number of sessions for each type of therapy?
CREATE TABLE sessions (session_id INT,type VARCHAR(20),therapist_id INT,patient_id INT,sessions INT); INSERT INTO sessions (session_id,type,therapist_id,patient_id,sessions) VALUES (1,'CBT',1,1,5); INSERT INTO sessions (session_id,type,therapist_id,patient_id,sessions) VALUES (2,'CBT',1,2,4); INSERT INTO sessions (session_id,type,therapist_id,patient_id,sessions) VALUES (3,'DBT',2,3,6);
SELECT type, SUM(sessions) FROM sessions GROUP BY type;
Calculate the total donation amount for each nonprofit
CREATE TABLE donations (id INT PRIMARY KEY,donor_id INT,donation_amount DECIMAL(10,2),donation_date DATE); CREATE TABLE nonprofits (id INT PRIMARY KEY,name VARCHAR(100),city VARCHAR(50),mission VARCHAR(200)); INSERT INTO donations (id,donor_id,donation_amount,donation_date) VALUES (1,1,500,'2022-01-01'); INSERT INTO donations (id,donor_id,donation_amount,donation_date) VALUES (2,2,750,'2022-02-15'); INSERT INTO nonprofits (id,name,city,mission) VALUES (1,'Save the Children','Washington','Improving the lives of children through better education,health care,and economic opportunities.'); INSERT INTO nonprofits (id,name,city,mission) VALUES (2,'Greenpeace','San Francisco','Dedicated to preserving the environment and promoting peace.');
SELECT donations.nonprofit_id, SUM(donation_amount) as total_donations FROM donations GROUP BY donations.nonprofit_id;
Insert a new record into the Wastewater_Treatment table with the wastewater treatment plant ID 5, a treatment date of '2022-06-01', and a treatment volume of 1800.
CREATE TABLE Wastewater_Treatment (id INT,treatment_date DATE,treatment_volume FLOAT); INSERT INTO Wastewater_Treatment (id,treatment_date,treatment_volume) VALUES (1,'2022-01-01',1500.0),(2,'2022-02-01',1600.0),(3,'2022-03-01',1700.0),(4,'2022-04-01',1800.0),(5,'2022-05-01',1900.0);
INSERT INTO Wastewater_Treatment (id, treatment_date, treatment_volume) VALUES (6, '2022-06-01', 1800.0);
What is the minimum budget allocated for technology for social good projects in Oceania countries?
CREATE TABLE SocialGoodBudget (Country VARCHAR(50),Budget DECIMAL(10,2)); INSERT INTO SocialGoodBudget (Country,Budget) VALUES ('Australia',1200000.00),('New Zealand',1500000.00); CREATE TABLE Countries (Country VARCHAR(50),Continent VARCHAR(50)); INSERT INTO Countries (Country,Continent) VALUES ('Australia','Oceania'),('New Zealand','Oceania');
SELECT MIN(SocialGoodBudget.Budget) AS MinBudget FROM SocialGoodBudget INNER JOIN Countries ON SocialGoodBudget.Country = Countries.Country WHERE Countries.Continent = 'Oceania';
How many unique clothing items are available in size 2XL?
CREATE TABLE inventory (id INT,item_name VARCHAR(50),item_size VARCHAR(10)); INSERT INTO inventory (id,item_name,item_size) VALUES (1,'T-Shirt','XL'); INSERT INTO inventory (id,item_name,item_size) VALUES (2,'Jeans','2XL'); INSERT INTO inventory (id,item_name,item_size) VALUES (3,'Sweater','M');
SELECT COUNT(DISTINCT item_name) FROM inventory WHERE item_size = '2XL';
Calculate the average daily revenue for the top 10 customers in Q1 2022.
CREATE TABLE customers (customer_id INT,customer_name TEXT); CREATE TABLE sales (sale_id INT,customer_id INT,sale_date DATE,revenue FLOAT);
SELECT c.customer_name, AVG(s.revenue) AS avg_daily_revenue FROM sales s JOIN customers c ON s.customer_id = c.customer_id WHERE s.sale_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY c.customer_id, c.customer_name ORDER BY avg_daily_revenue DESC LIMIT 10;
Which community development initiatives were completed in the 'rural_infrastructure' schema between 2015 and 2017, inclusive?
CREATE TABLE community_initiatives (id INT,name VARCHAR(50),completion_date DATE); INSERT INTO community_initiatives (id,name,completion_date) VALUES (1,'Community Center Project','2016-08-15');
SELECT name FROM rural_infrastructure.community_initiatives WHERE completion_date BETWEEN '2015-01-01' AND '2017-12-31';
List the names of all sensors and their respective last recorded timestamps from the 'sensor_data' table
CREATE TABLE sensor_data (sensor_id INT,water_level FLOAT,timestamp TIMESTAMP);
SELECT sensor_id, MAX(timestamp) as last_recorded_timestamp FROM sensor_data;
Which organizations have the lowest average donation amount in the West?
CREATE TABLE organizations (org_id INT,org_name TEXT,region TEXT,avg_donation FLOAT); INSERT INTO organizations (org_id,org_name,region,avg_donation) VALUES (1,'Habitat for Humanity','West',100.00),(2,'Red Cross','West',115.00),(3,'UNICEF','East',200.00);
SELECT org_name, AVG(avg_donation) as avg_donation FROM organizations WHERE region = 'West' GROUP BY org_name ORDER BY avg_donation ASC;
Display all military equipment sales that occurred between Contractor Q and Country E in Q4 of 2018.
CREATE TABLE EquipmentSales (SaleID INT,Contractor VARCHAR(255),EquipmentType VARCHAR(255),Quantity INT,SalePrice DECIMAL(5,2),Country VARCHAR(255),Quarter VARCHAR(10),Year INT); INSERT INTO EquipmentSales (SaleID,Contractor,EquipmentType,Quantity,SalePrice,Country,Quarter,Year) VALUES (1,'Contractor Q','Aircraft',2,20000000,'Country E','Q4',2018);
SELECT * FROM EquipmentSales WHERE Contractor = 'Contractor Q' AND Country = 'Country E' AND Quarter = 'Q4' AND Year = 2018;
Which countries spent the most on R&D in '2020', excluding the US?
CREATE TABLE rd_2020_2(country varchar(20),expenditure int); INSERT INTO rd_2020_2(country,expenditure) VALUES('US',12000),('Canada',9000);
SELECT country, MAX(expenditure) FROM rd_2020_2 WHERE country != 'US' GROUP BY country
What is the total production cost for each aircraft model?
CREATE TABLE AircraftProductionCost (id INT,model VARCHAR(255),quantity INT,unit_cost DECIMAL(5,2)); INSERT INTO AircraftProductionCost (id,model,quantity,unit_cost) VALUES (1,'F-15',100,120.50),(2,'F-16',200,145.20),(3,'F-35',300,189.90);
SELECT model, SUM(quantity * unit_cost) AS total_cost FROM AircraftProductionCost GROUP BY model;
Which community policing districts have the highest police interactions?
CREATE TABLE CommunityPolicing (id INT,district VARCHAR(255),police_interactions INT);
SELECT district, MAX(police_interactions) FROM CommunityPolicing GROUP BY district;
Which organizations have the highest and lowest total hours of volunteer work?
CREATE TABLE Volunteers (VolID INT,OrgID INT,VolName VARCHAR(255),Hours INT); INSERT INTO Volunteers (VolID,OrgID,VolName,Hours) VALUES (1,1,'Alice',50),(2,1,'Bob',75),(3,2,'Charlie',100),(4,3,'David',120),(5,3,'Eve',150),(6,4,'Frank',180),(7,5,'Grace',200);
SELECT OrgID, SUM(Hours) as TotalHours FROM Volunteers GROUP BY OrgID ORDER BY TotalHours DESC, OrgID;
What is the maximum and minimum budget for intelligence operations by year?
CREATE TABLE IntelligenceBudget (id INT PRIMARY KEY,year INT,budget DECIMAL(10,2)); INSERT INTO IntelligenceBudget (id,year,budget) VALUES (1,2018,5000000.00),(2,2019,5500000.00),(3,2020,6000000.00);
SELECT YEAR(budget_date) as year, MAX(budget) as max_budget, MIN(budget) as min_budget FROM IntelligenceBudget GROUP BY YEAR(budget_date);
What is the fairness score for each AI algorithm, partitioned by algorithm type, ordered by score in ascending order?
CREATE TABLE ai_algorithms_fairness (algorithm_id INT,algorithm_name VARCHAR(50),fairness_score DECIMAL(5,2)); INSERT INTO ai_algorithms_fairness (algorithm_id,algorithm_name,fairness_score) VALUES (1,'DeepQA',0.87),(2,'Random Forest',0.92),(3,'Support Vector Machine',0.91),(4,'Neural Network',0.88);
SELECT algorithm_name, AVG(fairness_score) as avg_fairness_score FROM ai_algorithms_fairness GROUP BY algorithm_name ORDER BY avg_fairness_score ASC;
Update the quantity of item 'EAA-001' in the inventory table to 500
CREATE TABLE Inventory (Item VARCHAR(10),Quantity INT); INSERT INTO Inventory (Item,Quantity) VALUES ('EAA-001',300),('EAA-002',400);
UPDATE Inventory SET Quantity = 500 WHERE Item = 'EAA-001';
What is the number of contracts for each category?
CREATE TABLE contracts (id INT,category VARCHAR(255),value DECIMAL(10,2));INSERT INTO contracts (id,category,value) VALUES (1,'Aircraft',5000000.00),(2,'Missiles',2000000.00),(3,'Shipbuilding',8000000.00),(4,'Cybersecurity',3000000.00),(5,'Aircraft',6000000.00),(6,'Shipbuilding',9000000.00);
SELECT category, COUNT(*) as contract_count FROM contracts GROUP BY category;
What is the average budget allocated for disability support programs in '2021'?
CREATE TABLE DisabilitySupportPrograms (year INT,budget DECIMAL(5,2)); INSERT INTO DisabilitySupportPrograms (year,budget) VALUES (2019,120000.00),(2020,150000.00),(2021,180000.00);
SELECT AVG(budget) FROM DisabilitySupportPrograms WHERE year = 2021;
Find the top 5 goal scorers in the English Premier League in the 2020-2021 season.
CREATE TABLE epl_2020_2021 (player TEXT,goals INT);
SELECT player, goals FROM epl_2020_2021 ORDER BY goals DESC LIMIT 5;
What is the total number of machines for each type, and the latest model year for each type?
CREATE TABLE machines (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),year INT); INSERT INTO machines (id,name,type,year) VALUES (1,'Machine A','CNC',2015),(2,'Machine B','3D Printing',2020),(3,'Machine C','CNC',2018);
SELECT type, COUNT(*) as total_machines, MAX(year) as latest_model FROM machines GROUP BY type;
Update the percentage of 'organic_cotton' use in 'India' to 76.5
CREATE TABLE organic_materials (country VARCHAR(50),fashion_production_sector VARCHAR(50),organic_material_type VARCHAR(50),percentage_use FLOAT); INSERT INTO organic_materials (country,fashion_production_sector,organic_material_type,percentage_use) VALUES ('India','fashion_production','organic_cotton',75.5),('India','fashion_production','organic_silk',82.3),('India','fashion_production','organic_wool',90.1);
UPDATE organic_materials SET percentage_use = 76.5 WHERE country = 'India' AND organic_material_type = 'organic_cotton';
What is the average monthly revenue for prepaid mobile customers in the city of Dallas?
CREATE TABLE mobile_customers (customer_id INT,monthly_revenue FLOAT,city VARCHAR(20),plan_type VARCHAR(10)); INSERT INTO mobile_customers (customer_id,monthly_revenue,city,plan_type) VALUES (1,25.5,'Dallas','prepaid'),(2,32.2,'Houston','postpaid'),(3,28.9,'Dallas','prepaid');
SELECT AVG(monthly_revenue) FROM mobile_customers WHERE city = 'Dallas' AND plan_type = 'prepaid';
What are the total installed capacities (in MW) of wind farms in Germany and France?
CREATE TABLE wind_farm_germany (id INT,name TEXT,location TEXT,capacity_mw FLOAT); INSERT INTO wind_farm_germany (id,name,location,capacity_mw) VALUES (1,'Windpark Nordsee One','Germany',332.0); CREATE TABLE wind_farm_france (id INT,name TEXT,location TEXT,capacity_mw FLOAT); INSERT INTO wind_farm_france (id,name,location,capacity_mw) VALUES (1,'Parc éolien en mer de Fécamp','France',498.0);
SELECT SUM(capacity_mw) FROM wind_farm_germany WHERE location = 'Germany' UNION SELECT SUM(capacity_mw) FROM wind_farm_france WHERE location = 'France';
What is the average policy impact for cities with implemented policies with a positive impact?
CREATE TABLE City_Policy (city_id INT,description TEXT,implemented BOOLEAN,impact INT); INSERT INTO City_Policy (city_id,description,implemented,impact) VALUES (1,'Bike lane expansion',true,8); INSERT INTO City_Policy (city_id,description,implemented,impact) VALUES (1,'Park renovation',false,NULL); INSERT INTO City_Policy (city_id,description,implemented,impact) VALUES (2,'Bus lane creation',true,6); INSERT INTO City_Policy (city_id,description,implemented,impact) VALUES (2,'Smart traffic lights',true,7); INSERT INTO City_Policy (city_id,description,implemented,impact) VALUES (3,'Green spaces creation',true,9);
SELECT City_Policy.city_id, AVG(City_Policy.impact) as 'Avg Policy Impact' FROM City_Policy WHERE City_Policy.implemented = true AND City_Policy.impact > 0 GROUP BY City_Policy.city_id;
What is the maximum number of attendees at an esports event held in Europe?
CREATE TABLE EsportsEvents (EventID INT,EventName VARCHAR(50),Location VARCHAR(50),Attendance INT); INSERT INTO EsportsEvents (EventID,EventName,Location,Attendance) VALUES (1,'GameCon Europe','London',60000),(2,'Esports World Cup','Berlin',90000),(3,'Gaming Summit','Paris',70000);
SELECT MAX(Attendance) FROM EsportsEvents WHERE Location = 'Europe';
What's the total number of smart contracts by technology type?
CREATE TABLE smart_contracts (id INT,name VARCHAR(255),technology VARCHAR(50)); INSERT INTO smart_contracts (id,name,technology) VALUES (1,'SC1','EVM'); INSERT INTO smart_contracts (id,name,technology) VALUES (2,'SC2','Solidity'); INSERT INTO smart_contracts (id,name,technology) VALUES (3,'SC3','EVM'); CREATE TABLE technologies (id INT,name VARCHAR(50)); INSERT INTO technologies (id,name) VALUES (1,'EVM'); INSERT INTO technologies (id,name) VALUES (2,'Solidity');
SELECT technology, COUNT(*) FROM smart_contracts GROUP BY technology;
Insert new donor records for the first quarter of 2023.
CREATE TABLE Donors (DonorID int,FirstName varchar(50),LastName varchar(50)); INSERT INTO Donors (DonorID,FirstName,LastName) VALUES (1,'John','Doe'),(2,'Jane','Doe');
INSERT INTO Donors (DonorID, FirstName, LastName) VALUES (3, 'Mohammad', 'Ali'), (4, 'Hanako', 'Yamada'), (5, 'Leonel', 'Messi');
Add a new row to the 'autonomous_driving_research' table with id 100, vehicle_name 'Wayve', and research_topic 'Deep Learning'
CREATE TABLE autonomous_driving_research (id INT,vehicle_name VARCHAR(50),research_topic VARCHAR(50));
INSERT INTO autonomous_driving_research (id, vehicle_name, research_topic) VALUES (100, 'Wayve', 'Deep Learning');
How many IoT moisture sensors are currently installed?
CREATE TABLE sensor_installation (sensor_id INT,install_date DATE); INSERT INTO sensor_installation (sensor_id,install_date) VALUES (1001,'2021-04-03'),(1002,'2021-04-17'),(1003,'2021-04-01'),(1004,'2021-04-15'),(1005,'2021-03-30');
SELECT COUNT(*) FROM sensor_installation WHERE install_date <= CURDATE();
What is the weekly sales trend for vegan menu items?
CREATE TABLE menu_sales(menu_item VARCHAR(50),sale_date DATE,sales INT,type VARCHAR(10)); INSERT INTO menu_sales VALUES ('Burger','2022-01-01',50,'non-veg'),('Pizza','2022-01-01',30,'veg'),('Salad','2022-01-01',20,'veg'),('Burger','2022-01-02',60,'non-veg'),('Pizza','2022-01-02',40,'veg'),('Salad','2022-01-02',30,'veg');
SELECT sale_date, type, SUM(sales) AS total_sales, ROW_NUMBER() OVER (PARTITION BY type ORDER BY SUM(sales) DESC) AS ranking FROM menu_sales WHERE type = 'veg' GROUP BY sale_date, type ORDER BY sale_date, total_sales DESC;
List all customers who have not made any transactions in the last 6 months.
CREATE TABLE customers (customer_id INT,name VARCHAR(50)); INSERT INTO customers (customer_id,name) VALUES (1,'John Smith'),(2,'Jane Doe'),(3,'Bob Johnson'); CREATE TABLE transactions (transaction_id INT,customer_id INT,amount DECIMAL(10,2),transaction_date DATE); INSERT INTO transactions (transaction_id,customer_id,amount,transaction_date) VALUES (1,1,100.00,'2022-01-05'),(2,1,200.00,'2022-02-10'),(3,2,50.00,'2022-03-15'),(4,3,1000.00,'2022-06-30');
SELECT c.customer_id, c.name FROM customers c LEFT JOIN transactions t ON c.customer_id = t.customer_id WHERE t.transaction_date IS NULL OR t.transaction_date < DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
Insert new records into the fashion_trends table with the latest trending garment types in the African market.
CREATE TABLE fashion_trends (id INT,garment_type VARCHAR(255),region VARCHAR(255),popularity INT); INSERT INTO fashion_trends (id,garment_type,region,popularity) VALUES (1,'Ankara Dress','Africa',90),(2,'Kente Cloth Pants','Africa',80),(3,'Dashiki Shirt','Africa',70);
INSERT INTO fashion_trends (id, garment_type, region, popularity) VALUES (4, 'Boubou', 'Africa', 85), (5, 'Kufi Hat', 'Africa', 95), (6, 'Fila Jacket', 'Africa', 88);
What is the average energy consumption for commercial buildings in Canada, grouped by province?
CREATE TABLE Commercial_Buildings (province VARCHAR(255),consumption INT); INSERT INTO Commercial_Buildings (province,consumption) VALUES ('Ontario',120),('Quebec',100),('British Columbia',150);
SELECT province, AVG(consumption) AS avg_consumption FROM Commercial_Buildings GROUP BY province;
Select the total number of public libraries in New York City
CREATE TABLE public_libraries (library_id INT,name VARCHAR(255),location VARCHAR(255),city VARCHAR(255),state VARCHAR(255),zip INT); INSERT INTO public_libraries (library_id,name,location,city,state,zip) VALUES (1,'New York Public Library','Fifth Avenue','New York','NY',10003); INSERT INTO public_libraries (library_id,name,location,city,state,zip) VALUES (2,'Brooklyn Public Library','Grand Army Plaza','Brooklyn','NY',11238);
SELECT COUNT(*) FROM public_libraries WHERE city = 'New York';
How many hotels are there in 'New York'?
CREATE TABLE hotels (id INT,name TEXT,city TEXT); INSERT INTO hotels (id,name,city) VALUES (1,'Hotel Plaza','New York'),(2,'Hotel Wellington','New York'),(3,'Hotel Giraffe','New York');
SELECT COUNT(*) FROM hotels WHERE city = 'New York';
Identify the total number of legal technology patents filed by women-led teams from 2010 to 2020
CREATE TABLE legal_technology_patents (patent_id INT,filing_year INT,women_led_team BOOLEAN); INSERT INTO legal_technology_patents (patent_id,filing_year,women_led_team) VALUES (1,2010,FALSE),(2,2011,TRUE),(3,2012,TRUE),(4,2015,FALSE),(5,2018,TRUE),(6,2020,TRUE);
SELECT SUM(women_led_team) FROM legal_technology_patents WHERE filing_year BETWEEN 2010 AND 2020 AND women_led_team = TRUE;
Delete all clinical trial records for drug 'DrugX' from the 'clinical_trial_data' table.
CREATE TABLE clinical_trial_data (clinical_trial_id INT,drug_name VARCHAR(255),primary_investigator VARCHAR(255),start_date DATE,end_date DATE);
DELETE FROM clinical_trial_data WHERE drug_name = 'DrugX';
List the names and research interests of all professors who have received a research grant.
CREATE TABLE professors (id INT,name VARCHAR(50),department VARCHAR(50),research_interest VARCHAR(50),grant INT); INSERT INTO professors (id,name,department,research_interest,grant) VALUES (1,'John Doe','Computer Science','Machine Learning',1),(2,'Jane Smith','Computer Science','Data Science',1),(3,'Alice Johnson','Electrical Engineering','Power Systems',0);
SELECT name, research_interest FROM professors WHERE grant = 1;
List all the police stations and their respective zones?
CREATE TABLE police_stations (station_id INT,station_name TEXT,zone_id INT); INSERT INTO police_stations (station_id,station_name,zone_id) VALUES (1,'Central',1),(2,'North',2),(3,'South',3); CREATE TABLE zones (zone_id INT,zone_name TEXT); INSERT INTO zones (zone_id,zone_name) VALUES (1,'A'),(2,'B'),(3,'C');
SELECT station_name, zone_name FROM police_stations p JOIN zones z ON p.zone_id = z.zone_id;
Which European country has the highest obesity rate?
CREATE TABLE Europe (Country VARCHAR(50),Population INT,ObesityRate FLOAT); INSERT INTO Europe (Country,Population,ObesityRate) VALUES ('Germany',83.123456,22.1),('France',66.789123,20.5),('United Kingdom',67.564321,24.9),('Italy',60.345678,21.3),('Spain',48.987654,23.2),('Russia',145.678901,25.7),('Poland',38.123456,23.9),('Ukraine',44.567891,24.5),('Netherlands',17.234567,21.8),('Belgium',11.54321,22.4);
SELECT Country, ObesityRate FROM Europe ORDER BY ObesityRate DESC LIMIT 1;
Which strains have the lowest yield in the 'Indica' category?
CREATE TABLE strains (id INT,name TEXT,category TEXT,yield FLOAT); INSERT INTO strains (id,name,category,yield) VALUES (1,'Purple Kush','Indica',0.5),(2,'Northern Lights','Indica',0.6),(3,'Granddaddy Purple','Indica',0.7),(4,'Afghan Kush','Indica',0.8),(5,'Bubba Kush','Indica',0.9);
SELECT name FROM strains WHERE category = 'Indica' ORDER BY yield ASC;
Identify the total funding amount for each biotech startup, along with the average genetic research study funding per year, grouped by industry.
CREATE SCHEMA if not exists genetics; USE genetics; CREATE TABLE if not exists startups (id INT,name VARCHAR(100),industry VARCHAR(100),total_funding DECIMAL(10,2)); CREATE TABLE if not exists studies (id INT,name VARCHAR(100),year INT,funding DECIMAL(10,2)); INSERT INTO startups (id,name,industry,total_funding) VALUES (1,'StartupA','Biotech',10000000.00),(2,'StartupB','AI',15000000.00),(3,'StartupC','Biotech',12000000.00),(4,'StartupD','Software',18000000.00),(5,'StartupE','Bioprocess',20000000.00); INSERT INTO studies (id,name,year,funding) VALUES (1,'StudyA',2015,1000000.00),(2,'StudyB',2016,1500000.00),(3,'StudyC',2017,2000000.00),(4,'StudyD',2018,2500000.00),(5,'StudyE',2019,3000000.00),(6,'StudyF',2020,3500000.00);
SELECT startups.industry, AVG(studies.funding) AS avg_yearly_funding FROM genetics.startups INNER JOIN genetics.studies ON startups.id = studies.id GROUP BY startups.industry;
How many unique ethical labor certifications are there in the labor_certifications table?
CREATE TABLE labor_certifications (certification_id INT,certification_name VARCHAR(50)); INSERT INTO labor_certifications (certification_id,certification_name) VALUES (1,'Fair Trade'),(2,'Certified B Corporation'),(3,'SA8000 Social Accountability');
SELECT COUNT(DISTINCT certification_name) FROM labor_certifications;
What is the total number of disaster preparedness trainings held in the state of California in the year 2019?
CREATE TABLE DisasterPreparedness (id INT,state VARCHAR(20),year INT,training_count INT);
SELECT SUM(training_count) FROM DisasterPreparedness WHERE state = 'California' AND year = 2019;
Identify instructors with no students requiring accommodations.
CREATE TABLE Instructor_Student_Mapping (instructor_id INT,student_id INT);
SELECT i.name as instructor_name FROM Instructors i LEFT JOIN Instructor_Student_Mapping ism ON i.id = ism.instructor_id LEFT JOIN Accommodations a ON ism.student_id = a.student_id WHERE a.id IS NULL;
Compare OTA commission rates for hotels in Asia and Europe.
CREATE TABLE ota_data (hotel_id INT,location VARCHAR(20),ota VARCHAR(20),commission DECIMAL(5,2));
SELECT ota, AVG(commission) as avg_commission FROM ota_data WHERE location IN ('Asia', 'Europe') GROUP BY ota
Which countries received innovation grants over 10 million dollars?
CREATE TABLE Innovation_Grants (Grant_ID INT PRIMARY KEY,Grant_Name VARCHAR(255),Recipient VARCHAR(255),Amount DECIMAL(10,2),Date_Granted DATE); INSERT INTO Innovation_Grants (Grant_ID,Grant_Name,Recipient,Amount,Date_Granted) VALUES (1,'Project STARLIGHT','Lockheed Martin',5000000,'2018-05-15');
SELECT DISTINCT Recipient FROM Innovation_Grants WHERE Amount > 10000000;
Identify the city with the lowest preparedness score in DisasterPreparedness table.
CREATE TABLE DisasterPreparedness (id INT,city VARCHAR(20),year INT,budget DECIMAL(10,2),preparedness_score INT); INSERT INTO DisasterPreparedness (id,city,year,budget,preparedness_score) VALUES (1,'San Francisco',2020,1500000,85); INSERT INTO DisasterPreparedness (id,city,year,budget,preparedness_score) VALUES (2,'New York',2020,2000000,90); INSERT INTO DisasterPreparedness (id,city,year,budget,preparedness_score) VALUES (3,'Los Angeles',2020,1000000,80);
SELECT city, MIN(preparedness_score) OVER () as lowest_preparedness_score FROM DisasterPreparedness WHERE year = 2020;
What is the total carbon emissions for each brand?
CREATE TABLE emissions (id INT,brand VARCHAR(255),emissions FLOAT);
SELECT brand, SUM(emissions) FROM emissions GROUP BY brand;
How many smart contracts were created by developers in each country?
CREATE TABLE developers (developer_id INT,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE smart_contracts (contract_id INT,name VARCHAR(255),developer_id INT); INSERT INTO developers (developer_id,name,country) VALUES (1,'Alice','USA'),(2,'Bob','Canada'),(3,'Charlie','India'),(4,'Dave','Brazil'),(5,'Eve','USA'); INSERT INTO smart_contracts (contract_id,name,developer_id) VALUES (1,'SmartContract1',1),(2,'SmartContract2',2),(3,'SmartContract3',3),(4,'SmartContract4',4),(5,'SmartContract5',5),(6,'SmartContract6',1);
SELECT d.country, COUNT(*) as num_contracts FROM smart_contracts sc JOIN developers d ON sc.developer_id = d.developer_id GROUP BY d.country;
What is the number of clients with a credit card and residing in Texas?
CREATE TABLE clients (client_id INT,name TEXT,dob DATE,branch TEXT,state TEXT);CREATE TABLE accounts (account_id INT,client_id INT,account_type TEXT);INSERT INTO clients VALUES (4,'Alice Davis','1985-02-25','Houston','Texas');INSERT INTO accounts VALUES (104,4,'Credit Card');
SELECT COUNT(*) FROM clients INNER JOIN accounts ON clients.client_id = accounts.client_id WHERE accounts.account_type = 'Credit Card' AND clients.state = 'Texas';
What is the average area of organic farming per farm in 'Africa'?
CREATE TABLE organic_farms (id INT,country VARCHAR(50),region VARCHAR(50),no_farms INT,area_ha FLOAT); INSERT INTO organic_farms (id,country,region,no_farms,area_ha) VALUES (1,'Kenya','Africa',1000,5678.9); INSERT INTO organic_farms (id,country,region,no_farms,area_ha) VALUES (2,'Tanzania','Africa',2000,8765.4); INSERT INTO organic_farms (id,country,region,no_farms,area_ha) VALUES (3,'Nigeria','Africa',1500,3456.7);
SELECT AVG(area_ha/no_farms) FROM organic_farms WHERE region = 'Africa';
What percentage of products sourced from Australia have natural ingredients?
CREATE TABLE products_ext(id INT,name TEXT,source_country TEXT,natural_ingredients BOOLEAN); INSERT INTO products_ext(id,name,source_country,natural_ingredients) VALUES (1,'Cleanser X','US',true),(2,'Lotion Y','France',true),(3,'Shampoo Z','Australia',false),(4,'Conditioner W','Canada',true),(5,'Moisturizer V','Australia',true);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM products_ext WHERE source_country = 'Australia')) AS percentage FROM products_ext WHERE natural_ingredients = true AND source_country = 'Australia';
What is the production rate of wells with a depth greater than 15000 feet in the 'Wells' table, ordered by production rate in descending order?
CREATE TABLE Wells (well_id INT,location VARCHAR(50),depth INT,production_rate FLOAT); INSERT INTO Wells (well_id,location,depth,production_rate) VALUES (1,'Oklahoma',16000,500),(2,'Texas',14000,400),(3,'Louisiana',18000,600),(4,'Alabama',15500,450);
SELECT production_rate FROM (SELECT well_id, location, depth, production_rate, ROW_NUMBER() OVER (ORDER BY production_rate DESC) as rank FROM Wells WHERE depth > 15000) AS wells_filtered WHERE rank <= 5;
Which journalists published the most articles in 2018?
CREATE TABLE journalists (journalist_id INT,name TEXT,article_count INT);
SELECT name, article_count FROM journalists WHERE publish_date >= '2018-01-01' AND publish_date < '2019-01-01' ORDER BY article_count DESC LIMIT 1;
What is the total number of members in unions that have a focus on healthcare?
CREATE TABLE unions (id INT,name TEXT,domain TEXT); INSERT INTO unions (id,name,domain) VALUES (1,'National Nurses United','Healthcare'); INSERT INTO unions (id,name,domain) VALUES (2,'Service Employees International Union','Healthcare,Public Services');
SELECT COUNT(*) FROM unions WHERE domain LIKE '%Healthcare%';
What is the total amount of coal and iron depleted by each mining operation in the last quarter?
CREATE TABLE ResourceDepletion (Operation VARCHAR(50),Resource VARCHAR(50),DepletionQuantity FLOAT); INSERT INTO ResourceDepletion(Operation,Resource,DepletionQuantity) VALUES ('Operation A','Coal',12000),('Operation A','Iron',15000),('Operation B','Coal',10000),('Operation B','Iron',18000),('Operation C','Coal',16000),('Operation C','Iron',13000),('Operation A','Coal',11000),('Operation A','Iron',14000),('Operation B','Coal',9000),('Operation B','Iron',17000);
SELECT Operation, SUM(DepletionQuantity) FROM ResourceDepletion WHERE Resource IN ('Coal', 'Iron') AND DepletionQuantity >= 0 GROUP BY Operation;
What was the average waiting time in hours for vessels arriving at the Port of Singapore in Q1 2020?
CREATE TABLE vessel_status (id INT PRIMARY KEY,vessel_id INT,status VARCHAR(50),timestamp TIMESTAMP);
SELECT AVG(TIMESTAMPDIFF(HOUR, vessel_status.timestamp, lead(vessel_status.timestamp) OVER (PARTITION BY vessel_id ORDER BY vessel_status.timestamp))) FROM vessel_status WHERE status = 'arrived' AND DATE(vessel_status.timestamp) BETWEEN '2020-01-01' AND '2020-03-31' GROUP BY vessel_id;
What is the third highest account balance for microfinance customers in the West region?
CREATE TABLE customers (customer_id INT,name VARCHAR(50),region VARCHAR(20),account_balance DECIMAL(10,2)); INSERT INTO customers (customer_id,name,region,account_balance) VALUES (1,'John Doe','South',5000.00),(2,'Jane Smith','North',7000.00);
SELECT DISTINCT account_balance FROM (SELECT account_balance, ROW_NUMBER() OVER (PARTITION BY region ORDER BY account_balance DESC) as rn FROM customers WHERE region = 'West' AND product_type = 'Microfinance') as sub WHERE rn = 3;
Show vessels with outdated safety certifications before 2010
CREATE TABLE vessels (vessel_id INT,name VARCHAR(50),certificate_expiration_date DATE);
SELECT name FROM vessels WHERE certificate_expiration_date < '2010-01-01';
List all smart city initiatives that have been implemented in the European Union.
CREATE TABLE smart_city_initiatives (initiative_id INT,country VARCHAR(50),city VARCHAR(100),status VARCHAR(50)); INSERT INTO smart_city_initiatives (initiative_id,country,city,status) VALUES (1,'France','Paris','Implemented');
SELECT city, status FROM smart_city_initiatives WHERE country = 'European Union';
List the number of veteran unemployed per state in March 2021
CREATE TABLE VeteranEmployment (id INT,state VARCHAR(50),status VARCHAR(50),unemployed_date DATE); INSERT INTO VeteranEmployment (id,state,status,unemployed_date) VALUES (1,'California','Unemployed','2021-03-01');
SELECT state, COUNT(*) FROM VeteranEmployment WHERE EXTRACT(MONTH FROM unemployed_date) = 3 AND EXTRACT(YEAR FROM unemployed_date) = 2021 AND status = 'Unemployed' GROUP BY state;
What is the average temperature recorded in the 'arctic_weather' table for each month in 2020?
CREATE TABLE arctic_weather (date DATE,temperature FLOAT);
SELECT AVG(temperature) FROM arctic_weather WHERE EXTRACT(YEAR FROM date) = 2020 GROUP BY EXTRACT(MONTH FROM date);
Total sales of organic cosmetics by quarter?
CREATE TABLE sales_data (sale_id INT,product_id INT,sale_date DATE,organic BOOLEAN); INSERT INTO sales_data (sale_id,product_id,sale_date,organic) VALUES (1,101,'2022-01-05',true),(2,102,'2022-02-10',false),(3,103,'2022-03-15',true);
SELECT DATEPART(quarter, sale_date) as quarter, SUM(CASE WHEN organic THEN 1 ELSE 0 END) as organic_sales FROM sales_data GROUP BY DATEPART(quarter, sale_date);
How many safety incidents were reported for each vessel type in 2021?
CREATE TABLE incidents (id INT,vessel_id INT,type VARCHAR(50),date DATE); INSERT INTO incidents (id,vessel_id,type,date) VALUES (1,1,'Collision','2021-03-15'); INSERT INTO incidents (id,vessel_id,type,date) VALUES (2,1,'Grounding','2021-08-22'); INSERT INTO incidents (id,vessel_id,type,date) VALUES (3,2,'Fire','2021-02-03'); INSERT INTO incidents (id,vessel_id,type,date) VALUES (4,2,'Collision','2021-11-09');
SELECT type as vessel_type, COUNT(*) as incident_count FROM incidents WHERE date >= '2021-01-01' AND date < '2022-01-01' GROUP BY vessel_type;
Update the installed capacity of 'Windfarm A' in the 'wind_farms' table to 55.0, and also update its end_date to '2025-12-31'
CREATE TABLE wind_farms (id INT,country VARCHAR(255),name VARCHAR(255),capacity FLOAT,start_date DATE,end_date DATE); INSERT INTO wind_farms (id,country,name,capacity,start_date,end_date) VALUES (1,'Germany','Windfarm A',50.5,'2020-01-01','2024-12-31');
UPDATE wind_farms SET capacity = 55.0, end_date = '2025-12-31' WHERE name = 'Windfarm A';
Insert new records for visitors from Nigeria, South Africa, and Egypt into the visitors table
CREATE TABLE visitors (id INT,age INT,gender TEXT,country TEXT);
INSERT INTO visitors (id, age, gender, country) VALUES (7001, 28, 'Male', 'Nigeria'), (7002, 35, 'Female', 'South Africa'), (7003, 42, 'Male', 'Egypt');
What is the average fare for trains in the 'south' region?
CREATE TABLE train_fares (fare_id INT,region_id INT,fare DECIMAL(5,2)); INSERT INTO train_fares (fare_id,region_id,fare) VALUES (1,1,3.50),(2,2,4.25),(3,3,3.75),(4,2,4.25);
SELECT AVG(tf.fare) FROM train_fares tf INNER JOIN regions r ON tf.region_id = r.region_id WHERE r.region_name = 'south';
Update the name of soldier with ID 2001 to 'Emily Davis' in the soldiers_personal_data table
CREATE TABLE soldiers_personal_data (soldier_id INT,name VARCHAR(50),rank VARCHAR(50),departure_date DATE);
UPDATE soldiers_personal_data SET name = 'Emily Davis' WHERE soldier_id = 2001;
How many spacecraft were launched per year?
CREATE TABLE spacecraft_launches (spacecraft_name VARCHAR(50),launch_year INT);
SELECT launch_year, COUNT(*) as num_launches FROM spacecraft_launches GROUP BY launch_year;
What is the total revenue generated from broadband services in the state of New York?
CREATE TABLE broadband_customers (customer_id INT,monthly_revenue FLOAT,state VARCHAR(20)); INSERT INTO broadband_customers (customer_id,monthly_revenue,state) VALUES (11,60,'New York'),(12,70,'New York'),(13,55,'California'),(14,65,'Texas'),(15,75,'New York');
SELECT SUM(monthly_revenue) FROM broadband_customers WHERE state = 'New York';