instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total carbon emissions reduction in metric tons for energy efficiency projects in the 'energy_efficiency' schema, for projects that have achieved a cost savings of at least 15%?
CREATE SCHEMA energy_efficiency; CREATE TABLE efficiency_projects (id INT,name VARCHAR(50),carbon_reduction FLOAT,cost_savings FLOAT); INSERT INTO efficiency_projects (id,name,carbon_reduction,cost_savings) VALUES (1,'Efficiency Project 1',200.5,0.16),(2,'Efficiency Project 2',150.3,0.18),(3,'Efficiency Project 3',250.0,0.12),(4,'Efficiency Project 4',100.0,0.22),(5,'Efficiency Project 5',300.0,0.15);
SELECT SUM(carbon_reduction) as total_carbon_reduction FROM energy_efficiency.efficiency_projects WHERE cost_savings >= 0.15;
Which artist has the highest average ticket price for their concerts?
CREATE TABLE Concerts (concert_id INT,artist VARCHAR(50),tier VARCHAR(50),sales INT,price DECIMAL(10,2)); INSERT INTO Concerts (concert_id,artist,tier,sales,price) VALUES (1,'Taylor Swift','Platinum',5000,150),(2,'The Rolling Stones','Gold',7000,120),(3,'Miles Davis','Silver',6000,90),(4,'Taylor Swift','Platinum',5000,160),(5,'Jay Z','Gold',7000,130);
SELECT artist, AVG(price) as avg_price FROM Concerts GROUP BY artist ORDER BY avg_price DESC LIMIT 1;
What is the average revenue for restaurants serving Chinese food?
CREATE TABLE Restaurants (id INT,name TEXT,type TEXT,revenue FLOAT); INSERT INTO Restaurants (id,name,type,revenue) VALUES (1,'Restaurant A','Italian',5000.00),(2,'Restaurant B','Chinese',6000.00),(3,'Restaurant C','Chinese',9000.00);
SELECT AVG(revenue) FROM Restaurants WHERE type = 'Chinese';
What was the maximum energy efficiency improvement (in %) for any technology in 2021?
CREATE TABLE energy_efficiency (technology VARCHAR(255),year INT,improvement FLOAT);
SELECT MAX(improvement) FROM energy_efficiency WHERE year = 2021;
Update the 'name' of organization with 'id' 2 to 'Tech for Social Good Org'
CREATE TABLE organizations (id INT,name VARCHAR(50),type VARCHAR(50),country VARCHAR(50)); INSERT INTO organizations (id,name,type,country) VALUES (1,'Accessible AI','Non-profit','USA'),(2,'Tech for Social Good','Non-governmental','India'),(3,'Digital Divide Initiative','Non-profit','Brazil');
UPDATE organizations SET name = 'Tech for Social Good Org' WHERE id = 2;
Who are the top 3 authors with the highest average word count per article in the 'investigative_reports' table?
CREATE TABLE investigative_reports (id INT,title VARCHAR(255),author VARCHAR(255),publication_date DATE,word_count INT);
SELECT author, AVG(word_count) as avg_word_count FROM investigative_reports GROUP BY author ORDER BY avg_word_count DESC LIMIT 3;
What's the total amount donated by individual donors from the USA and Canada?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT); INSERT INTO Donors (DonorID,DonorName,Country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Canada'); CREATE TABLE Donations (DonationID INT,DonorID INT,DonationAmount DECIMAL); INSERT INTO Donations (DonationID,DonorID,DonationAmount) VALUES (1,1,500),(2,1,250),(3,2,300),(4,2,150);
SELECT SUM(DonationAmount) FROM Donations D JOIN Donors DON ON D.DonorID = DON.DonorID WHERE DON.Country IN ('USA', 'Canada');
How many military personnel are stationed in each region based on the 'military_personnel' table?
CREATE TABLE military_personnel (id INT,personnel_name VARCHAR(255),region VARCHAR(255),rank VARCHAR(255),personnel_date DATE);
SELECT region, COUNT(*) as personnel_count FROM military_personnel GROUP BY region;
What is the total number of public parks in New York City and the total area they cover?
CREATE TABLE public_parks (name VARCHAR(255),city VARCHAR(255),area FLOAT); INSERT INTO public_parks (name,city,area) VALUES ('Central Park','New York',341.0),('Prospect Park','New York',526.0),('Washington Square Park','New York',9.75);
SELECT SUM(area) AS total_area, 'New York' AS city FROM public_parks WHERE city = 'New York';
List the carbon pricing for regions with the highest energy efficiency in 2021
CREATE TABLE carbon_pricing (region VARCHAR(20),price DECIMAL(5,2));CREATE TABLE energy_efficiency (region VARCHAR(20),efficiency INT);
SELECT c.region, c.price FROM carbon_pricing c JOIN (SELECT region FROM energy_efficiency WHERE efficiency = (SELECT MAX(efficiency) FROM energy_efficiency) LIMIT 1) e ON c.region = e.region;
What is the total budget of the department of education in the city of Los Angeles in 2021?
CREATE TABLE budgets (id INT,city VARCHAR,department VARCHAR,year INT,budget FLOAT); INSERT INTO budgets (id,city,department,year,budget) VALUES (1,'Los Angeles','Education',2021,1000000.00);
SELECT SUM(budget) FROM budgets WHERE city = 'Los Angeles' AND department = 'Education' AND year = 2021;
What is the total energy consumption in Brazil by sector (residential, commercial, industrial)?
CREATE TABLE energy_consumption (country VARCHAR(255),sector VARCHAR(255),consumption INT); INSERT INTO energy_consumption (country,sector,consumption) VALUES ('Brazil','Residential',5000),('Brazil','Commercial',7000),('Brazil','Industrial',10000);
SELECT SUM(consumption) FROM energy_consumption WHERE country = 'Brazil';
Delete the sport column from the players table
CREATE TABLE players (id INT PRIMARY KEY,name VARCHAR(50),age INT,sport VARCHAR(50));
ALTER TABLE players DROP COLUMN sport;
How many unique artists are there in the country genre?
CREATE TABLE artists (artist_id INT,artist_name VARCHAR(100),genre VARCHAR(50)); INSERT INTO artists (artist_id,artist_name,genre) VALUES (1,'Dolly Parton','country'),(2,'Garth Brooks','country'),(3,'Shania Twain','country'),(4,'Johnny Cash','country'),(5,'Taylor Swift','country'),(6,'Carrie Underwood','country'); CREATE TABLE songs (song_id INT,song_name VARCHAR(100),artist_id INT); INSERT INTO songs (song_id,song_name,artist_id) VALUES (1,'Jolene',1),(2,'Friends in Low Places',2),(3,'Man! I Feel Like a Woman!',3),(4,'I Walk the Line',4),(5,'Love Story',5),(6,'Before He Cheats',6),(7,'Shake it Off',5);
SELECT COUNT(DISTINCT artists.artist_name) as num_artists FROM artists JOIN songs ON artists.artist_id = songs.artist_id WHERE artists.genre = 'country';
What is the policy count for policyholders in each age group, in 5-year intervals, for policyholders in each country?
CREATE TABLE Policyholders (PolicyholderID INT,Age INT,Country VARCHAR(20)); INSERT INTO Policyholders (PolicyholderID,Age,Country) VALUES (1,25,'USA'),(2,30,'USA'),(3,45,'Canada'),(4,50,'Canada'),(5,60,'Mexico');
SELECT Country, FLOOR(Age / 5) * 5 AS AgeGroup, COUNT(*) AS PolicyCount FROM Policyholders GROUP BY Country, AgeGroup;
What is the total biomass of all whale species in the Atlantic Ocean?
CREATE TABLE MarineLife (id INT,ocean_id INT,species VARCHAR(50),biomass INT); INSERT INTO MarineLife (id,ocean_id,species,biomass) VALUES (1,1,'Blue Whale',190000),(2,1,'Fin Whale',74000),(3,2,'Sperm Whale',57000),(4,2,'Humpback Whale',36000);
SELECT SUM(MarineLife.biomass) FROM MarineLife JOIN Oceans ON MarineLife.ocean_id = Oceans.id WHERE Oceans.name = 'Atlantic' AND MarineLife.species LIKE '%Whale%';
What's the total revenue for TV shows in the 'Drama' genre?
CREATE TABLE TVShows (id INT,title VARCHAR(100),genre VARCHAR(20),viewers INT,budget FLOAT,revenue FLOAT);
SELECT SUM(revenue) FROM TVShows WHERE genre = 'Drama';
What is the failure rate of each spacecraft model?
CREATE TABLE spacecrafts (id INT,name VARCHAR(50),launches INT,failures INT); INSERT INTO spacecrafts VALUES (1,'Dragon',30,2); INSERT INTO spacecrafts VALUES (2,'Falcon',15,0);
SELECT name, (failures * 100 / launches) as failure_rate FROM spacecrafts;
List all policy types that have no claims, ordered by policy type.
CREATE TABLE PolicyTypes (PolicyTypeID INT,PolicyType TEXT); INSERT INTO PolicyTypes (PolicyTypeID,PolicyType) VALUES (1,'Home'),(2,'Auto'),(3,'Life'); CREATE TABLE Policyholders (PolicyholderID INT,PolicyholderName TEXT,PolicyTypeID INT); INSERT INTO Policyholders (PolicyholderID,PolicyholderName,PolicyTypeID) VALUES (1,'John Doe',1),(2,'Jane Smith',2),(3,'Bob Johnson',2),(4,'Alice Williams',3),(5,'Charlie Brown',3); CREATE TABLE Claims (ClaimID INT,PolicyholderID INT,ClaimDate DATE); INSERT INTO Claims (ClaimID,PolicyholderID,ClaimDate) VALUES (1,1,'2022-01-15'),(2,1,'2022-02-10'),(3,2,'2022-02-20'),(4,2,'2022-02-25');
SELECT PolicyTypes.PolicyType FROM PolicyTypes LEFT JOIN Policyholders ON PolicyTypes.PolicyTypeID = Policyholders.PolicyTypeID LEFT JOIN Claims ON Policyholders.PolicyholderID = Claims.PolicyholderID WHERE Claims.ClaimID IS NULL GROUP BY PolicyTypes.PolicyType ORDER BY PolicyTypes.PolicyType;
Identify the disaster resources with the highest and lowest quantities?
CREATE TABLE disaster_preparedness (id INT,resource VARCHAR(255),location VARCHAR(255),quantity INT,timestamp TIMESTAMP); INSERT INTO disaster_preparedness (id,resource,location,quantity,timestamp) VALUES (1,'Water','Miami',500,'2021-01-05 11:00:00'); INSERT INTO disaster_preparedness (id,resource,location,quantity,timestamp) VALUES (2,'Food','San Francisco',300,'2021-01-06 17:30:00');
SELECT resource, MIN(quantity) as lowest, MAX(quantity) as highest FROM disaster_preparedness GROUP BY resource;
How many marine research projects does the "Ocean Discoverers" organization have in total?
CREATE TABLE marine_research_projects (project_name TEXT,org_name TEXT); INSERT INTO marine_research_projects (project_name,org_name) VALUES ('Project 1','Ocean Discoverers'),('Project 2','Ocean Discoverers'),('Project 3','Ocean Explorers');
SELECT COUNT(*) FROM marine_research_projects WHERE org_name = 'Ocean Discoverers';
Show the total number of unique customers who have purchased sustainable clothing items, grouped by their preferred clothing category.
CREATE TABLE Customers (CustomerID int,CustomerName varchar(50),PreferredCategory varchar(50)); INSERT INTO Customers (CustomerID,CustomerName,PreferredCategory) VALUES (1,'SustainableSam','Women''s Dresses'); INSERT INTO Customers (CustomerID,CustomerName,PreferredCategory) VALUES (2,'EcoElla','Men''s Shirts'); CREATE TABLE Orders (OrderID int,CustomerID int,ProductID int,Sustainable boolean); INSERT INTO Orders (OrderID,CustomerID,ProductID,Sustainable) VALUES (1,1,1,true); INSERT INTO Orders (OrderID,CustomerID,ProductID,Sustainable) VALUES (2,2,2,true);
SELECT c.PreferredCategory, COUNT(DISTINCT o.CustomerID) as TotalCustomers FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID WHERE o.Sustainable = true GROUP BY c.PreferredCategory;
Find vessels that have never loaded cargo.
CREATE TABLE VesselCargo (VesselID INT,CargoID INT); INSERT INTO VesselCargo (VesselID,CargoID) VALUES (1,1),(2,2),(3,NULL),(4,4);
SELECT VesselID FROM VesselCargo WHERE CargoID IS NULL;
Insert new data into the 'OceanPollution' table
CREATE TABLE OceanPollution (PollutantID INT,Pollutant VARCHAR(255),Source VARCHAR(255),Quantity FLOAT,Location VARCHAR(255));
INSERT INTO OceanPollution (PollutantID, Pollutant, Source, Quantity, Location) VALUES (1, 'Oil', 'Offshore Drilling', 150.5, 'Gulf of Mexico');
What is the minimum policy start date by policyholder state?
CREATE TABLE policy_start_date (policy_id INT,policy_start_date DATE); CREATE TABLE policies (policy_id INT,policyholder_id INT); INSERT INTO policy_start_date VALUES (1,'2019-01-01'); INSERT INTO policies VALUES (1,1);
SELECT policyholder_state, MIN(policy_start_date) as min_policy_start_date FROM policies JOIN policy_start_date ON policies.policy_id = policy_start_date.policy_id JOIN policyholder_state ON policies.policyholder_id = policyholder_state.policyholder_id GROUP BY policyholder_state;
Add a new record to the sustainable_practices table
CREATE TABLE sustainable_practices (id INT PRIMARY KEY,hotel_name VARCHAR(255),country VARCHAR(255),practice VARCHAR(255));
INSERT INTO sustainable_practices (id, hotel_name, country, practice) VALUES (1, 'Eco-Friendly Hotel', 'Sweden', 'Recycling program');
What is the change in landfill capacity for each region between 2019 and 2020?
CREATE TABLE landfill_capacity (id INT,region VARCHAR(255),year INT,capacity INT); INSERT INTO landfill_capacity (id,region,year,capacity) VALUES (1,'Asia',2019,20000),(2,'Asia',2020,22000),(3,'Europe',2019,18000),(4,'Europe',2020,20000);
SELECT region, (capacity - LAG(capacity) OVER (PARTITION BY region ORDER BY year)) AS change FROM landfill_capacity;
What are the average ratings for cosmetic products that are both cruelty-free and vegan?
CREATE TABLE Products (Product_ID INT,Product_Name TEXT,Is_Cruelty_Free BOOLEAN,Is_Vegan BOOLEAN); INSERT INTO Products (Product_ID,Product_Name,Is_Cruelty_Free,Is_Vegan) VALUES (1,'Lush Dream Cream',true,true),(2,'Estée Lauder Double Wear Foundation',false,false),(3,'The Body Shop Vitamin E Moisture Cream',true,true); CREATE TABLE Ratings (Rating_ID INT,Product_ID INT,Rating DECIMAL(2,1)); INSERT INTO Ratings (Rating_ID,Product_ID,Rating) VALUES (1,1,4.5),(2,1,5.0),(3,2,4.0),(4,3,4.8),(5,3,4.9);
SELECT AVG(R.Rating) FROM Products P INNER JOIN Ratings R ON P.Product_ID = R.Product_ID WHERE P.Is_Cruelty_Free = true AND P.Is_Vegan = true;
What is the total investment in green building projects in Vancouver, Canada?
CREATE TABLE green_building_projects (id INT,project_name VARCHAR(50),city VARCHAR(50),country VARCHAR(50),investment FLOAT); INSERT INTO green_building_projects (id,project_name,city,country,investment) VALUES (1,'Vancouver Green Building','Vancouver','Canada',35000000);
SELECT SUM(investment) FROM green_building_projects WHERE city = 'Vancouver' AND country = 'Canada';
What is the maximum number of views for articles published in 'asia' region?
CREATE TABLE views (id INT,article_id INT,region VARCHAR(30),views INT); INSERT INTO views (id,article_id,region,views) VALUES (1,1,'asia',1000),(2,2,'europe',500),(3,3,'asia',2000);
SELECT MAX(views) FROM views WHERE region = 'asia';
Which menu items have the lowest and highest quantity sold, and what is the price of these items?
CREATE TABLE menu_items (menu_item_id INT,menu_item_name VARCHAR(50),category VARCHAR(50),price FLOAT,quantity_sold INT); INSERT INTO menu_items (menu_item_id,menu_item_name,category,price,quantity_sold) VALUES (1,'Burger','Main Course',12.99,1500);
SELECT menu_item_name, price, quantity_sold, RANK() OVER (ORDER BY quantity_sold) FROM menu_items;
How many safety incidents were reported by each facility, in total and per month?
CREATE TABLE Facility(Id INT,Name VARCHAR(50),Location VARCHAR(50)); CREATE TABLE SafetyIncident(Id INT,FacilityId INT,IncidentDate DATE);
SELECT f.Name, COUNT(si.Id) AS TotalIncidents, DATE_FORMAT(si.IncidentDate, '%Y-%m') AS Month, COUNT(si.Id) AS MonthlyIncidents FROM SafetyIncident si JOIN Facility f ON si.FacilityId = f.Id GROUP BY f.Name, Month WITH ROLLUP;
What is the average mental health score of students in 'Fall 2021'?
CREATE TABLE student_mental_health (student_id INT,mental_health_score INT,date DATE); INSERT INTO student_mental_health (student_id,mental_health_score,date) VALUES (1,80,'2021-09-01'),(2,85,'2021-09-01'),(3,70,'2021-09-02');
SELECT AVG(mental_health_score) FROM student_mental_health WHERE date = '2021-09-01';
How many individuals have accessed legal aid services in the 'legal_aid_services' table?
CREATE TABLE legal_aid_services (service_id INT,service_name VARCHAR(25),location VARCHAR(30),access_date DATE);
SELECT COUNT(*) FROM legal_aid_services;
Delete records of members who left before 2020 from Union Members table
CREATE TABLE UnionMembers (id INT,name VARCHAR(50),union_name VARCHAR(50),membership_start_date DATE,membership_end_date DATE); INSERT INTO UnionMembers (id,name,union_name,membership_start_date,membership_end_date) VALUES (1,'John Doe','Union A','2020-01-01','2022-01-01');
DELETE FROM UnionMembers WHERE membership_end_date < '2020-01-01';
What is the distribution of satellite deployments by organization and type?
CREATE TABLE SatelliteDeploymentsByType (id INT,organization VARCHAR(50),satellite_type VARCHAR(50),deployment_year INT); INSERT INTO SatelliteDeploymentsByType (id,organization,satellite_type,deployment_year) VALUES (1,'NASA','Communications',2010),(2,'NASA','Earth Observation',2015),(3,'SpaceX','Communications',2017),(4,'SpaceX','Navigation',2018),(5,'ISRO','Earth Observation',2020);
SELECT organization, satellite_type, deployment_year, COUNT(*) as total_deployments FROM SatelliteDeploymentsByType GROUP BY organization, satellite_type, deployment_year ORDER BY organization, satellite_type, deployment_year;
What is the minimum number of items delivered per day for 'daily_deliveries' table for 'Oceania' in the year 2021?
CREATE TABLE daily_deliveries (delivery_id INT,item_count INT,delivery_date DATE,location VARCHAR(50)); INSERT INTO daily_deliveries (delivery_id,item_count,delivery_date,location) VALUES (1,5,'2021-01-01','Oceania'),(2,10,'2021-01-02','Oceania');
SELECT MIN(item_count) FROM daily_deliveries WHERE EXTRACT(YEAR FROM delivery_date) = 2021 AND location = 'Oceania';
What is the total amount of investments made by different genders?
CREATE TABLE Investors (InvestorID INT,Gender VARCHAR(10),Amount INT); INSERT INTO Investors (InvestorID,Gender,Amount) VALUES (1,'Male',5000),(2,'Female',7000),(3,'Non-binary',6000);
SELECT Gender, SUM(Amount) as TotalInvestment FROM Investors GROUP BY Gender;
Determine the average time between vehicle maintenance for each route
CREATE TABLE vehicle_maintenance (maintenance_id INT,route_id INT,maintenance_date DATE);
SELECT routes.route_name, AVG(DATEDIFF(day, LAG(maintenance_date, 1) OVER (PARTITION BY route_id ORDER BY maintenance_date), maintenance_date)) AS average_days_between_maintenance FROM vehicle_maintenance JOIN routes ON vehicle_maintenance.route_id = routes.route_id GROUP BY routes.route_id, routes.route_name;
Get total funding for electric vehicle adoption statistics research in Asia
CREATE TABLE ev_research (id INT,region VARCHAR(50),funding FLOAT); INSERT INTO ev_research VALUES (1,'Asia',3000000); INSERT INTO ev_research VALUES (2,'North America',4000000);
SELECT SUM(funding) FROM ev_research WHERE region = 'Asia';
What is the minimum number of containers handled in a single day by cranes in the Port of Rotterdam in April 2021?
CREATE TABLE Port_Rotterdam_Crane_Stats (crane_name TEXT,handling_date DATE,containers_handled INTEGER); INSERT INTO Port_Rotterdam_Crane_Stats (crane_name,handling_date,containers_handled) VALUES ('CraneI','2021-04-01',70),('CraneJ','2021-04-02',60),('CraneK','2021-04-03',50),('CraneL','2021-04-04',80);
SELECT MIN(containers_handled) FROM Port_Rotterdam_Crane_Stats WHERE handling_date >= '2021-04-01' AND handling_date <= '2021-04-30';
What is the average number of investment rounds for companies founded by women in the "e-commerce" sector?
CREATE TABLE company (id INT,industry TEXT,founders TEXT); INSERT INTO company (id,industry,founders) VALUES (1,'e-commerce','female'),(2,'fintech','male,female'),(3,'e-commerce','non-binary'),(4,'healthcare','male,female,female'),(5,'e-commerce','male'),(6,'transportation','male,female,non-binary');
SELECT AVG(total_rounds) FROM (SELECT company.id, COUNT(round_data.round) AS total_rounds FROM company LEFT JOIN round_data ON company.id = round_data.company_id WHERE company.industry = 'e-commerce' AND founders LIKE '%female%' GROUP BY company.id) AS subquery;
What was the total production of 'Corn' and 'Soybeans' in each state in 'StateCropYield' table?
CREATE TABLE StateCropYield (state VARCHAR(20),crop VARCHAR(20),quantity INT,price FLOAT);
SELECT state, SUM(CASE WHEN crop = 'Corn' THEN quantity ELSE 0 END) + SUM(CASE WHEN crop = 'Soybeans' THEN quantity ELSE 0 END) as total_corn_soybeans FROM StateCropYield GROUP BY state;
What is the total number of athletes in each sport in the 'athletes' table?
CREATE TABLE athletes (id INT PRIMARY KEY,name VARCHAR(100),age INT,sport VARCHAR(50)); CREATE TABLE teams (id INT PRIMARY KEY,name VARCHAR(100),sport VARCHAR(50));
SELECT t.sport, COUNT(a.id) as total_athletes FROM athletes a JOIN teams t ON a.sport = t.sport GROUP BY t.sport;
Update the ticket price for tennis matches in the 'tennis_tickets' table in June to 75?
CREATE TABLE tennis_tickets (ticket_id INT,match_id INT,price DECIMAL(5,2),date DATE);
UPDATE tennis_tickets SET price = 75 WHERE MONTH(date) = 6;
What is the minimum funding amount for biotech startups in the Middle East?
CREATE TABLE Startups (startup_id INT,startup_name TEXT,industry TEXT,total_funding FLOAT,region TEXT); CREATE VIEW BiotechStartups AS SELECT * FROM Startups WHERE industry = 'Biotech'; CREATE VIEW MiddleEastStartups AS SELECT * FROM Startups WHERE region = 'Middle East';
SELECT MIN(total_funding) FROM BiotechStartups INNER JOIN MiddleEastStartups ON BiotechStartups.startup_id = MiddleEastStartups.startup_id;
What is the total number of employees in each department, and what percentage of them identify as LGBTQ+?
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),Position VARCHAR(50),LGBTQ INT); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Position,LGBTQ) VALUES (1,'John','Doe','IT','Developer',1),(2,'Jane','Smith','IT','Developer',0),(3,'Alice','Johnson','IT','Manager',1),(4,'Bob','Brown','HR','Manager',0);
SELECT Employees.Department, COUNT(Employees.EmployeeID) AS Total_Employees, (SUM(Employees.LGBTQ) / COUNT(Employees.EmployeeID)) * 100 AS Percentage_LGBTQ FROM Employees GROUP BY Employees.Department;
Find the average age of players who have played any game.
CREATE TABLE Game_Library (player_id INT,name VARCHAR(50),age INT,gender VARCHAR(10)); INSERT INTO Game_Library (player_id,name,age,gender) VALUES (1,'John Doe',25,'Male'),(2,'Jane Smith',30,'Female'),(3,'Alice Johnson',35,'Female'),(4,'Bob Brown',28,'Male'),(5,'Charlie Davis',22,'Male');
SELECT AVG(age) FROM Game_Library;
What is the average number of beds in hospitals and total number of beds by state?
CREATE TABLE hospitals (id INT,name TEXT,city TEXT,state TEXT,beds INT); INSERT INTO hospitals (id,name,city,state,beds) VALUES (1,'General Hospital','Miami','Florida',500); INSERT INTO hospitals (id,name,city,state,beds) VALUES (2,'Memorial Hospital','Boston','Massachusetts',600);
SELECT state, AVG(beds) as avg_beds, SUM(beds) as total_beds FROM hospitals GROUP BY state;
Which countries produced the most Tm and Dy in 2016?
CREATE TABLE country_production (country VARCHAR(50),element VARCHAR(10),year INT,quantity INT); INSERT INTO country_production (country,element,year,quantity) VALUES ('Australia','Dy',2016,750),('China','Tm',2016,500),('Mongolia','Dy',2016,600),('India','Tm',2016,650);
SELECT cp.country, cp.element, SUM(cp.quantity) as total_quantity FROM country_production cp WHERE cp.year = 2016 AND cp.element IN ('Tm', 'Dy') GROUP BY cp.country, cp.element ORDER BY total_quantity DESC;
Display the average salary for employees, by country, and sort the results by the average salary in descending order
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Country VARCHAR(50),Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,FirstName,LastName,Country,Salary) VALUES (1,'John','Doe','USA',50000.00); INSERT INTO Employees (EmployeeID,FirstName,LastName,Country,Salary) VALUES (2,'Jane','Doe','Canada',60000.00);
SELECT Country, AVG(Salary) as AverageSalary FROM Employees GROUP BY Country ORDER BY AverageSalary DESC;
How many times has supplier B had a failed inspection?
CREATE TABLE Suppliers (SupplierID varchar(10),SupplierName varchar(20)); INSERT INTO Suppliers VALUES ('B','Supplier B'); CREATE TABLE Inspections (InspectionID int,InspectionDate date,SupplierID varchar(10),Failed bit); INSERT INTO Inspections VALUES (1,'2022-01-01','B',1),(2,'2022-02-01','B',0),(3,'2022-03-01','B',1);
SELECT COUNT(*) FROM Inspections WHERE SupplierID = 'B' AND Failed = 1;
What is the total number of smart contracts and their unique hashes for the 'Ethereum' network?
CREATE TABLE ethereum_network (network_name TEXT,smart_contract_count INTEGER,smart_contract_hash TEXT);
SELECT network_name, COUNT(DISTINCT smart_contract_hash) as total_smart_contracts, COUNT(*) as total_count FROM ethereum_network GROUP BY network_name;
What is the name of the most recent military innovation in the area of cybersecurity?
CREATE TABLE military_innovation (innovation_id INT,innovation_name VARCHAR(255),category VARCHAR(255),date DATE); INSERT INTO military_innovation (innovation_id,innovation_name,category,date) VALUES (1,'Innovation A','Unmanned Aerial Vehicles','2018-01-01'),(2,'Innovation B','Cybersecurity','2019-01-01'),(3,'Innovation C','Unmanned Aerial Vehicles','2020-01-01'); CREATE TABLE categories (category VARCHAR(255));
SELECT innovation_name FROM military_innovation INNER JOIN categories ON military_innovation.category = categories.category WHERE category = 'Cybersecurity' AND date = (SELECT MAX(date) FROM military_innovation);
What is the most popular menu item for each cuisine type?
CREATE TABLE menu(id INT,item VARCHAR(255),cuisine VARCHAR(255),popularity INT); INSERT INTO menu(id,item,cuisine,popularity) VALUES (1,'Pizza','Italian',50),(2,'Spaghetti','Italian',30),(3,'Tacos','Mexican',70),(4,'Burritos','Mexican',40);
SELECT cuisine, item, popularity FROM (SELECT cuisine, item, popularity, RANK() OVER (PARTITION BY cuisine ORDER BY popularity DESC) as rank FROM menu) subquery WHERE rank = 1;
What is the maximum cultural competency score by race?
CREATE TABLE if not exists cultural_competency_scores (score INT,race VARCHAR(255)); INSERT INTO cultural_competency_scores (score,race) VALUES (90,'Hispanic'),(85,'African American'),(95,'Asian');
SELECT MAX(score), race FROM cultural_competency_scores GROUP BY race;
List all routes with their corresponding stops
CREATE TABLE routes (route_id INT,name VARCHAR(255),type VARCHAR(255)); CREATE TABLE stations (station_id INT,name VARCHAR(255),latitude DECIMAL(9,6),longitude DECIMAL(9,6)); CREATE TABLE route_stops (route_id INT,station_id INT);
SELECT r.name AS route_name, s.name AS station_name FROM routes r JOIN route_stops rs ON r.route_id = rs.route_id JOIN stations s ON rs.station_id = s.station_id;
How many streams did each artist have in the last month, for artists who performed at music festivals in the last year?
CREATE TABLE artist_streams (artist_id INT,streams INT,stream_date DATE); CREATE TABLE festival_performances (artist_id INT,festival_id INT,performance_date DATE);
SELECT a.artist_id, SUM(s.streams) as total_streams FROM artist_streams s JOIN festival_performances f ON s.artist_id = f.artist_id WHERE s.stream_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND f.performance_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY a.artist_id;
How many seals are there in the 'seals' table?
CREATE TABLE seals (id INT,name VARCHAR(255),location VARCHAR(255));
SELECT COUNT(*) FROM seals;
What is the number of startups founded by women in the technology sector with no funding records?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founding_year INT,founder_gender TEXT); INSERT INTO companies (id,name,industry,founding_year,founder_gender) VALUES (1,'TechFem','Technology',2015,'Female'); INSERT INTO companies (id,name,industry,founding_year,founder_gender) VALUES (2,'GreenInno','GreenTech',2018,'Male');
SELECT COUNT(*) FROM companies WHERE founder_gender = 'Female' AND industry = 'Technology' AND id NOT IN (SELECT company_id FROM funding_records);
What is the total revenue generated per region?
CREATE TABLE sales (sale_id INT,product VARCHAR(20),region VARCHAR(20),revenue DECIMAL(10,2)); INSERT INTO sales (sale_id,product,region,revenue) VALUES (1,'Software','North',5000.00),(2,'Hardware','South',3000.00),(3,'Consulting','East',7000.00);
SELECT region, SUM(revenue) as total_revenue FROM sales GROUP BY region;
What was the total number of art workshops attended by adults aged 25-34 in New York?
CREATE TABLE art_workshops (id INT,age INT,city VARCHAR(50)); INSERT INTO art_workshops (id,age,city) VALUES (1,27,'New York'),(2,32,'Los Angeles');
SELECT SUM(1) FROM art_workshops WHERE age BETWEEN 25 AND 34 AND city = 'New York';
Delete records in the restaurant_revenue table with a total_revenue less than 2500
CREATE TABLE restaurant_revenue (restaurant_id INT,revenue_date DATE,total_revenue DECIMAL(10,2));
DELETE FROM restaurant_revenue WHERE total_revenue < 2500;
List the top 3 countries with the highest local economic impact from tourism?
CREATE TABLE economic_impact (id INT,country VARCHAR(50),impact FLOAT); INSERT INTO economic_impact (id,country,impact) VALUES (1,'India',5000),(2,'Japan',6000),(3,'Italy',7000);
SELECT country, impact FROM economic_impact WHERE row_number() OVER (ORDER BY impact DESC) <= 3;
List habitats, the number of species in each, and the number of animals they protect
CREATE TABLE habitats (id INT,name VARCHAR(255));CREATE TABLE animals (id INT,species_id INT,habitat_id INT);CREATE TABLE species (id INT,name VARCHAR(255));CREATE TABLE community_outreach (id INT,habitat_id INT,animal_id INT); INSERT INTO habitats (id,name) VALUES (1,'Forest'),(2,'Savannah'); INSERT INTO animals (id,species_id,habitat_id) VALUES (1,1,2),(2,2,1),(3,3,2),(4,1,2),(5,4,1); INSERT INTO species (id,name) VALUES (1,'Lion'),(2,'Elephant'),(3,'Giraffe'),(4,'Zebra'); INSERT INTO community_outreach (id,habitat_id,animal_id) VALUES (1,1,2),(2,1,3),(3,2,1),(4,2,4),(5,2,5);
SELECT h.name AS habitat_name, COUNT(DISTINCT s.id) AS species_count, COUNT(co.animal_id) AS animals_protected FROM community_outreach co INNER JOIN animals a ON co.animal_id = a.id INNER JOIN species s ON a.species_id = s.id INNER JOIN habitats h ON a.habitat_id = h.id GROUP BY h.name;
What is the average amount of donations made by individuals from the United States?
CREATE TABLE donors (id INT,name VARCHAR(255),country VARCHAR(255),donation DECIMAL(10,2));
SELECT AVG(donation) FROM donors WHERE country = 'United States';
How many home games did the 'los_angeles_dodgers' play in the 'games' table?
CREATE TABLE games (team VARCHAR(50),location VARCHAR(50),date DATE); INSERT INTO games (team,location,date) VALUES ('Los Angeles Dodgers','Home','2022-06-01'),('Los Angeles Dodgers','Away','2022-06-03'),('New York Yankees','Home','2022-06-02'),('Los Angeles Dodgers','Home','2022-06-04');
SELECT COUNT(*) FROM games WHERE team = 'Los Angeles Dodgers' AND location = 'Home';
Update the 'oil_production' table to set the yearly_production to 1000000 for all records where the company_name = 'Green Oil Inc.'
CREATE TABLE oil_production (production_id INT PRIMARY KEY,company_name VARCHAR(255),year INT,yearly_production BIGINT);
UPDATE oil_production SET yearly_production = 1000000 WHERE company_name = 'Green Oil Inc.';
Show the total number of wins for each team in the 2023 NBA season.
CREATE TABLE nba_teams (id INT,team VARCHAR(50),wins INT,losses INT,season VARCHAR(10)); INSERT INTO nba_teams (id,team,wins,losses,season) VALUES (1,'Boston Celtics',60,20,'2023'),(2,'LA Lakers',45,35,'2023');
SELECT team, SUM(wins) FROM nba_teams WHERE season = '2023';
What is the total biomass of all marine life in the Atlantic Ocean?
CREATE TABLE marine_life_biomass (id INT,location TEXT,biomass FLOAT); INSERT INTO marine_life_biomass (id,location,biomass) VALUES (1,'Atlantic Ocean',1500000.0),(2,'Pacific Ocean',1200000.0);
SELECT SUM(biomass) FROM marine_life_biomass WHERE location = 'Atlantic Ocean';
What is the average organic waste generation per capita in Spain?
CREATE TABLE OrganicWasteData (country VARCHAR(50),population INT,organic_waste_kg FLOAT); INSERT INTO OrganicWasteData (country,population,organic_waste_kg) VALUES ('Spain',47351247,3.8);
SELECT AVG(organic_waste_kg/population) FROM OrganicWasteData WHERE country = 'Spain';
List all startups that have not exited
CREATE TABLE startups (id INT,name TEXT,exit_date DATE); CREATE TABLE exits (id INT,startup_id INT,exit_date DATE);
SELECT startups.name FROM startups LEFT JOIN exits ON startups.id = exits.startup_id WHERE exits.exit_date IS NULL;
What is the average media literacy score for content creators in the United States?
CREATE TABLE content_creators (id INT,name TEXT,country TEXT,media_literacy_score INT); INSERT INTO content_creators (id,name,country,media_literacy_score) VALUES (1,'Alice','USA',80),(2,'Bob','USA',85);
SELECT AVG(media_literacy_score) FROM content_creators WHERE country = 'USA';
What is the number of days with extreme weather events in each region over the last 5 years?
CREATE TABLE extreme_weather_data (region VARCHAR(255),year INT,days_with_extreme_weather INT);
SELECT region, SUM(days_with_extreme_weather) OVER (PARTITION BY region) FROM extreme_weather_data WHERE year BETWEEN 2018 AND 2022;
Identify the top 3 countries with the highest total donation amounts in the 'InternationalDonations' table.
CREATE TABLE InternationalDonations (DonationID INT,DonorID INT,Country VARCHAR(50),DonationAmount DECIMAL(10,2),DonationDate DATE);
SELECT Country, SUM(DonationAmount) AS TotalDonations FROM InternationalDonations GROUP BY Country ORDER BY TotalDonations DESC LIMIT 3;
Which district had the highest recycling rate in 2019?
CREATE TABLE districts (district_id INT,district_name TEXT,recycling_rate DECIMAL(5,4)); INSERT INTO districts (district_id,district_name,recycling_rate) VALUES (1,'District A',0.35),(2,'District B',0.45),(3,'District C',0.55);
SELECT district_name, MAX(recycling_rate) FROM districts WHERE YEAR(districts.date) = 2019 GROUP BY district_name;
What is the total number of steps taken by users in a day?
CREATE TABLE steps (user_id INT,steps INT,step_date DATE); INSERT INTO steps (user_id,steps,step_date) VALUES (1,5000,'2022-01-01'),(2,7000,'2022-01-01'),(3,8000,'2022-01-02'),(4,9000,'2022-01-02');
SELECT SUM(steps) FROM steps GROUP BY step_date;
What is the maximum song_length in the metal genre?
CREATE TABLE genres (genre VARCHAR(10),song_id INT,song_length FLOAT); INSERT INTO genres (genre,song_id,song_length) VALUES ('metal',22,175.2),('metal',23,160.8),('metal',24,205.9);
SELECT MAX(song_length) FROM genres WHERE genre = 'metal';
What is the most popular genre among users in 'Canada'?
CREATE TABLE users (id INT,name VARCHAR(50),country VARCHAR(50),favorite_genre VARCHAR(50)); INSERT INTO users (id,name,country,favorite_genre) VALUES (1,'Alice','USA','Pop'),(2,'Bob','Canada','Rock'),(3,'Charlie','Canada','Rock'),(4,'David','USA','Jazz'),(5,'Eve','USA','Pop'),(6,'Frank','Canada','Country'),(7,'Grace','Canada','Country'),(8,'Harry','USA','R&B'),(9,'Ivy','USA','Pop'),(10,'Jack','USA','Jazz');
SELECT favorite_genre, COUNT(*) as genre_count FROM users WHERE country = 'Canada' GROUP BY favorite_genre ORDER BY genre_count DESC LIMIT 1;
What is the total production of 'Broccoli' by all farmers in 'California'?
CREATE TABLE Farmers (FarmerID int,FarmerName text,Location text); INSERT INTO Farmers (FarmerID,FarmerName,Location) VALUES (1,'John Doe','California'); CREATE TABLE Production (Product text,FarmerID int,Quantity int); INSERT INTO Production (Product,FarmerID,Quantity) VALUES ('Broccoli',1,500);
SELECT SUM(Quantity) FROM Production JOIN Farmers ON Production.FarmerID = Farmers.FarmerID WHERE Product = 'Broccoli' AND Location = 'California';
Delete all records from the 'Bikes' table where 'bike_type' is 'Hybrid Bike'
CREATE TABLE Bikes (bike_id INT,bike_type VARCHAR(20)); INSERT INTO Bikes (bike_id,bike_type) VALUES (1,'Mountain Bike'),(2,'Road Bike'),(3,'Hybrid Bike');
DELETE FROM Bikes WHERE bike_type = 'Hybrid Bike';
What is the total number of whales spotted in all oceans in 2021?
CREATE TABLE whale_sightings_2021 (ocean VARCHAR(255),num_whales INT); INSERT INTO whale_sightings_2021 (ocean,num_whales) VALUES ('Atlantic',150),('Pacific',210),('Indian',180),('Arctic',120);
SELECT SUM(num_whales) FROM whale_sightings_2021;
What are the top 5 most vulnerable devices in the 'NetworkDevices' table, based on the number of vulnerabilities?
CREATE TABLE NetworkDevices (id INT,device_name VARCHAR(50),severity VARCHAR(10),discovered_date DATE); INSERT INTO NetworkDevices (id,device_name,severity,discovered_date) VALUES (1,'Router1','High','2021-08-01'),(2,'Switch1','Medium','2021-07-15'),(3,'Firewall1','Low','2021-06-01'),(4,'Router2','High','2021-09-01'),(5,'Switch2','Low','2021-07-15');
SELECT device_name, COUNT(*) as number_of_vulnerabilities FROM NetworkDevices GROUP BY device_name ORDER BY number_of_vulnerabilities DESC LIMIT 5;
What is the total fare collected for each route segment in the past month?
CREATE TABLE ROUTE_SEGMENTS (route_id TEXT,segment_start TEXT,segment_end TEXT,fare REAL,collection_date DATE); INSERT INTO ROUTE_SEGMENTS (route_id,segment_start,segment_end,fare,collection_date) VALUES ('1','Start1','End1',2.5,'2022-03-01'),('2','Start2','End2',3.0,'2022-03-02'),('1','Start3','End3',2.3,'2022-03-03');
SELECT route_id, SUM(fare) FROM ROUTE_SEGMENTS WHERE collection_date >= (CURRENT_DATE - INTERVAL '30 days') GROUP BY route_id;
What is the average water temperature in January for all Salmon farms?
CREATE TABLE Salmon_farms (id INT,name TEXT,country TEXT,water_temp FLOAT); INSERT INTO Salmon_farms (id,name,country,water_temp) VALUES (1,'Farm A','Norway',8.5),(2,'Farm B','Canada',2.0);
SELECT AVG(water_temp) FROM Salmon_farms WHERE MONTH(created_at) = 1 AND species = 'Salmon';
What is the total donation amount by city for cities that start with 'S'?
CREATE TABLE donations (donation_id INT,donor_city VARCHAR(50),donation_amount DECIMAL(10,2)); INSERT INTO donations VALUES (1,'NYC',100.00),(2,'LA',200.00),(3,'SF',150.00),(4,'Seattle',250.00);
SELECT SUM(donation_amount) FROM donations WHERE donor_city LIKE 'S%';
What is the total budget for services in a department with a name starting with 'D'?
CREATE TABLE Service (id INT,department_id INT,name VARCHAR(50),cost DECIMAL(10,2)); INSERT INTO Service (id,department_id,name,cost) VALUES (1,1,'Service1',10000.00); INSERT INTO Service (id,department_id,name,cost) VALUES (2,1,'Service2',15000.00); INSERT INTO Service (id,department_id,name,cost) VALUES (3,2,'Service3',20000.00); CREATE TABLE Department (id INT,city_id INT,name VARCHAR(50),budget DECIMAL(10,2)); INSERT INTO Department (id,city_id,name,budget) VALUES (1,1,'DeptX',500000.00); INSERT INTO Department (id,city_id,name,budget) VALUES (2,1,'DeptY',750000.00); INSERT INTO Department (id,city_id,name,budget) VALUES (3,2,'DeptZ',1000000.00);
SELECT SUM(Service.cost) FROM Service INNER JOIN Department ON Service.department_id = Department.id WHERE Department.name LIKE 'D%';
What is the number of IoT devices in farm C?
CREATE TABLE Farm (id INT,name VARCHAR(50)); CREATE TABLE IotDevice (id INT,name VARCHAR(50),farm_id INT); INSERT INTO Farm (id,name) VALUES (1,'Farm A'),(2,'Farm B'),(3,'Farm C'); INSERT INTO IotDevice (id,name,farm_id) VALUES (1,'Device 1',3),(2,'Device 2',3);
SELECT COUNT(*) FROM IotDevice WHERE farm_id = (SELECT id FROM Farm WHERE name = 'Farm C');
Update all records related to Gadolinium production in the production_data_2 table to 1000 metric tons?
CREATE TABLE production_data_2 (year INT,company_name TEXT,element TEXT,quantity INT); INSERT INTO production_data_2 (year,company_name,element,quantity) VALUES (2018,'RST Mining','Gadolinium',1200),(2019,'STW Mining','Gadolinium',1500),(2020,'TUV Mining','Gadolinium',1800);
UPDATE production_data_2 SET quantity = 1000 WHERE element = 'Gadolinium';
Calculate the average inspection frequency for all bridges in the Bridge_Inspections table
CREATE TABLE Bridge_Inspections (inspection_id INT,bridge_name VARCHAR(50),bridge_type VARCHAR(50),inspection_date DATE);
SELECT AVG(DATEDIFF(inspection_date, LAG(inspection_date) OVER (PARTITION BY bridge_name ORDER BY inspection_date))) FROM Bridge_Inspections WHERE bridge_type = 'Bridge';
Which farmers have the highest revenue from urban agriculture?
CREATE TABLE farmers (id INT,name VARCHAR(255),system_type VARCHAR(255)); INSERT INTO farmers (id,name,system_type) VALUES (1,'Jane Doe','Urban Agriculture'); INSERT INTO farmers (id,name,system_type) VALUES (2,'John Smith','Agroecology'); INSERT INTO farmers (id,name,system_type) VALUES (3,'Maria Garcia','Indigenous Food Systems'); INSERT INTO farmers (id,name,system_type) VALUES (4,'Ali Ahmed','Urban Agriculture'); CREATE TABLE farmer_revenue (farmer_id INT,revenue FLOAT); INSERT INTO farmer_revenue (farmer_id,revenue) VALUES (1,12000.00); INSERT INTO farmer_revenue (farmer_id,revenue) VALUES (2,9000.00); INSERT INTO farmer_revenue (farmer_id,revenue) VALUES (3,8500.00); INSERT INTO farmer_revenue (farmer_id,revenue) VALUES (4,15000.00);
SELECT farmers.name, MAX(farmer_revenue.revenue) as highest_revenue FROM farmers JOIN farmer_revenue ON farmers.id = farmer_revenue.farmer_id WHERE farmers.system_type = 'Urban Agriculture' GROUP BY farmers.name;
What is the minimum mental health score of students in 'Winter 2022' by school district?
CREATE TABLE student_mental_health (student_id INT,mental_health_score INT,school_district VARCHAR(255),date DATE); INSERT INTO student_mental_health (student_id,mental_health_score,school_district,date) VALUES (1,75,'ABC School District','2022-02-01'); CREATE VIEW winter_2022_smh AS SELECT * FROM student_mental_health WHERE date BETWEEN '2022-01-01' AND '2022-03-31';
SELECT MIN(mental_health_score) as min_mental_health, school_district FROM winter_2022_smh GROUP BY school_district;
Delete the record of the disability policy advocacy event that took place on 2021-07-01.
CREATE TABLE AdvocacyEvents (EventID INT,EventName VARCHAR(50),EventDate DATETIME); INSERT INTO AdvocacyEvents (EventID,EventName,EventDate) VALUES (1,'Event A','2021-01-01'),(2,'Event B','2021-02-01'),(3,'Event C','2021-07-01'),(4,'Event D','2021-08-01');
DELETE FROM AdvocacyEvents WHERE EventDate = '2021-07-01';
Identify traditional music events in Mexico with more than 3 performers and an average attendance greater than 50 in the last 3 years.
CREATE TABLE MusicEvents (id INT,name VARCHAR(255),country VARCHAR(255),UNIQUE (id)); CREATE TABLE Performers (id INT,name VARCHAR(255),music_event_id INT,UNIQUE (id),FOREIGN KEY (music_event_id) REFERENCES MusicEvents(id)); CREATE TABLE Attendance (id INT,music_event_id INT,year INT,attendees INT,UNIQUE (id),FOREIGN KEY (music_event_id) REFERENCES MusicEvents(id));
SELECT me.name FROM MusicEvents me JOIN Performers p ON me.id = p.music_event_id JOIN Attendance a ON me.id = a.music_event_id WHERE me.country = 'Mexico' GROUP BY me.name HAVING COUNT(DISTINCT p.id) > 3 AND AVG(a.attendees) > 50 AND a.year BETWEEN 2020 AND 2022;
What is the average daily data usage by mobile subscribers for each technology in the Southern region?
CREATE TABLE mobile_subscribers (subscriber_id INT,technology VARCHAR(20),region VARCHAR(50),daily_data_usage INT); INSERT INTO mobile_subscribers (subscriber_id,technology,region,daily_data_usage) VALUES (1,'4G','North',1000),(2,'5G','North',2000),(3,'3G','South',1500),(4,'5G','East',2500),(5,'5G','North',3000),(6,'3G','South',1800),(7,'4G','West',2200);
SELECT technology, region, AVG(daily_data_usage) AS avg_daily_data_usage FROM mobile_subscribers WHERE region = 'South' GROUP BY technology, region;
What is the total sales amount for a specific drug in a given region for the year 2020?
CREATE TABLE sales (sale_id INT,drug_name TEXT,sale_region TEXT,sale_amount INT,sale_date DATE); INSERT INTO sales (sale_id,drug_name,sale_region,sale_amount,sale_date) VALUES (1,'DrugA','Europe',1500000,'2020-01-01'),(2,'DrugA','US',2000000,'2020-12-31'),(3,'DrugB','Europe',1200000,'2020-07-04');
SELECT SUM(sale_amount) FROM sales WHERE drug_name = 'DrugA' AND sale_region = 'Europe' AND sale_date >= '2020-01-01' AND sale_date <= '2020-12-31';
What is the minimum temperature recorded by IoT sensors in Australia in the last week?
CREATE TABLE if NOT EXISTS iot_sensors_2 (id int,location varchar(50),temperature float,timestamp datetime); INSERT INTO iot_sensors_2 (id,location,temperature,timestamp) VALUES (1,'Australia',18.2,'2022-03-15 10:00:00');
SELECT MIN(temperature) FROM iot_sensors_2 WHERE location = 'Australia' AND timestamp >= DATE_SUB(NOW(), INTERVAL 1 WEEK);
Get the top three regions with the highest chemical waste production in 2021 and the total waste produced.
CREATE TABLE region_waste (region VARCHAR(50),year INT,waste_amount FLOAT); INSERT INTO region_waste (region,year,waste_amount) VALUES ('Asia',2021,500.5),('Europe',2021,450.2),('Africa',2021,300.1),('Australia',2021,250.6),('North America',2021,200.9),('Asia',2021,550.7),('Europe',2021,475.3),('Africa',2021,320.5),('Australia',2021,260.8),('North America',2021,220.4);
SELECT region, SUM(waste_amount) as total_waste FROM region_waste WHERE year = 2021 GROUP BY region ORDER BY total_waste DESC LIMIT 3;
What are the names of the movies and their genres for movies produced in Germany?
CREATE TABLE movie (id INT,title VARCHAR(255),genre VARCHAR(255),country VARCHAR(255)); INSERT INTO movie (id,title,genre,country) VALUES (1,'Movie1','Comedy','Spain'),(2,'Movie2','Drama','France'),(3,'Movie3','Action','Germany'),(4,'Movie4','Adventure','Germany');
SELECT title, genre FROM movie WHERE country = 'Germany';
List all unique conservation statuses in the 'animal_info' table
CREATE TABLE animal_info (animal_id INT,conservation_status VARCHAR(20)); INSERT INTO animal_info (animal_id,conservation_status) VALUES (1,'endangered'),(2,'vulnerable'),(3,'threatened'),(4,'endangered'),(5,'vulnerable');
SELECT DISTINCT conservation_status FROM animal_info;