instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
List all the unique sources of threat intelligence for the financial sector from the last year.
CREATE TABLE threat_intelligence_sources (source_id INT,source_name VARCHAR(255),sector VARCHAR(255),last_updated TIMESTAMP);
SELECT DISTINCT source_name FROM threat_intelligence_sources WHERE sector = 'Financial' AND last_updated >= NOW() - INTERVAL '1 year';
How many films featuring LGBTQ+ representation were released in the US between 2015 and 2020?
CREATE TABLE movies (title varchar(255),release_year int,LGBTQ_representation boolean); INSERT INTO movies (title,release_year,LGBTQ_representation) VALUES ('Moonlight',2016,true); INSERT INTO movies (title,release_year,LGBTQ_representation) VALUES ('Call Me By Your Name',2017,true); INSERT INTO movies (title,release_y...
SELECT COUNT(*) FROM movies WHERE LGBTQ_representation = true AND release_year BETWEEN 2015 AND 2020;
What is the maximum timeline for a construction project in Illinois?
CREATE TABLE Construction_Projects (project_id INT,project_name VARCHAR(50),state VARCHAR(2),timeline INT); INSERT INTO Construction_Projects VALUES (1,'Chicago Loop Tower','IL',48);
SELECT MAX(timeline) FROM Construction_Projects WHERE state = 'IL';
List the factories that have sustainable practices and the number of workers in those factories in the factories and workers tables.
CREATE TABLE factories (factory_id INT,has_sustainable_practices BOOLEAN,factory_name TEXT); INSERT INTO factories VALUES (1,TRUE,'Green Factory'); INSERT INTO factories VALUES (2,FALSE,'Eco-friendly Solutions'); CREATE TABLE workers (worker_id INT,factory_id INT); INSERT INTO workers VALUES (1,1); INSERT INTO workers ...
SELECT factories.factory_name, COUNT(workers.worker_id) FROM factories INNER JOIN workers ON factories.factory_id = workers.factory_id WHERE has_sustainable_practices = TRUE GROUP BY factories.factory_name;
What is the total sales revenue per sales representative, ranked by sales revenue?
CREATE TABLE DrugSales (SalesRepID int,DrugName varchar(50),SalesDate date,TotalSalesRev decimal(18,2)); INSERT INTO DrugSales (SalesRepID,DrugName,SalesDate,TotalSalesRev) VALUES (5,'DrugV','2021-03-15',65000.00),(6,'DrugW','2021-02-01',90000.00),(7,'DrugX','2021-01-25',78000.00),(8,'DrugY','2021-04-02',110000.00);
SELECT SalesRepID, SUM(TotalSalesRev) as TotalSales, ROW_NUMBER() OVER (ORDER BY SUM(TotalSalesRev) DESC) as SalesRank FROM DrugSales GROUP BY SalesRepID;
What are the top 3 energy efficient countries in Asia in 2022?
CREATE TABLE EnergyEfficiency (Country TEXT,Year INT,Score NUMBER); INSERT INTO EnergyEfficiency (Country,Year,Score) VALUES ('Japan',2022,80),('South Korea',2022,75),('China',2022,70),('India',2022,65); CREATE TABLE GHGEmissions (Country TEXT,Year INT,Emissions NUMBER); INSERT INTO GHGEmissions (Country,Year,Emissions...
SELECT EnergyEfficiency.Country, AVG(EnergyEfficiency.Score) AS Average_Score FROM EnergyEfficiency WHERE EnergyEfficiency.Country IN ('Japan', 'South Korea', 'China', 'India') AND EnergyEfficiency.Year = 2022 GROUP BY EnergyEfficiency.Country ORDER BY Average_Score DESC LIMIT 3;
Find the total budget and total number of events for each event type, from the 'Event_Data' table, grouped by Event_Type.
CREATE TABLE Event_Data (EventID INT,Event_Type VARCHAR(50),Budget DECIMAL(10,2));
SELECT Event_Type, SUM(Budget) AS Total_Budget, COUNT(*) AS Total_Events FROM Event_Data GROUP BY Event_Type;
What is the average city traffic speed of the electric vehicles that participated in safety testing?
CREATE TABLE Vehicle (id INT,name TEXT,is_electric BOOLEAN,city_traffic_speed FLOAT); CREATE TABLE SafetyTesting (id INT,vehicle_id INT); INSERT INTO Vehicle (id,name,is_electric,city_traffic_speed) VALUES (1,'Model S',true,15.3),(2,'Camry',false,18.9),(3,'Bolt',true,13.2); INSERT INTO SafetyTesting (id,vehicle_id) VAL...
SELECT AVG(city_traffic_speed) FROM Vehicle INNER JOIN SafetyTesting ON Vehicle.id = SafetyTesting.vehicle_id WHERE is_electric = true;
Find the total volume of timber harvested in 'Africa' from 'coniferous' type
CREATE TABLE forest_types (id INT,type VARCHAR(20)); INSERT INTO forest_types (id,type) VALUES (3,'coniferous');
SELECT SUM(volume) FROM timber_harvest t JOIN forest_types ft ON t.forest_type_id = ft.id WHERE t.harvest_location = 'Africa' AND ft.type = 'coniferous';
What is the total watch time for news videos in Asia with a disinformation score below 4 in the last month?
CREATE TABLE video_views (id INT,user_id INT,video_id INT,watch_time INT,video_type TEXT,view_date DATE,disinformation_score INT); INSERT INTO video_views (id,user_id,video_id,watch_time,video_type,view_date,disinformation_score) VALUES (1,1,1,60,'news','2022-03-01',3); INSERT INTO video_views (id,user_id,video_id,watc...
SELECT SUM(watch_time) FROM video_views WHERE video_type = 'news' AND view_date >= DATEADD(month, -1, GETDATE()) AND country = 'Asia' AND disinformation_score < 4;
Add new cargo record for 'copper ore' with id 100, arrived at port on Feb 10, 2022
CREATE SCHEMA if not exists ocean_shipping;CREATE TABLE if not exists ocean_shipping.cargo (id INT,cargo_type VARCHAR(255),arrived_at DATE);
INSERT INTO ocean_shipping.cargo (id, cargo_type, arrived_at) VALUES (100, 'copper ore', '2022-02-10');
Update the Sharks table to increase the population of the Great White Shark in the Pacific Ocean by 5000.
CREATE TABLE Sharks (Species VARCHAR(255),Ocean VARCHAR(255),Population INT); INSERT INTO Sharks (Species,Ocean,Population) VALUES ('Great White Shark','Pacific Ocean',32000);
UPDATE Sharks SET Population = Population + 5000 WHERE Species = 'Great White Shark' AND Ocean = 'Pacific Ocean';
What is the name and location of hospitals that have administered the COVID-19 vaccine?
CREATE TABLE vaccinations (id INT,patient_id INT,vaccine_type VARCHAR(50),date DATE,hospital_id INT); INSERT INTO vaccinations (id,patient_id,vaccine_type,date,hospital_id) VALUES (1,2,'COVID-19','2022-04-10',102),(2,3,'Flu','2022-03-15',101),(3,4,'COVID-19','2022-05-05',102); CREATE TABLE hospitals (id INT,name VARCHA...
SELECT hospitals.name, hospitals.location FROM vaccinations INNER JOIN hospitals ON vaccinations.hospital_id = hospitals.id WHERE vaccine_type = 'COVID-19';
Update the budget for the 'Sign Language Interpretation' program to $80,000 in the 'Disability Services' department.
CREATE TABLE budget (dept VARCHAR(50),program VARCHAR(50),amount INT); INSERT INTO budget (dept,program,amount) VALUES ('Disability Services','Accessible Technology',50000),('Disability Services','Sign Language Interpretation',75000),('Human Resources','Diversity Training',30000);
UPDATE budget SET amount = 80000 WHERE dept = 'Disability Services' AND program = 'Sign Language Interpretation';
What is the minimum fare for the commuter rail in Boston?
CREATE TABLE fares (fare_id INT,route_id INT,fare DECIMAL(5,2),fare_type VARCHAR(20)); INSERT INTO fares (fare_id,route_id,fare,fare_type) VALUES (1,1,8.00,'Commuter Rail'),(2,2,6.50,'Subway'),(3,3,9.00,'Commuter Rail');
SELECT MIN(fare) FROM fares WHERE fare_type = 'Commuter Rail';
What is the total number of cases for each case type ('case_types' table) in the 'case_outcomes' table?
CREATE TABLE case_outcomes (case_id INT,case_type_id INT,case_status VARCHAR(20)); CREATE TABLE case_types (case_type_id INT,case_type VARCHAR(20));
SELECT ct.case_type, COUNT(co.case_id) as num_cases FROM case_outcomes co JOIN case_types ct ON co.case_type_id = ct.case_type_id GROUP BY ct.case_type;
What is the average delivery time for satellites by SpaceTech Inc.?
CREATE TABLE Satellites (satellite_id INT,manufacturer VARCHAR(255),delivery_date DATE); INSERT INTO Satellites (satellite_id,manufacturer,delivery_date) VALUES (1,'SpaceTech Inc.','2020-01-01'),(2,'Galactic Enterprises','2019-05-15');
SELECT AVG(DATEDIFF('2022-08-01', delivery_date)) FROM Satellites WHERE manufacturer = 'SpaceTech Inc.';
What is the average energy efficiency rating of buildings in Texas that have received energy efficiency upgrades since 2010?
CREATE TABLE buildings (id INT,name VARCHAR(50),state VARCHAR(50),rating FLOAT,upgrade_year INT);
SELECT AVG(rating) FROM buildings WHERE state = 'Texas' AND upgrade_year >= 2010;
What is the maximum span length for bridges in the 'Bridge_Design' table?
CREATE TABLE Bridge_Design (project_name VARCHAR(100),span_length FLOAT); INSERT INTO Bridge_Design (project_name,span_length) VALUES ('Bicycle Bridge',50.00),('Pedestrian Bridge',30.00),('Train Bridge',100.00);
SELECT MAX(span_length) FROM Bridge_Design;
What is the total quantity of organic cotton used by textile suppliers in India and Pakistan?
CREATE TABLE TextileSuppliers (SupplierID INT,SupplierName TEXT,Country TEXT,OrganicCottonQty INT); INSERT INTO TextileSuppliers (SupplierID,SupplierName,Country,OrganicCottonQty) VALUES (1,'EcoFabrics','India',3000),(2,'GreenWeaves','Pakistan',4000),(3,'SustainableTextiles','Italy',6000);
SELECT Country, SUM(OrganicCottonQty) FROM TextileSuppliers WHERE Country IN ('India', 'Pakistan') GROUP BY Country;
What is the minimum number of peacekeeping personnel trained by the African Union in cybersecurity between 2016 and 2020, inclusive?
CREATE TABLE peacekeeping_training(id INT,personnel_id INT,trained_by VARCHAR(255),trained_in VARCHAR(255),training_year INT); INSERT INTO peacekeeping_training(id,personnel_id,trained_by,trained_in,training_year) VALUES (1,111,'AU','Cybersecurity',2016),(2,222,'EU','Mediation',2017),(3,333,'AU','Cybersecurity',2018),(...
SELECT MIN(personnel_id) FROM peacekeeping_training WHERE trained_by = 'AU' AND trained_in = 'Cybersecurity' AND training_year BETWEEN 2016 AND 2020;
Which organizations have successfully launched satellites and when were they launched?
CREATE TABLE satellites (id INT,name VARCHAR(255),launch_date DATE,organization VARCHAR(255),PRIMARY KEY(id)); INSERT INTO satellites (id,name,launch_date,organization) VALUES (1,'Satellite1','2010-05-12','Organization1'),(2,'Satellite2','2015-09-18','Organization2'),(3,'Satellite3','2020-01-03','Organization1');
SELECT satellites.organization, satellites.launch_date FROM satellites;
Delete the records where 'Polyester' is mislabeled as sustainable?
CREATE TABLE Products(id INT,name TEXT,material TEXT,is_sustainable BOOLEAN); INSERT INTO Products(id,name,material,is_sustainable) VALUES (1,'Shirt','Polyester',false),(2,'Pants','Hemp',true);
DELETE FROM Products WHERE material = 'Polyester' AND is_sustainable = true;
Add a new workout session for member with ID 3 on February 5, 2022.
CREATE TABLE Members (MemberID INT,FirstName VARCHAR(50),LastName VARCHAR(50)); INSERT INTO Members (MemberID,FirstName,LastName) VALUES (1,'John','Doe'); INSERT INTO Members (MemberID,FirstName,LastName) VALUES (2,'Jane','Doe'); CREATE TABLE Workouts (WorkoutID INT,MemberID INT,WorkoutDate DATE); INSERT INTO Workouts ...
INSERT INTO Workouts (WorkoutID, MemberID, WorkoutDate) VALUES (3, 3, '2022-02-05');
Insert records for waste_generation table, with data for 'London', 'Sydney', 'Rio de Janeiro' and generation_date values '2020-01-01', '2019-07-01', '2018-05-01' respectively
CREATE TABLE waste_generation (id INT,location VARCHAR(50),generation_date DATE,waste_amount INT);
INSERT INTO waste_generation (id, location, generation_date, waste_amount) VALUES (3, 'London', '2020-01-01', 1200), (4, 'Sydney', '2019-07-01', 1800), (5, 'Rio de Janeiro', '2018-05-01', 2500);
What is the average funding amount received by female founders in the Healthcare industry?
CREATE TABLE Founders (id INT,name TEXT,gender TEXT,industry TEXT); INSERT INTO Founders VALUES (1,'Alice','Female','Healthcare');
SELECT AVG(InvestmentRounds.funding_amount) FROM Founders JOIN InvestmentRounds ON Founders.id = InvestmentRounds.founder_id WHERE Founders.gender = 'Female' AND Founders.industry = 'Healthcare';
What's the total number of artworks in the 'Contemporary Art' exhibition?
CREATE TABLE Artworks (ArtworkID INT,ExhibitionID INT,VisitorID INT);
SELECT SUM(a.TotalArtworks) FROM (SELECT e.ExhibitionID, COUNT(a.ArtworkID) TotalArtworks FROM Artworks a JOIN Exhibitions e ON a.ExhibitionID = e.ExhibitionID WHERE e.ExhibitionName = 'Contemporary Art' GROUP BY e.ExhibitionID) a;
Find the number of spacecraft missions per week, and rank them in descending order?
CREATE TABLE spacecraft_missions (spacecraft_name TEXT,mission_date DATE);
SELECT DATE_TRUNC('week', mission_date) as mission_week, COUNT(*) as mission_count, RANK() OVER (ORDER BY COUNT(*) DESC) as mission_rank FROM spacecraft_missions GROUP BY mission_week ORDER BY mission_rank;
Delete all records for donors who identify as 'prefer not to say'.
CREATE TABLE donors (donor_id INT,donation_amount DECIMAL(10,2),donation_year INT,gender VARCHAR(255)); INSERT INTO donors (donor_id,donation_amount,donation_year,gender) VALUES (1,5000.00,2020,'female'),(2,3000.00,2019,'male'),(3,7000.00,2020,'non-binary'),(4,9000.00,2021,'non-binary'),(5,8000.00,2021,'genderqueer'),(...
DELETE FROM donors WHERE gender = 'prefer not to say';
Insert new temperature data for sensor 008 on 2023-03-03 with a value of 25°C
CREATE TABLE TemperatureData (date DATE,temperature FLOAT,sensor_id INT,FOREIGN KEY (sensor_id) REFERENCES SensorData(sensor_id));
INSERT INTO TemperatureData (date, temperature, sensor_id) VALUES ('2023-03-03', 25, 8);
What is the total number of smart contracts developed by developers from the US and China?
CREATE TABLE developers (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO developers (id,name,country) VALUES (1,'Alice','USA'),(2,'Bob','China'); CREATE TABLE smart_contracts (id INT,name VARCHAR(50),developer_id INT); INSERT INTO smart_contracts (id,name,developer_id) VALUES (1,'SC1',1),(2,'SC2',2);
SELECT COUNT(*) FROM smart_contracts sc INNER JOIN developers d ON sc.developer_id = d.id WHERE d.country IN ('USA', 'China');
What is the number of workplaces with successful collective bargaining agreements in Spain, grouped by province?
CREATE TABLE workplaces_spain (id INT,name TEXT,province TEXT,total_employees INT); INSERT INTO workplaces_spain (id,name,province,total_employees) VALUES (1,'ABC Company','Madrid',500); INSERT INTO workplaces_spain (id,name,province,total_employees) VALUES (2,'XYZ Corporation','Barcelona',300);
SELECT province, COUNT(*) as total_workplaces FROM workplaces_spain WHERE total_employees > 0 GROUP BY province;
What is the average age of female farmers in the 'agriculture_innovation' table?
CREATE TABLE agriculture_innovation (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),location VARCHAR(50)); INSERT INTO agriculture_innovation (id,name,age,gender,location) VALUES (1,'Jane',45,'Female','Rural Texas'); INSERT INTO agriculture_innovation (id,name,age,gender,location) VALUES (2,'Alice',52,'Female','Rur...
SELECT AVG(age) FROM agriculture_innovation WHERE gender = 'Female';
List the total production quantity of Ytterbium for each quarter it was produced.
CREATE TABLE Ytterbium_Production (Year INT,Quarter INT,Quantity INT); INSERT INTO Ytterbium_Production (Year,Quarter,Quantity) VALUES (2017,1,125),(2017,2,140),(2017,3,155),(2017,4,170),(2018,1,185),(2018,2,210),(2018,3,235),(2018,4,260);
SELECT Year, Quarter, SUM(Quantity) FROM Ytterbium_Production GROUP BY Year, Quarter;
Who are the top 5 cybersecurity strategists in the intelligence community?
CREATE TABLE Employee (ID INT,Name VARCHAR(50),Position VARCHAR(50),Department VARCHAR(50)); INSERT INTO Employee (ID,Name,Position,Department) VALUES (1,'Alice','Cybersecurity Strategist','Intelligence Agency A'),(2,'Bob','Cybersecurity Analyst','Intelligence Agency B'),(3,'Charlie','Cybersecurity Strategist','Intelli...
SELECT E.Name, E.Position, E.Department FROM Employee E INNER JOIN (SELECT Department, MAX(ID) AS MaxID FROM Employee WHERE Position = 'Cybersecurity Strategist' GROUP BY Department) MaxID ON E.Department = MaxID.Department AND E.ID = MaxID.MaxID;
What is the total water usage by each industrial sector in California in 2020?'
CREATE TABLE industrial_water_usage (state VARCHAR(20),year INT,sector VARCHAR(30),usage FLOAT); INSERT INTO industrial_water_usage (state,year,sector,usage) VALUES ('California',2020,'Agriculture',12345.6),('California',2020,'Manufacturing',23456.7),('California',2020,'Mining',34567.8);
SELECT sector, SUM(usage) FROM industrial_water_usage WHERE state = 'California' AND year = 2020 GROUP BY sector;
Update the name of all smart contracts created before 2019-01-01 with the word 'legacy' in it to 'LegacySC' in the smart_contracts table.
CREATE TABLE smart_contracts (id INT,name VARCHAR(100),code VARCHAR(1000),creation_date DATE); INSERT INTO smart_contracts (id,name,code,creation_date) VALUES (1,'legacySC123','0x123...','2017-01-01'); INSERT INTO smart_contracts (id,name,code,creation_date) VALUES (2,'otherSC','0x456...','2018-05-05');
UPDATE smart_contracts SET name = 'LegacySC' WHERE name LIKE '%legacy%' AND creation_date < '2019-01-01';
What is the average number of streams per user for each genre of music?
CREATE TABLE streams (stream_id INT,genre VARCHAR(255),user_id INT,streams_amount INT);
SELECT genre, AVG(streams_amount) FROM streams GROUP BY genre;
Find the average billing amount for cases in the 'Eastern' region.
CREATE TABLE cases (id INT,region VARCHAR(10),billing_amount INT); INSERT INTO cases (id,region,billing_amount) VALUES (1,'Eastern',5000),(2,'Western',7000),(3,'Eastern',6000);
SELECT AVG(billing_amount) FROM cases WHERE region = 'Eastern';
How many electric vehicles are there in the autonomous taxi fleet in Tokyo?
CREATE TABLE autonomous_taxis (taxi_id INT,taxi_type VARCHAR(50),taxi_registration_date DATE); INSERT INTO autonomous_taxis (taxi_id,taxi_type,taxi_registration_date) VALUES (1,'Tesla Model 3','2022-02-01'),(2,'Nissan Leaf','2022-02-02'),(3,'Honda Civic','2022-02-03');
SELECT COUNT(*) FROM autonomous_taxis WHERE taxi_type LIKE '%electric%';
How many fair trade suppliers are there?
CREATE TABLE suppliers (id INT PRIMARY KEY,name TEXT,location TEXT,is_fair_trade BOOLEAN);
SELECT COUNT(*) FROM suppliers WHERE is_fair_trade = TRUE;
What are the top 3 cities with the highest number of hotels that have adopted AI-powered chatbots for customer service?
CREATE TABLE hotel_data (hotel_id INT,hotel_name TEXT,city TEXT,country TEXT,stars INT,ai_chatbot BOOLEAN); INSERT INTO hotel_data (hotel_id,hotel_name,city,country,stars,ai_chatbot) VALUES (1,'Park Hotel','Zurich','Switzerland',5,true),(2,'Four Seasons','Montreal','Canada',5,false),(3,'The Plaza','New York','USA',4,tr...
SELECT city, COUNT(DISTINCT hotel_id) as hotel_count FROM hotel_data WHERE ai_chatbot = true GROUP BY city ORDER BY hotel_count DESC LIMIT 3;
What is the minimum investment in renewable energy projects in the 'renewable_energy' schema?
CREATE TABLE renewable_energy (id INT,project_name VARCHAR(50),location VARCHAR(50),investment FLOAT); INSERT INTO renewable_energy (id,project_name,location,investment) VALUES (1,'Solar Farm','Arizona',12000000),(2,'Wind Turbines','Texas',8000000);
SELECT MIN(investment) FROM renewable_energy;
How many graduate students are enrolled in Social Sciences programs per state?
CREATE TABLE students (id INT,name VARCHAR(100),field_of_study VARCHAR(50),state VARCHAR(50)); INSERT INTO students VALUES (1,'Jamie Johnson','Sociology','California');
SELECT state, COUNT(*) FROM students WHERE field_of_study IN ('Sociology', 'Political Science', 'Anthropology') GROUP BY state;
What is the total number of drugs approved in a given year, across all regions, including drugs approved for other years?
CREATE TABLE drugs_approval_all_years (drug_name TEXT,approval_year INTEGER,region TEXT); INSERT INTO drugs_approval_all_years (drug_name,approval_year,region) VALUES ('DrugX',2018,'North'),('DrugY',2019,'South'),('DrugZ',2020,'East'),('DrugA',2018,'West'),('DrugB',2020,'North'),('DrugC',2019,'North'),('DrugD',2021,'Ea...
SELECT COUNT(DISTINCT drug_name) FROM drugs_approval_all_years WHERE approval_year = 2020 UNION SELECT COUNT(DISTINCT drug_name) FROM drugs_approval_all_years WHERE approval_year != 2020;
Identify underrepresented founders who have raised funding in the e-commerce sector.
CREATE TABLE founders (id INT,name TEXT,race TEXT,industry TEXT,funds_raised FLOAT); INSERT INTO founders (id,name,race,industry,funds_raised) VALUES (1,'Alice','Asian','Technology',5000000),(2,'Bob','Black','Finance',2000000),(3,'Charlie','Latinx','Technology',3000000),(4,'Diana','White','E-commerce',1000000),(5,'Eve'...
SELECT DISTINCT name FROM founders WHERE industry = 'E-commerce' AND race NOT IN ('White');
Insert a new record in the humanitarian_assistance table for an operation named 'Medical Aid in Africa' in 2022
CREATE TABLE humanitarian_assistance (assistance_id INT,assistance_name VARCHAR(50),year INT,location VARCHAR(50),description TEXT);
INSERT INTO humanitarian_assistance (assistance_id, assistance_name, year, location, description) VALUES (1, 'Medical Aid in Africa', 2022, 'Africa', 'Description of the medical aid operation');
Show causes that received donations from both organizations and individual donors in Brazil in 2020.
CREATE TABLE Donations (id INT,donor_type TEXT,donor_name TEXT,cause_id INT,donation_amount DECIMAL(10,2),donation_date DATE); CREATE TABLE Causes (id INT,cause_name TEXT); CREATE TABLE Organizations (id INT,organization_name TEXT,country TEXT); CREATE TABLE Individual_Donors (id INT,donor_name TEXT,country TEXT);
SELECT c.cause_name FROM Donations d JOIN Causes c ON d.cause_id = c.id WHERE d.donation_date BETWEEN '2020-01-01' AND '2020-12-31' AND (d.donor_type = 'Organization' AND d.donor_name IN (SELECT organization_name FROM Organizations WHERE country = 'Brazil')) OR (d.donor_type = 'Individual' AND d.donor_name IN (SELECT d...
Delete models developed in South America.
CREATE TABLE models (id INT,name TEXT,country TEXT); INSERT INTO models (id,name,country) VALUES (1,'ModelA','US'),(2,'ModelB','Canada'),(3,'ModelC','Brazil');
DELETE FROM models WHERE country = 'Brazil';
Identify artworks by female artists that have not been exhibited since 2015.
CREATE TABLE Artists (ArtistID INT PRIMARY KEY,Name VARCHAR(100),Gender VARCHAR(10)); INSERT INTO Artists (ArtistID,Name,Gender) VALUES (1,'Clara Peeters','Female'); INSERT INTO Artists (ArtistID,Name,Gender) VALUES (2,'Francisco Goya','Male'); CREATE TABLE ArtWorks (ArtWorkID INT PRIMARY KEY,Title VARCHAR(100),YearCre...
SELECT ArtWorks.Title FROM ArtWorks INNER JOIN Artists ON ArtWorks.ArtistID = Artists.ArtistID WHERE Artists.Gender = 'Female' AND ArtWorks.LastExhibitionDate < '2016-01-01';
Create a view that shows the top 3 products with the least natural ingredients
CREATE TABLE product_ingredients (product_id INT,ingredient VARCHAR(255),percentage FLOAT,PRIMARY KEY (product_id,ingredient));
CREATE VIEW least_3_natural_ingredients AS SELECT product_id, SUM(percentage) as total_natural_ingredients FROM product_ingredients WHERE ingredient LIKE 'natural%' GROUP BY product_id ORDER BY total_natural_ingredients ASC LIMIT 3;
Show the total funding for biotech startups in the Bay Area, and the number of genetic research studies in the country with the most studies.
CREATE SCHEMA if not exists biotech_genetics; CREATE TABLE if not exists biotech_genetics.startups (id INT,name VARCHAR(100),location VARCHAR(50),funding DECIMAL(10,2)); INSERT INTO biotech_genetics.startups (id,name,location,funding) VALUES (1,'Genetech','San Francisco',2500000.00),(2,'IncellDX','New York',1500000.00)...
SELECT SUM(startups.funding) as total_funding, (SELECT COUNT(*) FROM biotech_genetics.studies WHERE country = (SELECT country FROM biotech_genetics.studies GROUP BY country ORDER BY COUNT(*) DESC LIMIT 1)) as study_count FROM biotech_genetics.startups WHERE location = 'San Francisco';
Create a view with reservoirs and their production
CREATE TABLE oil_reservoirs (reservoir_id INT,reservoir_name VARCHAR(100),location VARCHAR(100),oil_capacity FLOAT); INSERT INTO oil_reservoirs (reservoir_id,reservoir_name,location,oil_capacity) VALUES (1,'Girassol','Angola',800),(2,'Jazireh-e-Jafar','Iran',1500); CREATE TABLE production_data (reservoir_id INT,year IN...
CREATE VIEW reservoir_production AS SELECT r.reservoir_id, r.reservoir_name, SUM(p.production) FROM oil_reservoirs r JOIN production_data p ON r.reservoir_id = p.reservoir_id GROUP BY r.reservoir_id, r.reservoir_name;
What is the total number of autonomous cars in operation in San Francisco, Los Angeles, and Miami?
CREATE TABLE autonomous_cars (car_id INT,city VARCHAR(20),in_operation BOOLEAN); INSERT INTO autonomous_cars (car_id,city,in_operation) VALUES (1,'San Francisco',TRUE),(2,'San Francisco',FALSE),(3,'Los Angeles',TRUE),(4,'Los Angeles',TRUE),(5,'Miami',FALSE),(6,'Miami',TRUE);
SELECT city, COUNT(*) FROM autonomous_cars WHERE in_operation = TRUE GROUP BY city;
What is the average claim amount for policyholders living in 'CA'?
CREATE TABLE Policyholders (PolicyID INT,PolicyholderName TEXT,State TEXT); INSERT INTO Policyholders (PolicyID,PolicyholderName,State) VALUES (1,'John Smith','CA'),(2,'Jane Doe','NY'); CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimAmount INT); INSERT INTO Claims (ClaimID,PolicyID,ClaimAmount) VALUES (1,1,5000),(2...
SELECT AVG(Claims.ClaimAmount) FROM Claims INNER JOIN Policyholders ON Claims.PolicyID = Policyholders.PolicyID WHERE Policyholders.State = 'CA';
Display all trends from 'trends_by_region' table for region 'Asia'
CREATE TABLE trends_by_region (id INT PRIMARY KEY,region VARCHAR(255),trend_name VARCHAR(255),popularity_score INT);
SELECT * FROM trends_by_region WHERE region = 'Asia';
What is the total capacity of all container ships in the fleet?
CREATE TABLE fleet (id INT,name VARCHAR(50),capacity INT); INSERT INTO fleet VALUES (1,'ShipA',10000),(2,'ShipB',12000),(3,'ShipC',8000);
SELECT SUM(capacity) FROM fleet WHERE type = 'Container';
Which causes have received donations from donors in India?
CREATE TABLE donors (donor_id INT,donor_name TEXT,country TEXT); CREATE TABLE donations (donation_id INT,donor_id INT,cause_id INT,donation_amount DECIMAL); INSERT INTO donors (donor_id,donor_name,country) VALUES (1,'Aisha Patel','India'),(2,'Hiroshi Tanaka','Japan'),(3,'Clara Rodriguez','Brazil'); INSERT INTO donation...
SELECT causes.cause_name FROM causes INNER JOIN donations ON causes.cause_id = donations.cause_id INNER JOIN donors ON donations.donor_id = donors.donor_id WHERE donors.country = 'India';
What are the names of all wells in 'Venezuela'?
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),country VARCHAR(50)); INSERT INTO wells (well_id,well_name,country) VALUES (1,'WellA','Venezuela'),(2,'WellB','Venezuela'),(3,'WellC','Brazil');
SELECT well_name FROM wells WHERE country = 'Venezuela';
Show veteran employment statistics for the defense industry in the last quarter
CREATE TABLE veteran_employment (employment_id INT,industry VARCHAR(50),veteran_status VARCHAR(50),employment_date DATE);
SELECT industry, veteran_status, COUNT(*) AS num_employed FROM veteran_employment WHERE employment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND industry = 'Defense' GROUP BY industry, veteran_status;
Delete policies that have been expired for more than 2 years for policyholders in California.
CREATE TABLE policies (id INT,policyholder_id INT,policy_type TEXT,issue_date DATE,expiry_date DATE); INSERT INTO policies (id,policyholder_id,policy_type,issue_date,expiry_date) VALUES (1,3,'Life','2020-01-01','2022-01-01'),(2,4,'Health','2021-02-01','2023-02-01'),(3,5,'Auto','2021-03-01','2024-03-01'); CREATE TABLE p...
DELETE FROM policies WHERE policies.id IN (SELECT policies.id FROM policies JOIN policyholders ON policies.policyholder_id = policyholders.id WHERE policyholders.state = 'California' AND policies.expiry_date < DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR));
How many mobile customers are there in urban areas compared to rural areas?
CREATE TABLE customer_location (subscriber_id INT,area_type VARCHAR(10));
SELECT area_type, COUNT(*) FROM customer_location GROUP BY area_type;
Find the category with the minimum preference score for products that have at least 3 cruelty-free certifications.
CREATE TABLE ConsumerPreference (id INT,ConsumerID INT,ProductID INT,PreferenceScore INT); CREATE TABLE Products (id INT,ProductName VARCHAR(50),Category VARCHAR(50),Price DECIMAL(5,2),IsCrueltyFree BOOLEAN); CREATE TABLE CrueltyFreeCertification (id INT,ProductID INT,CertificationDate DATE);
SELECT P.Category, MIN(CP.PreferenceScore) as MinPreferenceScore FROM ConsumerPreference CP JOIN Products P ON CP.ProductID = P.id JOIN CrueltyFreeCertification CFC ON P.id = CFC.ProductID GROUP BY P.Category HAVING COUNT(DISTINCT CFC.CertificationDate) >= 3;
How many shared scooters are available in Berlin?
CREATE TABLE shared_vehicles (id INT,type VARCHAR(255),city VARCHAR(255),country VARCHAR(255),num_vehicles INT); INSERT INTO shared_vehicles VALUES (1,'Scooter','Berlin','Germany',2000);
SELECT num_vehicles FROM shared_vehicles WHERE type = 'Scooter' AND city = 'Berlin';
List the laborers who have worked on the most projects in the 'building_permit' and 'construction_labor' tables.
CREATE TABLE building_permit (permit_id INT,permit_date DATE,project_id INT,location VARCHAR(50)); CREATE TABLE construction_labor (laborer_id INT,laborer_name VARCHAR(50),project_id INT,material VARCHAR(50),cost DECIMAL(10,2));
SELECT laborer_name, COUNT(DISTINCT project_id) AS projects_worked FROM construction_labor JOIN building_permit ON construction_labor.project_id = building_permit.project_id GROUP BY laborer_name ORDER BY projects_worked DESC LIMIT 1;
What is the total value of military equipment sales for defense contractors located in Europe?
CREATE TABLE european_contractors (contractor_id INT,region VARCHAR(255)); INSERT INTO european_contractors (contractor_id,region) VALUES (6,'Europe'),(7,'Europe'),(8,'Europe');
SELECT SUM(s.sale_value) as total_sales FROM defense_contractors d INNER JOIN european_contractors ec ON d.contractor_id = ec.contractor_id INNER JOIN military_sales s ON d.contractor_id = s.contractor_id WHERE ec.region = 'Europe';
What is the ratio of male to female patients in rural areas of Alaska?
CREATE TABLE patients_by_gender (patient_id INT,age INT,gender VARCHAR(20),location VARCHAR(20)); INSERT INTO patients_by_gender (patient_id,age,gender,location) VALUES (1,45,'Male','Rural Alaska');
SELECT (COUNT(*) FILTER (WHERE gender = 'Male'))::float / COUNT(*) FROM patients_by_gender WHERE location = 'Rural Alaska';
How many mobile and broadband customers are there in total in the state of California?
CREATE TABLE mobile_customers (customer_id INT,state VARCHAR(20)); CREATE TABLE broadband_customers (customer_id INT,state VARCHAR(20)); INSERT INTO mobile_customers (customer_id,state) VALUES (1,'California'),(2,'New York'); INSERT INTO broadband_customers (customer_id,state) VALUES (3,'California'),(4,'Texas');
SELECT COUNT(*) FROM (SELECT customer_id FROM mobile_customers WHERE state = 'California' UNION ALL SELECT customer_id FROM broadband_customers WHERE state = 'California') AS total_customers;
What is the minimum number of days between deliveries to the same location?
CREATE TABLE delivery (delivery_id INT,delivery_date DATE,location VARCHAR(100)); INSERT INTO delivery (delivery_id,delivery_date,location) VALUES (1,'2022-01-01','Location A'),(2,'2022-01-05','Location A'),(3,'2022-01-10','Location B');
SELECT MIN(DATEDIFF(d2.delivery_date, d1.delivery_date)) FROM delivery d1 JOIN delivery d2 ON d1.location = d2.location AND d1.delivery_date < d2.delivery_date GROUP BY location;
Which investigative journalism projects received the most funding?
CREATE TABLE projects (id INT,name VARCHAR(50),category VARCHAR(20),funding DECIMAL(10,2)); CREATE VIEW investigative_projects AS SELECT * FROM projects WHERE category = 'investigative';
SELECT name, SUM(funding) FROM investigative_projects GROUP BY name ORDER BY SUM(funding) DESC;
What is the total revenue by ticket price range and sales channel?
CREATE TABLE ticket_sales (ticket_id INT,price DECIMAL(5,2),quantity INT,sales_channel VARCHAR(50)); INSERT INTO ticket_sales (ticket_id,price,quantity,sales_channel) VALUES (1,20.00,50,'Online'),(2,50.00,30,'Box Office'),(3,80.00,20,'Online');
SELECT CASE WHEN price <= 30 THEN 'Low' WHEN price <= 60 THEN 'Medium' ELSE 'High' END as price_range, sales_channel, SUM(price * quantity) as revenue FROM ticket_sales GROUP BY price_range, sales_channel;
What is the total revenue generated from mobile and broadband services in the 'South West' region?
CREATE TABLE revenue (id INT,subscriber_id INT,type VARCHAR(10),region VARCHAR(10),amount DECIMAL(10,2)); INSERT INTO revenue (id,subscriber_id,type,region,amount) VALUES (1,1,'mobile','South West',50.00),(2,2,'broadband','South West',60.00),(3,3,'mobile','North East',40.00);
SELECT SUM(revenue.amount) AS total_revenue FROM revenue WHERE revenue.region = 'South West';
Update the representative status of the Inuit to true
CREATE TABLE community(id INT,name VARCHAR(255),population INT,language VARCHAR(255),representative BOOLEAN);
UPDATE community SET representative = true WHERE name = 'Inuit';
What is the maximum budget for agricultural innovation projects in Argentina?
CREATE TABLE agri_innovation (id INT,name TEXT,location TEXT,budget FLOAT); INSERT INTO agri_innovation (id,name,location,budget) VALUES (1,'Precision Agriculture','Argentina',200000.00),(2,'Sustainable Farming','Argentina',250000.00);
SELECT MAX(budget) FROM agri_innovation WHERE location = 'Argentina';
Identify the change in monthly water consumption between 2020 and 2021 for Sydney, Australia.
CREATE TABLE australia_water_usage (id INT,city VARCHAR(50),year INT,monthly_consumption FLOAT); INSERT INTO australia_water_usage (id,city,year,monthly_consumption) VALUES (1,'Sydney',2020,140),(2,'Sydney',2021,145);
SELECT city, (LAG(monthly_consumption) OVER (PARTITION BY city ORDER BY year)) - monthly_consumption AS consumption_change FROM australia_water_usage WHERE city = 'Sydney';
What is the average lifespan of satellites in space?
CREATE TABLE satellites (satellite_id INT,launch_date DATE,decommission_date DATE); INSERT INTO satellites (satellite_id,launch_date,decommission_date) VALUES (1,'2010-01-01','2020-01-01'),(2,'2015-01-01','2022-01-01'),(3,'2020-01-01',NULL);
SELECT AVG(DATEDIFF(decommission_date, launch_date)) as avg_lifespan FROM satellites WHERE decommission_date IS NOT NULL;
Which providers in 'providers' table have not been used in any incident in the 'incidents' table?
CREATE TABLE incidents (incident_id INT,incident_date DATE,category VARCHAR(20),provider_id INT); INSERT INTO incidents (incident_id,incident_date,category,provider_id) VALUES (1,'2021-01-01','Medical',1),(2,'2021-02-15','Fire',2),(3,'2021-03-01','Traffic',3); CREATE TABLE providers (provider_id INT,name VARCHAR(50),ca...
SELECT name FROM providers WHERE provider_id NOT IN (SELECT provider_id FROM incidents);
Add a new satellite 'USA-210' launched on '2021-04-01' to the table
CREATE TABLE satellites (id INT PRIMARY KEY,name VARCHAR(50),launch_date DATE);
INSERT INTO satellites (id, name, launch_date) VALUES (6, 'USA-210', '2021-04-01');
What is the mental health score of the student with the highest ID who has not participated in open pedagogy?
CREATE TABLE students (student_id INT,mental_health_score INT,participated_in_open_pedagogy BOOLEAN); INSERT INTO students (student_id,mental_health_score,participated_in_open_pedagogy) VALUES (1,80,FALSE),(2,70,FALSE),(3,90,TRUE);
SELECT mental_health_score FROM students WHERE student_id = (SELECT MAX(student_id) FROM students WHERE participated_in_open_pedagogy = FALSE);
What percentage of total workout time is spent on strength training by members from Canada?
CREATE TABLE members (id INT,country VARCHAR(50)); INSERT INTO members (id,country) VALUES (1,'Canada'); CREATE TABLE workouts (id INT,member_id INT,activity VARCHAR(50),duration INT); INSERT INTO workouts (id,member_id,activity,duration) VALUES (1,1,'Strength Training',60);
SELECT 100.0 * SUM(CASE WHEN activity = 'Strength Training' THEN duration ELSE 0 END) / SUM(duration) AS percentage FROM members JOIN workouts ON members.id = workouts.member_id WHERE members.country = 'Canada';
What is the average heart rate of users aged 25-30 during their spin classes?
CREATE TABLE spin_classes (user_id INT,age INT,heart_rate INT);
SELECT AVG(heart_rate) FROM spin_classes WHERE age BETWEEN 25 AND 30;
List all events that have more than 50 volunteers signed up
CREATE TABLE VolunteerSignUps (SignUpID INT,VolunteerID INT,EventID INT,SignUpDate DATE);
SELECT Events.EventName FROM Events JOIN VolunteerSignUps ON Events.EventID = VolunteerSignUps.EventID GROUP BY Events.EventID HAVING COUNT(VolunteerSignUps.VolunteerID) > 50;
What is the average response time for emergency calls in each city district?
CREATE TABLE districts (did INT,name VARCHAR(255)); CREATE TABLE calls (cid INT,did INT,time DATETIME,response_time INT); INSERT INTO districts VALUES (1,'Downtown'),(2,'Uptown'); INSERT INTO calls VALUES (1,1,'2022-01-01 12:00:00',30),(2,2,'2022-01-01 13:00:00',45);
SELECT d.name, AVG(c.response_time) as avg_response_time FROM districts d JOIN calls c ON d.did = c.did GROUP BY d.did;
Which circular economy initiatives have the lowest and highest launch dates?
CREATE TABLE initiatives(initiative_id INT,name TEXT,launch_date DATE);
SELECT MIN(launch_date) as min_launch_date, MAX(launch_date) as max_launch_date FROM initiatives;
Calculate the total annual production of Terbium from the 'production' table for the years 2018 to 2020.
CREATE TABLE production (element VARCHAR(10),year INT,quantity INT); INSERT INTO production (element,year,quantity) VALUES ('Terbium',2018,1000),('Terbium',2018,1100),('Terbium',2018,1200),('Terbium',2019,1300),('Terbium',2019,1400),('Terbium',2019,1500),('Terbium',2020,1600),('Terbium',2020,1700),('Terbium',2020,1800)...
SELECT year, SUM(quantity) as total_production FROM production WHERE element = 'Terbium' AND year BETWEEN 2018 AND 2020 GROUP BY year;
Who are the top 3 employees in terms of revenue generated for each department?
CREATE TABLE employee_sales (employee TEXT,department TEXT,revenue FLOAT); INSERT INTO employee_sales (employee,department,revenue) VALUES ('John','Sales',5000.0),('Jane','Sales',6000.0),('Mike','Marketing',4000.0),('Lucy','Marketing',5000.0);
SELECT department, employee, revenue, ROW_NUMBER() OVER (PARTITION BY department ORDER BY revenue DESC) as rank FROM employee_sales WHERE rank <= 3;
Find the total energy efficiency investment in each sector in the EnergyEfficiency schema?
CREATE TABLE EnergyEfficiency (Sector VARCHAR(255),Investment DECIMAL(5,2),Year INT); INSERT INTO EnergyEfficiency (Sector,Investment,Year) VALUES ('Residential',50000,2021),('Commercial',75000,2021),('Industrial',100000,2021);
SELECT Sector, SUM(Investment) as TotalInvestment FROM EnergyEfficiency WHERE Year = 2021 GROUP BY Sector;
What are the total points scored in the last 5 NBA seasons by the team with the most points?
CREATE TABLE Seasons (SeasonID INT,TeamName VARCHAR(50),Points INT); INSERT INTO Seasons (SeasonID,TeamName,Points) VALUES (1,'Golden State Warriors',9785),(2,'Los Angeles Lakers',8874);
SELECT SUM(Points) FROM Seasons WHERE TeamName = (SELECT TeamName FROM Seasons WHERE SeasonID = (SELECT MAX(SeasonID) - 4 FROM Seasons)) AND SeasonID BETWEEN (SELECT MAX(SeasonID) - 4 FROM Seasons) AND (SELECT MAX(SeasonID) FROM Seasons)
Find the vessels with an average speed above the median average speed in the Vessel table.
CREATE TABLE Vessel (ID INT,Name TEXT,AverageSpeed DECIMAL); INSERT INTO Vessel (ID,Name,AverageSpeed) VALUES (1,'VesselA',20.5),(2,'VesselB',22.3),(3,'VesselC',18.9);
SELECT Name FROM (SELECT Name, AverageSpeed, PERCENT_RANK() OVER (ORDER BY AverageSpeed DESC) AS PercentRank FROM Vessel) AS RankedVessels WHERE PercentRank >= 0.5;
What is the average population of each species that has a population greater than 5000?
CREATE TABLE species (id INT PRIMARY KEY,name VARCHAR(255),population INT,region VARCHAR(255)); INSERT INTO species (id,name,population,region) VALUES (1,'Polar Bear',25000,'Arctic'); INSERT INTO species (id,name,population,region) VALUES (2,'Caribou',6000,'Tundra');
SELECT region, AVG(population) FROM species WHERE population > 5000 GROUP BY region;
What are the total points scored by athletes from different countries in the 2018 and 2020 Olympics?
CREATE TABLE athletes (athlete_id INT,name TEXT,country TEXT,points INT,olympics_year INT); INSERT INTO athletes (athlete_id,name,country,points,olympics_year) VALUES (1,'John Smith','USA',15,2018),(2,'Jessica Jones','GBR',10,2018),(3,'Peter Parker','USA',20,2020),(4,'Oliver Queen','CAN',18,2020);
SELECT SUM(points) FROM athletes WHERE olympics_year IN (2018, 2020) GROUP BY country;
Create a new view named 'top_players' that displays the top 5 players with the highest scores
CREATE TABLE players (id INT,name VARCHAR(100),region VARCHAR(50),score INT); INSERT INTO players (id,name,region,score) VALUES (1,'John','NA',500),(2,'Jane','EU',400),(3,'Alice','NA',600),(4,'Bob','EU',700),(5,'Charlie','ASIA',800),(6,'David','EU',900),(7,'Eve','NA',100),(8,'Frank','ASIA',150),(9,'Grace','NA',200),(10...
CREATE VIEW top_players AS SELECT * FROM (SELECT name, region, score, ROW_NUMBER() OVER (ORDER BY score DESC) as rank FROM players) as player_ranks WHERE rank <= 5;
What is the age distribution of visitors who attended the "Surrealism" exhibition?
CREATE TABLE visitors (visitor_id INT,age INT,visited_surrealism BOOLEAN); INSERT INTO visitors (visitor_id,age,visited_surrealism) VALUES (123,35,TRUE),(456,28,FALSE),(789,42,TRUE),(111,60,TRUE),(222,19,FALSE);
SELECT age_range, COUNT(*) AS visitor_count FROM (SELECT CASE WHEN age < 30 THEN '18-29' WHEN age < 50 THEN '30-49' ELSE '50+' END AS age_range, visited_surrealism FROM visitors) AS visitor_age_groups WHERE visited_surrealism = TRUE GROUP BY age_range;
What are the average safety ratings for gasoline vehicles?
CREATE TABLE Vehicles (Id INT,Type VARCHAR(20),SafetyRating FLOAT); INSERT INTO Vehicles (Id,Type,SafetyRating) VALUES (1,'Electric',4.3),(2,'Gasoline',4.0),(3,'Diesel',4.1);
SELECT AVG(SafetyRating) FROM Vehicles WHERE Type = 'Gasoline';
What was the average revenue per drug in 2021?
CREATE TABLE drugs (drug_id INT,drug_name VARCHAR(100),revenue FLOAT,year INT); INSERT INTO drugs (drug_id,drug_name,revenue,year) VALUES (1,'DrugA',1500000,2021),(2,'DrugB',2000000,2021),(3,'DrugC',1200000,2021);
SELECT AVG(revenue) FROM drugs WHERE year = 2021 AND drug_name IN (SELECT drug_name FROM drugs WHERE year = 2021);
What is the percentage change in attendance for dance events in 'CityX' compared to the previous year?
CREATE TABLE Visits (visit_id INT,visitor_id INT,event_id INT,visit_date DATE); CREATE TABLE Visitors (visitor_id INT,name VARCHAR(255),birthdate DATE); CREATE TABLE Events (event_id INT,name VARCHAR(255),date DATE,city VARCHAR(255));
SELECT 100.0 * (CURRENT_YEAR_ATTENDANCE - PREVIOUS_YEAR_ATTENDANCE) / PREVIOUS_YEAR_ATTENDANCE AS percentage_change FROM (SELECT COUNT(DISTINCT V.visitor_id) AS CURRENT_YEAR_ATTENDANCE FROM Visits V JOIN Visitors VV ON V.visitor_id = VV.visitor_id JOIN Events E ON V.event_id = E.event_id WHERE E.name LIKE '%Dance%' AND...
Determine the daily oil production for all platforms in Q3 2020
CREATE TABLE daily_oil_production (platform_id INT,production_date DATE,oil_production FLOAT); INSERT INTO daily_oil_production (platform_id,production_date,oil_production) VALUES (1,'2020-07-01',50),(1,'2020-07-02',60),(1,'2020-07-03',70),(1,'2020-08-01',80),(1,'2020-08-02',90),(1,'2020-08-03',100),(2,'2020-07-01',50)...
SELECT platform_id, production_date, oil_production FROM daily_oil_production WHERE YEAR(production_date) = 2020 AND MONTH(production_date) BETWEEN 7 AND 9;
Display the top 3 best-selling garments for each manufacturer.
CREATE TABLE Manufacturers (ManufacturerID INT,ManufacturerName VARCHAR(50));CREATE TABLE SalesData (SaleID INT,ManufacturerID INT,GarmentID INT,SalesQuantity INT);
SELECT M.ManufacturerName, G.GarmentName, SUM(SD.SalesQuantity) AS TotalSales FROM SalesData SD JOIN Manufacturers M ON SD.ManufacturerID = M.ManufacturerID JOIN Garments G ON SD.GarmentID = G.GarmentID GROUP BY M.ManufacturerName, G.GarmentName ORDER BY TotalSales DESC, M.ManufacturerName, G.GarmentName LIMIT 3;
How many sustainable building projects were completed in Florida in 2020 and 2021?
CREATE TABLE SustainableBuildingProjects (id INT,state VARCHAR(50),project_name VARCHAR(50),completed_date DATE,sustainability_rating INT); INSERT INTO SustainableBuildingProjects VALUES (1,'Florida','WindTower','2020-08-01',90); INSERT INTO SustainableBuildingProjects VALUES (2,'Florida','SolarFarm','2021-12-20',95);
SELECT COUNT(*) FROM SustainableBuildingProjects WHERE state = 'Florida' AND YEAR(completed_date) IN (2020, 2021);
What is the average score difference between the home team and the away team in the past 5 games for the 'League of Legends' tournaments?
CREATE TABLE tournaments (id INT,game VARCHAR(10),home_team VARCHAR(50),away_team VARCHAR(50),home_score INT,away_score INT,tournament_date DATE); INSERT INTO tournaments (id,game,home_team,away_team,home_score,away_score,tournament_date) VALUES (1,'League of Legends','Team Liquid','TSM',25,20,'2022-06-15');
SELECT AVG(home_score - away_score) AS avg_score_difference FROM (SELECT home_team, away_team, home_score, away_score, home_score - away_score AS score_difference, ROW_NUMBER() OVER (PARTITION BY home_team, away_team ORDER BY tournament_date DESC) rn FROM tournaments WHERE game = 'League of Legends') sub WHERE rn <= 5;