instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the number of active astronauts who have been on the ISS.
CREATE TABLE astronauts (id INT,name VARCHAR(50),status VARCHAR(50),missions VARCHAR(50)); INSERT INTO astronauts (id,name,status,missions) VALUES (1,'Neil Armstrong','deceased','Apollo 11'); INSERT INTO astronauts (id,name,status,missions) VALUES (2,'Scott Kelly','active','ISS,STS-103');
SELECT COUNT(*) FROM astronauts WHERE status = 'active' AND FIND_IN_SET('ISS', missions) > 0;
How many customers have savings greater than '8000'?
CREATE TABLE savings (customer_id INT,name TEXT,state TEXT,savings DECIMAL(10,2)); INSERT INTO savings (customer_id,name,state,savings) VALUES (7,'James Davis','New York',9000.00),(8,'Mia Anderson','Texas',10000.00);
SELECT COUNT(*) FROM savings WHERE savings > 8000;
What is the daily sales amount for each menu category in October 2022?
CREATE TABLE sales (sale_date DATE,menu_category VARCHAR(255),sales_amount DECIMAL(10,2)); INSERT INTO sales (sale_date,menu_category,sales_amount) VALUES ('2022-10-01','Appetizers',300.00),('2022-10-01','Entrees',800.00),('2022-10-01','Desserts',400.00),('2022-10-02','Appetizers',400.00),('2022-10-02','Entrees',700.00),('2022-10-02','Desserts',500.00);
SELECT menu_category, SUM(sales_amount) AS daily_sales FROM sales WHERE sale_date BETWEEN '2022-10-01' AND '2022-10-31' GROUP BY menu_category;
How many tourists from each country visited sustainable destinations?
CREATE TABLE Sustainable_Destinations (id INT,destination_name VARCHAR(50),sustainable BOOLEAN); CREATE TABLE Tourists_Destinations (tourist_id INT,destination_id INT,visit_date DATE); INSERT INTO Sustainable_Destinations VALUES (1,'Eco Village',true); INSERT INTO Sustainable_Destinations VALUES (2,'Green City',true); INSERT INTO Tourists_Destinations VALUES (1,1,'2022-01-01'); INSERT INTO Tourists_Destinations VALUES (2,2,'2022-01-02'); INSERT INTO Tourists_Destinations VALUES (3,1,'2022-01-03');
SELECT Tourists.nationality, COUNT(DISTINCT Tourists_Destinations.tourist_id) AS num_tourists FROM Tourists_Destinations INNER JOIN Tourists ON Tourists_Destinations.tourist_id = Tourists.id INNER JOIN Sustainable_Destinations ON Tourists_Destinations.destination_id = Sustainable_Destinations.id WHERE Sustainable_Destinations.sustainable = true GROUP BY Tourists.nationality;
Calculate the total number of tracks and revenue generated from digital music sales for the Latin genre.
CREATE TABLE MusicSales (sale_id INT,sale_date DATE,sale_amount DECIMAL(10,2),genre VARCHAR(20),track_id INT); CREATE TABLE Tracks (track_id INT,track_name VARCHAR(50),genre VARCHAR(20),artist_id INT); CREATE TABLE Artists (artist_id INT,artist_name VARCHAR(50),genre VARCHAR(20));
SELECT COUNT(t.track_id) as total_tracks, SUM(ms.sale_amount) as total_revenue FROM Tracks t INNER JOIN MusicSales ms ON t.track_id = ms.track_id INNER JOIN Artists a ON t.genre = a.genre WHERE a.genre = 'Latin';
What is the minimum number of days to remediate vulnerabilities in the manufacturing sector?
CREATE TABLE manufacturing_sector (sector VARCHAR(255),vulnerability VARCHAR(255),remediation_days INT); INSERT INTO manufacturing_sector (sector,vulnerability,remediation_days) VALUES ('Manufacturing','Vulnerability A',20),('Manufacturing','Vulnerability B',30),('Manufacturing','Vulnerability C',40),('Manufacturing','Vulnerability D',50),('Manufacturing','Vulnerability E',60);
SELECT MIN(remediation_days) FROM manufacturing_sector WHERE sector = 'Manufacturing';
How many genetic research projects are ongoing in Canada?
CREATE SCHEMA if not exists genetics; USE genetics; CREATE TABLE if not exists research_status (id INT,project_id INT,status VARCHAR(255)); INSERT INTO research_status (id,project_id,status) VALUES (1,1,'Ongoing'),(2,2,'Completed'),(3,3,'On Hold');
SELECT COUNT(*) FROM genetics.research_status WHERE project_id IN (SELECT id FROM genetics.research_projects WHERE country = 'Canada') AND status = 'Ongoing';
What is the maximum number of courses completed by a single teacher in a year?
CREATE TABLE teachers (id INT,name VARCHAR(255)); CREATE TABLE courses (id INT,name VARCHAR(255),start_date DATE,end_date DATE); CREATE TABLE teacher_courses (teacher_id INT,course_id INT,completed DATE);
SELECT t.name, MAX(COUNT(tc.teacher_id)) as max_courses FROM teacher_courses tc JOIN courses c ON tc.course_id = c.id JOIN teachers t ON tc.teacher_id = t.id WHERE c.start_date <= '2022-01-01' AND c.end_date >= '2022-12-31' GROUP BY t.id;
What is the total number of vehicles at the 'New York Auto Show' in the 'auto_shows' schema?
CREATE TABLE auto_shows (id INT,name VARCHAR(50),location VARCHAR(50)); CREATE TABLE vehicles_at_shows (id INT,auto_show_id INT,vehicle_count INT); INSERT INTO auto_shows VALUES (1,'New York Auto Show','New York'); INSERT INTO vehicles_at_shows VALUES (1,1,600);
SELECT SUM(vehicle_count) FROM vehicles_at_shows WHERE auto_show_id = (SELECT id FROM auto_shows WHERE name = 'New York Auto Show');
List employees who joined after January 1st, 2022 in the "finance" schema
CREATE TABLE finance.employees (id INT,name VARCHAR(50),hire_date DATE); INSERT INTO finance.employees (id,name,hire_date) VALUES (1,'Alice Johnson','2021-02-01'); INSERT INTO finance.employees (id,name,hire_date) VALUES (2,'Bob Brown','2021-03-15'); INSERT INTO finance.employees (id,name,hire_date) VALUES (3,'Jessica Lee','2022-01-01'); INSERT INTO finance.employees (id,name,hire_date) VALUES (4,'Ravi Patel','2022-04-03');
SELECT * FROM finance.employees WHERE hire_date > '2022-01-01';
List all the unique tags used in articles related to 'climate change' across 'The New York Times' and 'The Washington Post'.
CREATE TABLE nytimes (id INT,title VARCHAR(255),content TEXT,tags TEXT,pub_date DATE); INSERT INTO nytimes (id,title,content,tags,pub_date) VALUES (1,'Title1','Content1','climate change,tag1','2022-01-01'); CREATE TABLE wa_post (id INT,title VARCHAR(255),content TEXT,tags TEXT,pub_date DATE); INSERT INTO wa_post (id,title,content,tags,pub_date) VALUES (1,'Title2','Content2','climate change,tag2','2022-01-02');
SELECT DISTINCT trim(SPLIT_PART(tags, ',', n)) as tag FROM (SELECT tags, generate_series(1, ARRAY_LENGTH(string_to_array(tags, ','))) as n FROM (SELECT tags FROM nytimes WHERE lower(tags) like '%climate change%' UNION ALL SELECT tags FROM wa_post WHERE lower(tags) like '%climate change%') subquery) sq;
What is the average time interval between intrusion detection events for a specific destination IP, grouped by the protocol, while excluding the first event?
CREATE TABLE intrusion_detection (id INT,src_ip VARCHAR(50),dst_ip VARCHAR(50),protocol VARCHAR(10),timestamp DATETIME); INSERT INTO intrusion_detection (id,src_ip,dst_ip,protocol,timestamp) VALUES (1,'192.168.0.10','8.8.8.8','TCP','2022-02-01 14:20:00');
SELECT protocol, AVG(timestamp - LAG(timestamp) OVER (PARTITION BY dst_ip ORDER BY timestamp)) as avg_interval FROM intrusion_detection WHERE dst_ip = '8.8.8.8' GROUP BY protocol;
Find the average virtual tourism revenue for the Asia-Pacific region.
CREATE TABLE revenue (revenue_id INT,hotel_name VARCHAR(255),region VARCHAR(255),revenue INT); INSERT INTO revenue (revenue_id,hotel_name,region,revenue) VALUES (1,'The Royal Palace Hotel','Asia-Pacific',50000);
SELECT AVG(revenue) FROM revenue WHERE region = 'Asia-Pacific';
Find all cruelty-free products with a user rating greater than 4.5
Products (product_id,name,rating,cruelty_free)
SELECT * FROM Products WHERE cruelty_free = 'yes' AND rating > 4.5
How many unique medical conditions have affected astronauts?
CREATE TABLE Astronauts (AstronautID INT,Name VARCHAR(50),Gender VARCHAR(10)); CREATE TABLE MedicalConditions (ConditionID INT,Condition VARCHAR(50),AstronautID INT);
SELECT COUNT(DISTINCT Condition) FROM MedicalConditions;
List all startups founded by people from the LGBTQ+ community
CREATE TABLE startups (id INT,name TEXT,founding_year INT,founder_identity TEXT);
SELECT * FROM startups WHERE founder_identity IS NOT NULL AND founder_identity LIKE '%LGBTQ%';
What is the minimum wage in factories per region?
CREATE TABLE wages (id INT,factory_id INT,region VARCHAR(50),hourly_wage DECIMAL(5,2));
SELECT region, MIN(hourly_wage) AS min_wage FROM wages GROUP BY region;
What is the total number of players who have played a game with the genre 'Action' and a rating of 8 or higher?
CREATE TABLE PlayerGames (PlayerID int,Age int,GameGenre varchar(10),GameRating int); INSERT INTO PlayerGames (PlayerID,Age,GameGenre,GameRating) VALUES (1,30,'Action',9),(2,25,'Strategy',8);
SELECT COUNT(*) FROM PlayerGames WHERE GameGenre = 'Action' AND GameRating >= 8;
How many ethical and non-ethical products are sold by each retailer?
CREATE TABLE Retailer (id INT,name VARCHAR(255),type VARCHAR(255)); CREATE TABLE Product (id INT,name VARCHAR(255),retailer_id INT,ethical BOOLEAN);
SELECT r.name, COUNT(p.id) FILTER (WHERE p.ethical) as ethical_products_count, COUNT(p.id) FILTER (WHERE NOT p.ethical) as non_ethical_products_count FROM Retailer r JOIN Product p ON r.id = p.retailer_id GROUP BY r.name;
What is the maximum number of employees in the Mining Operations department from a single community?
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(255),Community VARCHAR(255)); INSERT INTO Employees (EmployeeID,Department,Community) VALUES (1,'Mining Operations','Community A'),(2,'Mining Operations','Community B'),(3,'Mining Operations','Community A');
SELECT Department, Community, MAX(COUNT(*)) OVER (PARTITION BY Department) FROM Employees GROUP BY Department, Community;
Identify the container ships that have a higher capacity than the average capacity of all container ships.
CREATE TABLE fleet (id INT,name VARCHAR(50),capacity INT,type VARCHAR(50)); INSERT INTO fleet VALUES (1,'ShipA',10000,'Container'),(2,'ShipB',12000,'Container'),(3,'ShipC',8000,'Container'),(4,'ShipD',5000,'Tanker');
SELECT * FROM fleet WHERE type = 'Container' AND capacity > (SELECT AVG(capacity) FROM fleet WHERE type = 'Container');
What is the average carbon offset (in metric tons) for carbon offset programs in Europe that were initiated in 2018?
CREATE TABLE if not exists carbon_offset_programs (program_id integer,program_start_date date,program_location varchar(255),carbon_offset_tons integer); INSERT INTO carbon_offset_programs (program_id,program_start_date,program_location,carbon_offset_tons) VALUES (1,'2018-01-01','France',2000),(2,'2018-06-01','Germany',2500),(3,'2018-12-31','Spain',1500);
SELECT program_location, AVG(carbon_offset_tons) as avg_offset FROM carbon_offset_programs WHERE program_start_date BETWEEN '2018-01-01' AND '2018-12-31' AND program_location LIKE 'Europe%' GROUP BY program_location;
What is the total quantity of item 'APP-01' in all warehouses?
CREATE TABLE warehouse (id INT,name VARCHAR(255),location VARCHAR(255)); INSERT INTO warehouse (id,name,location) VALUES (1,'NY','New York'),(2,'LA','Los Angeles'); CREATE TABLE inventory (item_code VARCHAR(255),quantity INT,warehouse_id INT); INSERT INTO inventory (item_code,quantity,warehouse_id) VALUES ('EGG-01',300,1),('APP-01',200,1),('APP-01',100,2);
SELECT SUM(quantity) FROM inventory WHERE item_code = 'APP-01';
Which biosensors were developed in the EU?
CREATE TABLE biosensors(id INT,name VARCHAR(50),country VARCHAR(50),development_date DATE);INSERT INTO biosensors (id,name,country,development_date) VALUES (1,'BioSensorA','USA','2021-03-01');INSERT INTO biosensors (id,name,country,development_date) VALUES (2,'BioSensorB','Germany','2020-12-10');
SELECT name FROM biosensors WHERE country LIKE 'EU%';
What was the total distance traveled by all vessels?
CREATE TABLE journeys (vessel VARCHAR(20),speed INT,distance INT); INSERT INTO journeys (vessel,speed,distance) VALUES ('Aurelia',20,100),('Aurelia',22,120),('Belfast',25,150),('Belfast',24,140),('Belfast',26,160),('Caledonia',21,110),('Caledonia',23,130);
SELECT SUM(distance) FROM journeys;
How many albums were released by jazz artists between 1980 and 1999?
CREATE TABLE artists (artist_id INT,artist_name VARCHAR(255),genre VARCHAR(255)); CREATE TABLE albums (album_id INT,album_name VARCHAR(255),release_year INT,artist_id INT); INSERT INTO artists (artist_id,artist_name,genre) VALUES (1,'Miles Davis','Jazz'); INSERT INTO albums (album_id,album_name,release_year,artist_id) VALUES (1,'The Man with the Horn',1981,1);
SELECT COUNT(*) FROM albums JOIN artists ON albums.artist_id = artists.artist_id WHERE artists.genre = 'Jazz' AND albums.release_year BETWEEN 1980 AND 1999;
Count the number of patients diagnosed with any disease in the 'California' region, grouped by gender.
CREATE TABLE Patients (PatientID INT,Age INT,Gender VARCHAR(10),Disease VARCHAR(20),Region VARCHAR(20)); INSERT INTO Patients (PatientID,Age,Gender,Disease,Region) VALUES (1,34,'Male','Influenza','Los Angeles'); INSERT INTO Patients (PatientID,Age,Gender,Disease,Region) VALUES (2,42,'Female','Pneumonia','New York');
SELECT Gender, COUNT(*) FROM Patients WHERE Region = 'California' GROUP BY Gender;
Update 'material_source' table, setting 'certified' column as 'yes' if 'sustainability_score' is greater than or equal to 80
CREATE TABLE material_source (id INT PRIMARY KEY,name VARCHAR(50),sustainability_score INT,certified VARCHAR(10)); INSERT INTO material_source (id,name,sustainability_score,certified) VALUES (1,'Organic Cotton',85,'no'),(2,'Recycled Polyester',70,'no'),(3,'Tencel',90,'no');
UPDATE material_source SET certified = 'yes' WHERE sustainability_score >= 80;
What are the top 3 most expensive concessions for each stadium?
CREATE TABLE Concessions (ConcessionID INT,Item VARCHAR(50),Price DECIMAL(5,2),StadiumID INT); INSERT INTO Concessions VALUES (1,'Hotdog',5,1); INSERT INTO Concessions VALUES (2,'Popcorn',3,1); INSERT INTO Concessions VALUES (3,'Nachos',6,2); INSERT INTO Concessions VALUES (4,'Soda',4,2); INSERT INTO Concessions VALUES (5,'Pretzel',7,2);
SELECT ConcessionID, Item, Price, StadiumID, ROW_NUMBER() OVER (PARTITION BY StadiumID ORDER BY Price DESC) AS PriceRank FROM Concessions WHERE PriceRank <= 3;
Update the 'LastEruption' date of the 'Eyjafjallajökull' volcano in the 'UnderwaterVolcanoes' table
CREATE TABLE UnderwaterVolcanoes (VolcanoID INT,VolcanoName VARCHAR(255),Location VARCHAR(255),LastEruption DATE);
UPDATE UnderwaterVolcanoes SET LastEruption = '2010-04-14' WHERE VolcanoName = 'Eyjafjallajökull';
What is the total budget for mental health campaigns in a specific region?
CREATE TABLE Campaigns (CampaignID INT,Year INT,Budget INT,Region VARCHAR(50)); CREATE TABLE MentalHealthCampaigns (CampaignID INT,CampaignName VARCHAR(50));
SELECT Campaigns.Region, SUM(Campaigns.Budget) FROM Campaigns INNER JOIN MentalHealthCampaigns ON Campaigns.CampaignID = MentalHealthCampaigns.CampaignID GROUP BY Campaigns.Region;
What is the average attendance for cultural events in 'Paris' and 'Berlin'?
CREATE TABLE cultural_events (id INT,city VARCHAR(20),attendance INT); INSERT INTO cultural_events (id,city,attendance) VALUES (1,'Paris',2000),(2,'Berlin',3000),(3,'New York',2500),(4,'Paris',2200),(5,'Berlin',2800);
SELECT city, AVG(attendance) FROM cultural_events GROUP BY city HAVING city IN ('Paris', 'Berlin');
What is the total revenue generated by local tour operators in India for the year 2021?
CREATE TABLE LocalTourOperators (name VARCHAR(50),location VARCHAR(20),year INT,revenue DECIMAL(10,2));
SELECT SUM(revenue) FROM LocalTourOperators WHERE location = 'India' AND year = 2021;
How many total unique visitors identified as artists visited events in the last 90 days?
CREATE TABLE Events (EventID int,EventName varchar(50),Attendance int,VisitorProfession varchar(50)); INSERT INTO Events VALUES (1,'Photography Workshop',50,'Artist'),(2,'Writing Seminar',30,'Writer'),(3,'Sculpture Class',40,'Artist');
SELECT COUNT(DISTINCT VisitorProfession) FROM Events WHERE EXTRACT(DAY FROM EventDate) BETWEEN EXTRACT(DAY FROM CURRENT_DATE - INTERVAL '90 days') AND EXTRACT(DAY FROM CURRENT_DATE) AND VisitorProfession = 'Artist';
Which crops were harvested in 'spring 2021' from the 'urban_farms' table?
CREATE TABLE urban_farms (id INT,name VARCHAR(50),location VARCHAR(50),crop VARCHAR(50),harvest_date DATE);
SELECT * FROM urban_farms WHERE harvest_date BETWEEN '2021-03-01' AND '2021-05-31';
What is the total number of disaster preparedness centers in coastal areas and the total number of training sessions conducted at these centers, broken down by training type?
CREATE TABLE disaster_preparedness_centers (id INT,center_name TEXT,location TEXT); INSERT INTO disaster_preparedness_centers (id,center_name,location) VALUES (1,'Center A','Coastal'),(2,'Center B','Inland'),(3,'Center C','Coastal'),(4,'Center D','Mountain'); CREATE TABLE training_sessions (id INT,center_id INT,training_type TEXT,session_count INT); INSERT INTO training_sessions (id,center_id,training_type,session_count) VALUES (1,1,'First Aid',20),(2,1,'CPR',30),(3,2,'First Aid',40),(4,2,'CPR',50),(5,3,'First Aid',25),(6,3,'CPR',35),(7,4,'First Aid',15),(8,4,'CPR',20);
SELECT c.location, training_type, SUM(session_count) AS total_sessions FROM disaster_preparedness_centers c JOIN training_sessions s ON c.id = s.center_id WHERE c.location = 'Coastal' GROUP BY c.location, training_type;
How many climate mitigation projects are led by women?
CREATE TABLE projects (id INT PRIMARY KEY,name VARCHAR(255),leader_gender VARCHAR(10),sector VARCHAR(255),region VARCHAR(255)); INSERT INTO projects (id,name,leader_gender,sector,region) VALUES (1,'Wind Power','Female','Renewable Energy','Europe'),(2,'Smart Grid','Male','Energy Efficiency','North America'),(3,'Reforestation','Female','Land Use','South America'),(4,'Coastal Protection','Male','Adaptation','Asia');
SELECT COUNT(*) FROM projects WHERE leader_gender = 'Female' AND sector = 'Renewable Energy' OR sector = 'Land Use';
Landfill capacity for each region in 2022?
CREATE TABLE landfill_capacity (region VARCHAR(50),year INT,capacity INT); INSERT INTO landfill_capacity (region,year,capacity) VALUES ('Africa',2022,1500),('Asia',2022,4000),('Europe',2022,3500),('North America',2022,4200),('South America',2022,3000),('Oceania',2022,2400);
SELECT region, capacity FROM landfill_capacity WHERE year = 2022;
What is the total number of graduate students per department?
CREATE TABLE departments (id INT,name VARCHAR(255)); INSERT INTO departments (id,name) VALUES (1,'Biology'),(2,'Mathematics'),(3,'Sociology'); CREATE TABLE graduate_students (id INT,department_id INT,gender VARCHAR(10),num_students INT); INSERT INTO graduate_students (id,department_id,gender,num_students) VALUES (1,1,'Female',50),(2,1,'Male',30),(3,2,'Female',20),(4,2,'Non-binary',10),(5,3,'Male',40),(6,3,'Female',35);
SELECT d.name, SUM(gs.num_students) FROM departments d JOIN graduate_students gs ON d.id = gs.department_id GROUP BY d.name;
Delete all records from the agricultural_robot_metrics table where battery_level is below 20% and timestamp is older than a month
CREATE TABLE agricultural_robot_metrics (robot_id INT,battery_level DECIMAL(3,1),metric_timestamp DATETIME);
DELETE FROM agricultural_robot_metrics WHERE battery_level < 20.0 AND metric_timestamp <= DATEADD(month, -1, GETDATE());
What was the total sales amount for each product category by country in 2022?
CREATE TABLE sales_2022 AS SELECT * FROM sales WHERE sale_date BETWEEN '2022-01-01' AND '2022-12-31'; ALTER TABLE sales_2022 ADD COLUMN country_region VARCHAR(50); UPDATE sales_2022 SET country_region = CASE WHEN sale_country = 'Brazil' THEN 'South America' WHEN sale_country = 'India' THEN 'Asia' WHEN sale_country = 'USA' THEN 'North America' WHEN sale_country = 'Italy' THEN 'Europe' ELSE country_region END;
SELECT country_region, product_category, SUM(sale_amount) FROM sales_2022 GROUP BY country_region, product_category;
What is the total number of medical facilities constructed in "Africa" before 2020?
CREATE TABLE medical_facilities (id INT,project_id INT,location VARCHAR(255),construction_date DATE); INSERT INTO medical_facilities (id,project_id,location,construction_date) VALUES (1,6001,'Kenya','2019-05-01'); INSERT INTO medical_facilities (id,project_id,location,construction_date) VALUES (2,6002,'Nigeria','2018-02-01');
SELECT COUNT(*) FROM medical_facilities WHERE location = 'Africa' AND YEAR(construction_date) < 2020;
What are the names and corresponding authors of all algorithmic fairness papers in the 'ACM FAccT' conference?
CREATE TABLE fairness_papers (paper_name VARCHAR(255),conference VARCHAR(255),author VARCHAR(255)); INSERT INTO fairness_papers (paper_name,conference,author) VALUES ('Bias in AI','ACM FAccT','Joanna Bryson'),('Fairness Metrics','ACM FAccT','Moritz Hardt');
SELECT paper_name, author FROM fairness_papers WHERE conference = 'ACM FAccT'
What is the total revenue for each mobile plan?
CREATE TABLE subscriber_data (subscriber_id INT,plan_id INT,monthly_charge DECIMAL(10,2)); INSERT INTO subscriber_data (subscriber_id,plan_id,monthly_charge) VALUES (1,1,50.00),(2,2,70.00),(3,3,100.00); CREATE TABLE mobile_plans (plan_id INT,plan_name VARCHAR(255),monthly_revenue DECIMAL(10,2));
INSERT INTO mobile_plans (plan_id, plan_name, monthly_revenue) SELECT plan_id, plan_name, SUM(monthly_charge) FROM subscriber_data GROUP BY plan_id;
What is the average daily transaction amount per customer?
CREATE TABLE customer_transactions (transaction_date DATE,customer_id INT,transaction_amt DECIMAL(10,2)); INSERT INTO customer_transactions (transaction_date,customer_id,transaction_amt) VALUES ('2022-01-01',1,200.00),('2022-01-02',2,300.50),('2022-01-03',3,150.25);
SELECT customer_id, AVG(transaction_amt) OVER (PARTITION BY customer_id) AS avg_daily_transaction_amt FROM customer_transactions;
How many cases were won by each attorney?
CREATE TABLE Attorneys (AttorneyID int,Name varchar(50)); INSERT INTO Attorneys VALUES (1,'Smith'),(2,'Johnson'); CREATE TABLE Cases (CaseID int,AttorneyID int,Outcome varchar(10)); INSERT INTO Cases VALUES (1,1,'Won'),(2,1,'Lost'),(3,2,'Won');
SELECT A.Name, COUNT(C.CaseID) as WonCases FROM Attorneys A INNER JOIN Cases C ON A.AttorneyID = C.AttorneyID WHERE C.Outcome = 'Won' GROUP BY A.Name;
What is the total amount of funding received by graduate students from research grants in the Humanities department who have published in the past year?
CREATE TABLE graduate_students (id INT,name VARCHAR(50),department VARCHAR(50)); CREATE TABLE research_grants (id INT,graduate_student_id INT,amount DECIMAL(10,2)); CREATE TABLE publications (id INT,graduate_student_id INT,publication_date DATE);
SELECT SUM(rg.amount) FROM research_grants rg JOIN graduate_students gs ON rg.graduate_student_id = gs.id JOIN publications p ON gs.id = p.graduate_student_id WHERE gs.department = 'Humanities' AND p.publication_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
Find the number of structures ('dam', 'bridge', 'tunnel') and their respective ages (in years) in the 'civil_engineering_structures' and 'structure_construction_dates' tables.
CREATE TABLE civil_engineering_structures (id INT,name VARCHAR(255),type VARCHAR(255),location VARCHAR(255)); CREATE TABLE structure_construction_dates (structure_id INT,year INT);
SELECT ce.type, COUNT(ce.id) as number_of_structures, YEAR(CURRENT_DATE) - scd.year as age_in_years FROM civil_engineering_structures ce INNER JOIN structure_construction_dates scd ON ce.id = scd.structure_id GROUP BY ce.type;
How many wells were drilled in each country in the year 2020?
CREATE TABLE wells (well_id INT,well_name TEXT,drill_year INT,country TEXT); INSERT INTO wells (well_id,well_name,drill_year,country) VALUES (1,'Well A',2020,'USA'),(2,'Well B',2019,'Canada'),(3,'Well C',2020,'Mexico');
SELECT country, COUNT(*) as well_count FROM wells WHERE drill_year = 2020 GROUP BY country;
How many veterans are employed in the defense industry in Texas?
CREATE TABLE veteran_employment (industry VARCHAR(255),state VARCHAR(255),employment NUMERIC); INSERT INTO veteran_employment (industry,state,employment) VALUES ('Defense','Texas',15000),('Aerospace','Texas',10000);
SELECT employment FROM veteran_employment WHERE industry = 'Defense' AND state = 'Texas';
What is the total carbon offset of smart city initiatives in Asia, broken down by quarter?
CREATE TABLE smart_city_initiatives (id INT,initiative_name VARCHAR(255),country VARCHAR(255),carbon_offset FLOAT,start_quarter DATE);
SELECT QUARTER(start_quarter) AS quarter, SUM(carbon_offset) FROM smart_city_initiatives WHERE country = 'Asia' GROUP BY quarter;
What is the minimum weight lifted by users in the 'Advanced' workout group?
CREATE TABLE workout_groups (id INT,user_id INT,group_label VARCHAR(10)); INSERT INTO workout_groups (id,user_id,group_label) VALUES (1,7,'Beginner'); INSERT INTO workout_groups (id,user_id,group_label) VALUES (2,8,'Advanced'); CREATE TABLE weights (id INT,workout_group_id INT,weight FLOAT); INSERT INTO weights (id,workout_group_id,weight) VALUES (1,8,100.5); INSERT INTO weights (id,workout_group_id,weight) VALUES (2,7,80.3);
SELECT MIN(weight) FROM weights w JOIN workout_groups g ON w.workout_group_id = g.id WHERE g.group_label = 'Advanced';
What is the total waste generated by each country in the circular economy?
CREATE TABLE CircularEconomy (country TEXT,waste INT); INSERT INTO CircularEconomy (country,waste) VALUES ('Country1',200),('Country2',300),('Country3',150),('Country4',250),('Country5',400);
SELECT country, SUM(waste) as total_waste FROM CircularEconomy GROUP BY country;
Delete all records in the "diversity_metrics" table where the region is "Europe"
CREATE TABLE diversity_metrics (id INT,company_name VARCHAR(100),region VARCHAR(50),employees_of_color INT,women_in_tech INT); INSERT INTO diversity_metrics (id,company_name,region,employees_of_color,women_in_tech) VALUES (1,'Acme Inc.','Europe',15,22),(2,'Bravo Corp.','North America',35,18);
DELETE FROM diversity_metrics WHERE region = 'Europe';
Insert new sustainable packaging options with corresponding costs.
CREATE TABLE Packaging (id INT,item VARCHAR(50),material VARCHAR(50),cost DECIMAL(5,2));
INSERT INTO Packaging (item, material, cost) VALUES ('Compostable Box', 'Plant-based', 14.99), ('Reusable Container', 'Glass', 24.99);
What is the minimum donation amount for donors from the United Kingdom?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT,DonationAmount DECIMAL); INSERT INTO Donors (DonorID,DonorName,Country,DonationAmount) VALUES (1,'Emma Thompson','United Kingdom',25.00),(2,'Daniel Craig','United Kingdom',50.00);
SELECT MIN(DonationAmount) FROM Donors WHERE Country = 'United Kingdom';
What is the total number of construction permits issued in the state of Georgia in 2018?
CREATE TABLE Construction_Permits (id INT,permit_number VARCHAR(20),issue_date DATE,state VARCHAR(20)); INSERT INTO Construction_Permits (id,permit_number,issue_date,state) VALUES (1,'CP12345','2018-01-01','Georgia');
SELECT COUNT(permit_number) FROM Construction_Permits WHERE issue_date >= '2018-01-01' AND issue_date < '2019-01-01' AND state = 'Georgia';
What is the average age of astronauts from India and China?
CREATE TABLE Astronauts (BadgeID INT PRIMARY KEY,Name VARCHAR(255),Age INT,Gender VARCHAR(10),Nationality VARCHAR(100)); INSERT INTO Astronauts (BadgeID,Name,Age,Gender,Nationality) VALUES (3,'Rakesh Sharma',52,'Male','India'); INSERT INTO Astronauts (BadgeID,Name,Age,Gender,Nationality) VALUES (4,'Yang Liwei',50,'Male','China');
SELECT AVG(Age) FROM Astronauts WHERE Nationality IN ('India', 'China');
What is the total number of technology accessibility initiatives in Asia?
CREATE TABLE tech_accessibility_initiatives (region VARCHAR(20),initiatives INT); INSERT INTO tech_accessibility_initiatives (region,initiatives) VALUES ('Asia',300),('North America',200),('Europe',250);
SELECT SUM(initiatives) as total_initiatives FROM tech_accessibility_initiatives WHERE region = 'Asia';
What are the details of organizations in Latin America focused on climate change and their partnerships with sustainable investments?
CREATE TABLE investments (id INT PRIMARY KEY,strategy VARCHAR(255),risk_level VARCHAR(50),impact_score INT,esg_rating VARCHAR(50));CREATE TABLE organizations (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),sector VARCHAR(255));CREATE TABLE partnerships (id INT PRIMARY KEY,investment_id INT,organization_id INT,start_date DATE,end_date DATE);CREATE VIEW climate_change_organizations AS SELECT * FROM organizations WHERE sector = 'Climate change';CREATE VIEW sustainable_investments AS SELECT * FROM investments WHERE esg_rating = 'High';
SELECT i.strategy, i.risk_level, i.impact_score, i.esg_rating, o.name, o.location, o.sector, p.start_date, p.end_date FROM partnerships p JOIN sustainable_investments si ON p.investment_id = si.id JOIN climate_change_organizations cco ON p.organization_id = cco.id JOIN investments i ON si.id = i.id JOIN organizations o ON cco.id = o.id WHERE o.location = 'Latin America';
What is the maximum number of community policing events in the 'rural' areas in a single month?
CREATE TABLE community_policing (id INT,area VARCHAR(10),month INT,num_events INT); INSERT INTO community_policing (id,area,month,num_events) VALUES (1,'urban',1,20),(2,'rural',1,25),(3,'urban',2,18),(4,'rural',2,30);
SELECT MAX(num_events) FROM community_policing WHERE area = 'rural' GROUP BY month;
Update the temperature record for 'Delhi' on '2022-01-01' to 70 degrees.
CREATE TABLE weather (city VARCHAR(255),temperature FLOAT,date DATE); INSERT INTO weather (city,temperature,date) VALUES ('Delhi',60,'2022-01-01');
UPDATE weather SET temperature = 70 WHERE city = 'Delhi' AND date = '2022-01-01';
What is the total number of training sessions conducted for employees with disabilities in the first half of 2022?
CREATE TABLE TrainingSessions (SessionID INT,SessionName VARCHAR(50),SessionDate DATE,NumberOfAttendees INT,AttendeeAccessibility VARCHAR(10));
SELECT COUNT(*) as TotalSessions FROM TrainingSessions WHERE SessionDate BETWEEN '2022-01-01' AND '2022-06-30' AND AttendeeAccessibility = 'Yes';
What is the maximum area of land used for urban agriculture?
CREATE TABLE MaxLand (Location VARCHAR(20),System VARCHAR(20),Area FLOAT); INSERT INTO MaxLand (Location,System,Area) VALUES ('New York','Urban Agriculture',1500),('Los Angeles','Urban Agriculture',2000),('Toronto','Urban Agriculture',2500);
SELECT MAX(Area) FROM MaxLand WHERE System = 'Urban Agriculture';
Delete customer preferences for customer 101
CREATE TABLE customer_preferences (customer_id INT,item_id INT,preference_score INT); INSERT INTO customer_preferences (customer_id,item_id,preference_score) VALUES (101,1,90),(101,2,80),(101,3,85),(102,1,75),(102,4,95);
DELETE FROM customer_preferences WHERE customer_id = 101;
What is the minimum and maximum word count of articles in the 'article_word_count' table?
CREATE TABLE article_word_count (article_id INT,word_count INT,category VARCHAR(20)); INSERT INTO article_word_count (article_id,word_count,category) VALUES (1,500,'Politics'),(2,800,'Sports'),(3,300,'Politics'),(4,1200,'Sports');
SELECT MIN(word_count) as min_word_count, MAX(word_count) as max_word_count FROM article_word_count;
What is the maximum biomass of fish in 'Aquaculture_farms'?
CREATE TABLE Aquaculture_farms (id INT,name TEXT,country TEXT,biomass FLOAT); INSERT INTO Aquaculture_farms (id,name,country,biomass) VALUES (1,'Farm A','Denmark',1500.0),(2,'Farm B','Canada',2000.0),(3,'Farm C','Japan',1000.0);
SELECT MAX(biomass) FROM Aquaculture_farms;
Show autonomous driving research papers with more than 100 citations.
CREATE TABLE ResearchPapers (Id INT,Title VARCHAR(100),Citations INT); INSERT INTO ResearchPapers (Id,Title,Citations) VALUES (1,'Autonomous Driving Algorithms',120),(2,'Deep Learning for Self-Driving Cars',80),(3,'Sensor Fusion in Autonomous Vehicles',150);
SELECT * FROM ResearchPapers WHERE Citations > 100;
How many users purchased a monthly pass in the last quarter?
CREATE TABLE user_profiles (user_id INT,user_name VARCHAR(255),pass_type VARCHAR(255),purchase_date DATE); INSERT INTO user_profiles (user_id,user_name,pass_type,purchase_date) VALUES (1,'Alice','Monthly','2022-03-01'),(2,'Bob','Weekly','2022-03-02'),(3,'Charlie','Monthly','2022-01-01');
SELECT COUNT(*) FROM user_profiles WHERE pass_type = 'Monthly' AND purchase_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH);
What is the average energy consumption per household in the Wind Turbine Projects?
CREATE TABLE Wind_Turbine_Projects (project_id INT,location VARCHAR(50),household_count INT,average_energy_consumption FLOAT); INSERT INTO Wind_Turbine_Projects (project_id,location,household_count,average_energy_consumption) VALUES (1,'Alberta',500,2500.0),(2,'Saskatchewan',300,2000.0);
SELECT AVG(average_energy_consumption) FROM Wind_Turbine_Projects;
What is the total production of 'cotton' and 'tobacco' for each region?
CREATE TABLE regions (id INT PRIMARY KEY,name TEXT); INSERT INTO regions (id,name) VALUES (1,'North'); CREATE TABLE crops (id INT PRIMARY KEY,region_id INT,crop TEXT,production INT); INSERT INTO crops (id,region_id,crop,production) VALUES (1,1,'cotton',500);
SELECT region_id, SUM(production) FROM crops WHERE crop IN ('cotton', 'tobacco') GROUP BY region_id;
How many acquisitions happened in 2021?
CREATE TABLE acquisitions (id INT,acquirer_id INT,acquiree_id INT,acquisition_year INT);
SELECT COUNT(*) FROM acquisitions WHERE acquisition_year = 2021;
Show the number of drilling rigs added or removed in the Gulf of Mexico in 2022
CREATE TABLE if not exists rig_movement (rig_id INT,rig_name TEXT,location TEXT,movement_year INT,movement_type TEXT); INSERT INTO rig_movement (rig_id,rig_name,location,movement_year,movement_type) VALUES (1,'Rig D','Gulf of Mexico',2022,'added'),(2,'Rig E','Gulf of Mexico',2021,'removed'),(3,'Rig F','North Sea',2022,'added');
SELECT location, SUM(CASE WHEN movement_type = 'added' THEN 1 WHEN movement_type = 'removed' THEN -1 ELSE 0 END) AS net_movement FROM rig_movement WHERE location = 'Gulf of Mexico' AND movement_year = 2022 GROUP BY location;
What is the total revenue generated from online ticket sales for the "Modern Art" exhibition?
CREATE TABLE tickets (ticket_id INT,exhibition_id INT,sale_date DATE,revenue DECIMAL(5,2)); INSERT INTO tickets (ticket_id,exhibition_id,sale_date,revenue) VALUES (1,2,'2022-01-02',25.00),(2,2,'2022-01-03',30.00),(3,3,'2022-01-04',20.00);
SELECT SUM(revenue) FROM tickets WHERE exhibition_id = 2 AND sale_date >= '2022-01-01';
What is the total fare collected for each route on January 1, 2022?
CREATE TABLE route (route_id INT,route_name VARCHAR(255)); INSERT INTO route (route_id,route_name) VALUES (1,'Route 1'),(2,'Route 2'); CREATE TABLE fares (fare_id INT,route_id INT,fare_amount DECIMAL,fare_date DATE); INSERT INTO fares (fare_id,route_id,fare_amount,fare_date) VALUES (1,1,2.50,'2022-01-01'),(2,1,2.50,'2022-01-01'),(3,2,3.25,'2022-01-01'),(4,2,3.25,'2022-01-01');
SELECT r.route_name, SUM(f.fare_amount) as total_fare FROM fares f JOIN route r ON f.route_id = r.route_id WHERE f.fare_date = '2022-01-01' GROUP BY r.route_name;
What is the total number of workplace safety incidents per 100 members for each union in the South region?
CREATE TABLE union_membership (member_id INT,name VARCHAR(50),union_name VARCHAR(50),membership_start_date DATE);CREATE TABLE workplace_safety (safety_id INT,union_name VARCHAR(50),incident_date DATE,incident_type VARCHAR(50),severity VARCHAR(50),union_membership_id INT);CREATE VIEW union_membership_summary AS SELECT union_name,COUNT(*) as num_members FROM union_membership GROUP BY union_name;CREATE VIEW south_unions AS SELECT union_name FROM union_membership WHERE region = 'South';
SELECT ums.union_name, (COUNT(*) * 100.0 / ums.num_members) as incidents_per_100_members FROM workplace_safety ws JOIN union_membership_summary ums ON ws.union_name = ums.union_name JOIN south_unions su ON ws.union_name = su.union_name GROUP BY ums.union_name;
What are the names of the spacecraft manufactured by SpaceCorp and their launch dates?
CREATE TABLE Spacecraft_Manufacturing (id INT,manufacturer VARCHAR(20),cost INT,launch_date DATE); INSERT INTO Spacecraft_Manufacturing (id,manufacturer,cost,launch_date) VALUES (1,'SpaceCorp',5000000,'2022-05-15');
SELECT manufacturer, launch_date FROM Spacecraft_Manufacturing WHERE manufacturer = 'SpaceCorp';
What is the minimum rating of hotels in Peru?
CREATE TABLE hotels(id INT,name TEXT,country TEXT,rating FLOAT); INSERT INTO hotels (id,name,country,rating) VALUES (1,'Hotel Cusco','Peru',4.2),(2,'Hotel Lima','Peru',4.5);
SELECT MIN(rating) FROM hotels WHERE country = 'Peru';
What is the percentage change in citizen participation over the last month?
CREATE TABLE citizen_participation (participation_date DATE,participation_value INT);
SELECT (SUM(CASE WHEN participation_date >= DATEADD(month, -1, GETDATE()) THEN participation_value ELSE 0 END) - SUM(CASE WHEN participation_date < DATEADD(month, -1, GETDATE()) THEN participation_value ELSE 0 END)) * 100.0 / SUM(participation_value) OVER () as participation_percentage_change FROM citizen_participation WHERE participation_date < GETDATE();
Delete the records of autonomous vehicles older than 5 years from the autonomous_vehicles table.
CREATE TABLE autonomous_vehicles (id INT,model VARCHAR(255),manufacture_date DATE);
DELETE FROM autonomous_vehicles WHERE manufacture_date < DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR);
What is the minimum energy storage capacity by technology in 2030?
CREATE TABLE energy_storage_2030 (technology VARCHAR(255),capacity FLOAT); INSERT INTO energy_storage_2030 (technology,capacity) VALUES ('Lithium-ion',18000.0),('Flow',25000.1),('Sodium-ion',32000.2);
SELECT technology, MIN(capacity) AS min_capacity FROM energy_storage_2030 GROUP BY technology;
What is the minimum number of launches for any SpaceX mission?
CREATE TABLE SpaceX_Missions (Id INT,Name VARCHAR(50),NumLaunches INT); INSERT INTO SpaceX_Missions (Id,Name,NumLaunches) VALUES (1,'Falcon1',5),(2,'Falcon9',10),(3,'FalconHeavy',3);
SELECT MIN(NumLaunches) FROM SpaceX_Missions;
How many cannabis plants were grown in Oregon in 2021?
CREATE TABLE plant_counts (plant_count INT,state CHAR(2),grow_year INT); INSERT INTO plant_counts (plant_count,state,grow_year) VALUES (1000,'OR',2021),(2000,'OR',2020),(3000,'CA',2021);
SELECT SUM(plant_count) FROM plant_counts WHERE state = 'OR' AND grow_year = 2021;
What is the total number of smart contracts created for each month in the '2022' year?
CREATE TABLE smart_contracts (contract_id INT,contract_name VARCHAR(50),creation_date DATE); INSERT INTO smart_contracts (contract_id,contract_name,creation_date) VALUES (1,'Contract A','2022-01-01'),(2,'Contract B','2022-02-01'),(3,'Contract C','2022-01-15'),(4,'Contract D','2022-02-15');
SELECT EXTRACT(MONTH FROM creation_date) as month, COUNT(*) as total_contracts FROM smart_contracts WHERE EXTRACT(YEAR FROM creation_date) = 2022 GROUP BY month;
What is the maximum max speed of vessels that have a type of 'Passenger'?
CREATE TABLE Vessel (vessel_id INT,name VARCHAR(255),type VARCHAR(255),max_speed DECIMAL(5,2)); INSERT INTO Vessel (vessel_id,name,type,max_speed) VALUES (1,'Test Vessel 1','Cargo',20.5),(2,'Test Vessel 2','Tanker',15.2),(3,'Test Vessel 3','Passenger',30.7),(4,'Test Vessel 4','Passenger',35.6);
SELECT MAX(v.max_speed) FROM Vessel v WHERE v.type = 'Passenger';
What is the total funding for projects in the "human rights" category in Asia?
CREATE TABLE projects (id INT,region VARCHAR(20),category VARCHAR(20),funding DECIMAL(10,2));
SELECT SUM(funding) FROM projects WHERE region = 'Asia' AND category = 'human rights';
Create a table for storing healthcare facility inspection results
CREATE TABLE inspection_results (id INT PRIMARY KEY,facility_id INT,inspection_date DATE,inspection_score INT);
INSERT INTO inspection_results (id, facility_id, inspection_date, inspection_score) VALUES (1, 1, '2022-10-15', 90), (2, 1, '2023-03-20', 95), (3, 2, '2022-11-05', 85);
Create a view named 'young_volunteers' showing volunteers under 25
CREATE TABLE volunteers(id INT PRIMARY KEY NOT NULL,name VARCHAR(50),age INT,city VARCHAR(30),country VARCHAR(30)); INSERT INTO volunteers (id,name,age,city,country) VALUES (1,'John Doe',25,'New York','USA'); INSERT INTO volunteers (id,name,age,city,country) VALUES (2,'Jane Doe',30,'Los Angeles','USA');
CREATE VIEW young_volunteers AS SELECT * FROM volunteers WHERE age < 25;
Update the region of customer with customer_id 1 to 'Europe'.
CREATE TABLE customers_5 (customer_id INT,name VARCHAR(50),region VARCHAR(20)); INSERT INTO customers_5 (customer_id,name,region) VALUES (1,'John Doe','Asia-Pacific'),(2,'Jane Smith','Europe'),(3,'Alice Johnson','Asia-Pacific'),(4,'Bob Brown','Americas');
UPDATE customers_5 SET region = 'Europe' WHERE customer_id = 1;
Which archaeologists have discovered artifacts in the same site?
CREATE TABLE ArchaeologistsBySite (SiteID INT,Archaeologist TEXT); INSERT INTO ArchaeologistsBySite (SiteID,Archaeologist) VALUES (1,'Giovanni Battista de Rossi'),(1,'Pietro Rosa'),(2,'Giovanni Carbonelli'),(3,'Zahi Hawass'),(4,'Howard Carter'),(4,'Theodore Davis');
SELECT SiteID, GROUP_CONCAT(Archaeologist) FROM ArchaeologistsBySite GROUP BY SiteID;
Create a table to store consumer demographic information
CREATE TABLE consumer_demographics (consumer_id INT PRIMARY KEY,age INT,gender TEXT,location TEXT);
CREATE TABLE consumer_demographics (consumer_id INT PRIMARY KEY, age INT, gender TEXT, location TEXT);
How many riders used each vehicle type in the last week of April 2021?
CREATE TABLE route_planning (id INT,vehicle_type VARCHAR(20),route_date DATE,num_riders INT); INSERT INTO route_planning (id,vehicle_type,route_date,num_riders) VALUES (1,'Bus','2021-04-26',150),(2,'Tram','2021-04-28',200),(3,'Train','2021-04-30',250);
SELECT vehicle_type, SUM(num_riders) as total_riders FROM route_planning WHERE route_date BETWEEN '2021-04-26' AND '2021-04-30' GROUP BY vehicle_type;
What is the number of military equipment failures in 2019 categorized by equipment type?
CREATE TABLE EquipmentFailures (EquipmentType TEXT,FailureCount INT,Year INT); INSERT INTO EquipmentFailures (EquipmentType,FailureCount,Year) VALUES ('Aircraft',150,2019),('Vehicles',120,2019),('Naval',80,2019),('Electronic',90,2019);
SELECT EquipmentType, FailureCount FROM EquipmentFailures WHERE Year = 2019;
Identify the top 3 countries in Europe with the highest percentage of sustainable products in their inventory.
CREATE TABLE products (product_id INT,name VARCHAR(255),material_id INT,is_sustainable BOOLEAN);CREATE TABLE suppliers (supplier_id INT,name VARCHAR(255),location VARCHAR(255));INSERT INTO products (product_id,name,material_id,is_sustainable) VALUES (1,'Sustainable T-Shirt',1,true),(2,'Conventional T-Shirt',2,false),(3,'Sustainable Jacket',3,true);INSERT INTO suppliers (supplier_id,name,location) VALUES (1,'European Textiles','Europe'),(2,'Global Fabrics','Global'),(3,'Eco-Friendly Fashions','Europe'),(4,'Sustainable Brands','Europe');
SELECT suppliers.location, AVG(products.is_sustainable) as avg_sustainability FROM products JOIN suppliers ON products.supplier_id = suppliers.supplier_id WHERE suppliers.location LIKE 'Europe%' GROUP BY suppliers.location ORDER BY avg_sustainability DESC LIMIT 3;
What is the average project timeline for sustainable building practices in Texas?
CREATE TABLE ProjectTimeline (TimelineID INT,Practice TEXT,State TEXT,Duration INT); INSERT INTO ProjectTimeline VALUES (1,'Green Roofs','Texas',90),(2,'Solar Panels','California',120),(3,'Insulation','Texas',60);
SELECT AVG(Duration) FROM ProjectTimeline WHERE Practice = 'Green Roofs' AND State = 'Texas';
What is the most common therapy approach for patients with PTSD?
CREATE TABLE therapy_sessions (id INT,patient_id INT,approach VARCHAR(50),session_date DATE); CREATE VIEW ptsd_therapy_sessions AS SELECT approach,COUNT(*) as count FROM therapy_sessions WHERE patient_id IN (SELECT id FROM patients WHERE condition = 'PTSD') GROUP BY approach ORDER BY count DESC LIMIT 1;
SELECT * FROM ptsd_therapy_sessions;
Update the 'rural_infrastructure' table to reflect the correct 'completion_date' for project 'Rural Electrification' in the 'Amazonas' region.
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(255),region VARCHAR(255),completion_date DATE); INSERT INTO rural_infrastructure (id,project_name,region,completion_date) VALUES (1,'Rural Electrification','Amazonas','2022-05-01');
UPDATE rural_infrastructure SET completion_date = '2022-12-31' WHERE project_name = 'Rural Electrification' AND region = 'Amazonas';
How many users are from each region?
CREATE TABLE Users (user_id INT,name TEXT,region TEXT); INSERT INTO Users (user_id,name,region) VALUES (1,'User1','North'),(2,'User2','South'),(3,'User3','North');
SELECT region, COUNT(*) as num_users FROM Users GROUP BY region;
Create a table named 'fish_species'
CREATE TABLE fish_species (id INT PRIMARY KEY,name VARCHAR(255),family VARCHAR(255));
CREATE TABLE fish_species (id INT PRIMARY KEY, name VARCHAR(255), family VARCHAR(255));
How many community development initiatives were completed in the last 2 years, categorized by project type, region, and status, with a budget over 50000?
CREATE TABLE initiative (initiative_id INT,initiative_start_date DATE,initiative_end_date DATE,budget FLOAT,region VARCHAR(50),status VARCHAR(50)); INSERT INTO initiative (initiative_id,initiative_start_date,initiative_end_date,budget,region,status) VALUES (5,'2019-01-01','2020-12-31',60000.0,'R5','completed'),(6,'2021-06-15','2022-05-30',40000.0,'R6','in progress');
SELECT EXTRACT(YEAR FROM initiative_end_date) - EXTRACT(YEAR FROM initiative_start_date) AS years_diff, region, status, project_type, COUNT(*) AS num_initiatives FROM initiative WHERE initiative_end_date >= (CURRENT_DATE - INTERVAL '2 years') AND budget > 50000 GROUP BY region, status, project_type, years_diff ORDER BY region, num_initiatives DESC;