instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the percentage of female healthcare providers in rural India?
CREATE TABLE healthcare_providers (id INT,name VARCHAR(50),gender VARCHAR(10),location VARCHAR(50)); INSERT INTO healthcare_providers (id,name,gender,location) VALUES (1,'Dr. Smith','Female','Rural India'); INSERT INTO healthcare_providers (id,name,gender,location) VALUES (2,'Dr. Johnson','Male','Urban New York');
SELECT ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM healthcare_providers WHERE location = 'Rural India'), 2) FROM healthcare_providers WHERE location = 'Rural India' AND gender = 'Female';
Which states have the highest and lowest vaccination rates for measles?
CREATE TABLE vaccinations (id INT,state VARCHAR(2),vaccine VARCHAR(50),rate DECIMAL(5,2)); INSERT INTO vaccinations (id,state,vaccine,rate) VALUES (1,'NY','Measles',0.95),(2,'CA','Measles',0.96),(3,'TX','Measles',0.92),(4,'FL','Measles',0.94),(5,'AK',0.98),(6,'MS',0.91);
SELECT state, rate FROM vaccinations WHERE vaccine = 'Measles' ORDER BY rate DESC, state ASC LIMIT 1; SELECT state, rate FROM vaccinations WHERE vaccine = 'Measles' ORDER BY rate ASC, state ASC LIMIT 1;
Update the price of jazz songs released before 2000 to $1.99
CREATE TABLE Songs (song_id INT,title TEXT,genre TEXT,release_date DATE,price DECIMAL(5,2));
UPDATE Songs SET price = 1.99 WHERE genre = 'jazz' AND release_date < '2000-01-01';
What is the percentage of cruelty-free beauty products in the overall beauty product sales in Italy?
CREATE TABLE beauty_products_italy (product_cruelty_free BOOLEAN,sales_quantity INT); INSERT INTO beauty_products_italy (product_cruelty_free,sales_quantity) VALUES (TRUE,800),(FALSE,1200);
SELECT (SUM(CASE WHEN product_cruelty_free = TRUE THEN sales_quantity ELSE 0 END) / SUM(sales_quantity)) * 100 AS cruelty_free_percentage FROM beauty_products_italy;
Find the top 2 countries with the most program impact in 2022?
CREATE TABLE program_impact (program_id INT,country VARCHAR(50),impact INT); INSERT INTO program_impact VALUES (1,'India',100),(2,'Brazil',150),(3,'USA',200),(4,'India',120),(5,'Brazil',180);
SELECT country, SUM(impact) as total_impact FROM program_impact WHERE program_id IN (SELECT program_id FROM program_impact WHERE program_id IN (SELECT program_id FROM program_impact WHERE year = 2022 GROUP BY country HAVING COUNT(*) > 1) GROUP BY country HAVING COUNT(*) > 1) GROUP BY country ORDER BY total_impact DESC LIMIT 2;
What is the total CO2 emission from coal mining operations in the USA and China?
CREATE TABLE mining_operations (id INT,location VARCHAR(50),operation_type VARCHAR(50),monthly_co2_emission INT); INSERT INTO mining_operations (id,location,operation_type,monthly_co2_emission) VALUES (1,'USA','Coal',12000),(2,'China','Coal',18000),(3,'Canada','Gold',8000);
SELECT SUM(CASE WHEN operation_type = 'Coal' AND location IN ('USA', 'China') THEN monthly_co2_emission ELSE 0 END) as total_coal_emission FROM mining_operations;
Virtual tourism revenue by quarter for each country?
CREATE TABLE virtual_tourism_extended_2 (country TEXT,revenue FLOAT,date DATE); INSERT INTO virtual_tourism_extended_2 (country,revenue,date) VALUES ('Spain',25000.0,'2022-03-01'),('Spain',28000.0,'2022-04-01'),('Italy',18000.0,'2022-03-01'),('Italy',20000.0,'2022-04-01'),('Germany',30000.0,'2022-02-01'),('Germany',35000.0,'2022-03-01'),('France',40000.0,'2022-01-01'),('France',42000.0,'2022-02-01'),('Japan',50000.0,'2022-01-01'),('Japan',52000.0,'2022-02-01'),('South Korea',60000.0,'2022-02-01'),('South Korea',62000.0,'2022-03-01');
SELECT country, DATE_TRUNC('quarter', date) AS quarter, SUM(revenue) FROM virtual_tourism_extended_2 GROUP BY country, quarter;
List the top 3 countries with the most tourists in 2025 based on current trends.
CREATE TABLE future_trends (country VARCHAR(50),year INT,projected_visitors INT); INSERT INTO future_trends (country,year,projected_visitors) VALUES ('France',2025,25000000),('Spain',2025,20000000),('Italy',2025,18000000),('Japan',2025,16000000),('Germany',2025,15000000);
SELECT country, projected_visitors FROM future_trends WHERE year = 2025 ORDER BY projected_visitors DESC LIMIT 3;
What is the average loan amount for socially responsible lenders in Asia, grouped by year?
CREATE TABLE Loans (Id INT,Lender VARCHAR(20),Location VARCHAR(20),LoanType VARCHAR(20),LoanAmount DECIMAL(10,2),LoanYear INT); INSERT INTO Loans (Id,Lender,Location,LoanType,LoanAmount,LoanYear) VALUES (1,'LenderA','Asia','Socially Responsible',500.00,2020),(2,'LenderB','Asia','Socially Responsible',700.00,2020),(3,'LenderC','Asia','Socially Responsible',600.00,2021);
SELECT AVG(LoanAmount) AS Avg_Loan_Amount, LoanYear FROM Loans WHERE LoanType = 'Socially Responsible' AND Location = 'Asia' GROUP BY LoanYear;
What is the number of smart city initiatives and their average carbon offsets by location?
CREATE TABLE smart_city_initiatives (initiative_id INT,initiative_name VARCHAR(50),location VARCHAR(50),carbon_offsets FLOAT); INSERT INTO smart_city_initiatives (initiative_id,initiative_name,location,carbon_offsets) VALUES (1,'Smart Grid 1','CityC',1000.0),(2,'Smart Lighting 1','CityD',500.0),(3,'Smart Waste Management 1','CityC',1500.0);
SELECT location, COUNT(*), AVG(carbon_offsets) FROM smart_city_initiatives GROUP BY location;
Delete records of cars with no fuel type specified in the cars table.
cars (id,make,model,year,fuel_type)
DELETE FROM cars WHERE cars.fuel_type IS NULL;
What is the average production of Europium per country in 2018?
CREATE TABLE production (country VARCHAR(255),element VARCHAR(255),quantity INT,year INT); INSERT INTO production (country,element,quantity,year) VALUES ('China','Europium',2000,2018),('China','Europium',2500,2018),('United States','Europium',1000,2018),('United States','Europium',1200,2018);
SELECT country, AVG(quantity) as avg_production FROM production WHERE element = 'Europium' AND year = 2018 GROUP BY country;
What is the average CO2 offset for each carbon offset initiative in the carbon_offset_initiatives table?
CREATE TABLE IF NOT EXISTS carbon_offset_initiatives (initiative_id INT,initiative_name VARCHAR(255),co2_offset FLOAT,PRIMARY KEY (initiative_id)); INSERT INTO carbon_offset_initiatives (initiative_id,initiative_name,co2_offset) VALUES (1,'Tree Planting',50),(2,'Solar Power Installation',100),(3,'Wind Farm Development',150);
SELECT AVG(co2_offset) FROM carbon_offset_initiatives;
Which region had the highest sales in Q3 2022?
CREATE TABLE sales_by_region (region VARCHAR(20),quarter VARCHAR(2),year INT,sales_amount FLOAT); INSERT INTO sales_by_region (region,quarter,year,sales_amount) VALUES ('Europe','Q3',2022,90000.0),('Asia','Q3',2022,85000.0),('Africa','Q3',2022,95000.0);
SELECT region, MAX(sales_amount) FROM sales_by_region WHERE quarter = 'Q3' AND year = 2022 GROUP BY region;
What is the total amount of dysprosium exported to Africa in the past 3 years by companies with a revenue greater than $1 billion?
CREATE TABLE export_info (id INT,element TEXT,location TEXT,company TEXT,date DATE,quantity INT,revenue INT); INSERT INTO export_info (id,element,location,company,date,quantity,revenue) VALUES (1,'dysprosium','Africa','Company A','2019-01-01',500,2000000000),(2,'dysprosium','Africa','Company B','2020-01-01',600,3000000000);
SELECT SUM(quantity) FROM export_info WHERE element = 'dysprosium' AND location = 'Africa' AND company IN (SELECT company FROM export_info WHERE revenue > 1000000000) AND extract(year from date) >= 2019;
List the top 3 regions with the highest mental health parity index scores, along with their corresponding scores.
CREATE TABLE MentalHealthParity (Region VARCHAR(255),ParityIndexScore INT); INSERT INTO MentalHealthParity (Region,ParityIndexScore) VALUES ('North',80),('South',85),('East',70),('West',90);
SELECT Region, ParityIndexScore FROM (SELECT Region, ParityIndexScore, ROW_NUMBER() OVER (ORDER BY ParityIndexScore DESC) as Rank FROM MentalHealthParity) as RankedData WHERE Rank <= 3;
List the auto show events happening in Japan in 2023.
CREATE TABLE AutoShows (name VARCHAR(20),country VARCHAR(10),year INT); INSERT INTO AutoShows (name,country,year) VALUES ('Tokyo Auto Salon','Japan',2023);
SELECT name FROM AutoShows WHERE country = 'Japan' AND year = 2023;
What is the maximum contract value awarded to a defense contractor in Texas in 2022?
CREATE TABLE ContractValues (company TEXT,contract_date DATE,contract_value FLOAT); INSERT INTO ContractValues (company,contract_date,contract_value) VALUES ('Contractor D','2022-03-01',3000000),('Contractor E','2022-07-15',4000000),('Contractor F','2022-11-30',2500000);
SELECT MAX(contract_value) FROM ContractValues WHERE company LIKE '%defense%' AND contract_date BETWEEN '2022-01-01' AND '2022-12-31' AND state = 'Texas';
How many female and male beneficiaries were served by each program in 2020?
CREATE TABLE beneficiaries (program VARCHAR(10),gender VARCHAR(6),date DATE); INSERT INTO beneficiaries (program,gender,date) VALUES ('ProgA','Female','2020-01-01'),('ProgA','Male','2020-01-05'),('ProgB','Female','2020-03-02');
SELECT program, gender, COUNT(*) FROM beneficiaries WHERE YEAR(date) = 2020 GROUP BY program, gender;
How many performances were held in Asia or Oceania between 2010 and 2020?
CREATE TABLE Performances (id INT,name TEXT,year INT,location TEXT,type TEXT); INSERT INTO Performances (id,name,year,location,type) VALUES (1,'Performance1',2015,'Japan','dance'),(2,'Performance2',2005,'USA','theater'),(3,'Performance3',2018,'Australia','music');
SELECT COUNT(*) FROM Performances WHERE location IN ('Asia', 'Oceania') AND year BETWEEN 2010 AND 2020;
What is the total number of citizen feedback records received for the 'Housing' service?
CREATE TABLE Feedback (Date DATE,Region VARCHAR(50),Service VARCHAR(50),Comment TEXT); INSERT INTO Feedback (Date,Region,Service,Comment) VALUES ('2021-01-01','Central','Healthcare','Great service'),('2021-01-02','Central','Healthcare','Poor service'),('2021-02-01','North','Education','Excellent education'),('2022-03-01','East','Housing','Adequate conditions');
SELECT COUNT(*) FROM Feedback WHERE Service = 'Housing';
What is the total defense spending for each continent?
CREATE TABLE defense_spending (country VARCHAR(50),continent VARCHAR(50),amount DECIMAL(10,2)); INSERT INTO defense_spending (country,continent,amount) VALUES ('USA','North America',73200000000),('China','Asia',26100000000),('Russia','Europe',61000000000),('Japan','Asia',50500000000),('India','Asia',57000000000);
SELECT continent, SUM(amount) as total_defense_spending FROM defense_spending GROUP BY continent;
Get the number of new followers for each user in the last month, pivoted by day of the week in the "users" table
CREATE TABLE users (id INT,username VARCHAR(255),followers INT,follow_date DATE);
SELECT username, SUM(CASE WHEN DATE_FORMAT(follow_date, '%W') = 'Monday' THEN 1 ELSE 0 END) AS Monday, SUM(CASE WHEN DATE_FORMAT(follow_date, '%W') = 'Tuesday' THEN 1 ELSE 0 END) AS Tuesday, SUM(CASE WHEN DATE_FORMAT(follow_date, '%W') = 'Wednesday' THEN 1 ELSE 0 END) AS Wednesday, SUM(CASE WHEN DATE_FORMAT(follow_date, '%W') = 'Thursday' THEN 1 ELSE 0 END) AS Thursday, SUM(CASE WHEN DATE_FORMAT(follow_date, '%W') = 'Friday' THEN 1 ELSE 0 END) AS Friday, SUM(CASE WHEN DATE_FORMAT(follow_date, '%W') = 'Saturday' THEN 1 ELSE 0 END) AS Saturday, SUM(CASE WHEN DATE_FORMAT(follow_date, '%W') = 'Sunday' THEN 1 ELSE 0 END) AS Sunday FROM users WHERE follow_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY username;
What is the average number of humanitarian assistance missions carried out by each organization in the last 2 years?
CREATE TABLE Humanitarian_Assistance_Missions (id INT,organization VARCHAR(50),year INT,missions INT);
SELECT organization, AVG(missions) as avg_missions FROM Humanitarian_Assistance_Missions WHERE year BETWEEN (YEAR(CURRENT_DATE) - 2) AND YEAR(CURRENT_DATE) GROUP BY organization;
How many cases were opened for each month in the year 2020?
CREATE TABLE Cases (id INT,case_number INT,opened_date DATE);
SELECT MONTH(opened_date) AS Month, COUNT(*) AS NumberOfCases FROM Cases WHERE YEAR(opened_date) = 2020 GROUP BY Month;
Show the details of volunteers who have donated more than $1000?
CREATE TABLE VolunteerDonors (VolunteerID INT,VolunteerName TEXT,DonationAmount DECIMAL(10,2),DonationDate DATE); INSERT INTO VolunteerDonors (VolunteerID,VolunteerName,DonationAmount,DonationDate) VALUES (1,'Ravi Patel',1200.00,'2022-06-01');
SELECT * FROM VolunteerDonors WHERE DonationAmount > 1000;
Display the view JobTitlesDepartments
CREATE VIEW JobTitlesDepartments AS SELECT JobTitle,Department FROM TalentAcquisition;
SELECT * FROM JobTitlesDepartments;
List the number of unique industries and total funding for companies founded by people of color before 2010
CREATE TABLE diversity (id INT,company_id INT,founder_race VARCHAR(255)); INSERT INTO diversity SELECT 1,1,'Hispanic'; INSERT INTO diversity SELECT 2,2,'Asian'; INSERT INTO diversity SELECT 3,3,'Black'; INSERT INTO companies (id,industry,founding_date) SELECT 2,'Finance','2005-01-01'; INSERT INTO companies (id,industry,founding_date) SELECT 3,'Retail','2008-01-01'; INSERT INTO companies (id,industry,founding_date) SELECT 4,'IT','2012-01-01'; INSERT INTO funding (company_id,amount) SELECT 2,1000000; INSERT INTO funding (company_id,amount) SELECT 3,750000; INSERT INTO funding (company_id,amount) SELECT 4,1250000;
SELECT diversity.founder_race, COUNT(DISTINCT companies.industry) AS unique_industries, SUM(funding.amount) AS total_funding FROM diversity JOIN companies ON diversity.company_id = companies.id JOIN funding ON companies.id = funding.company_id WHERE companies.founding_date < '2010-01-01' AND diversity.founder_race IN ('Hispanic', 'Asian', 'Black') GROUP BY diversity.founder_race;
Find the number of unique IP addresses associated with malware activity in the 'South America' region in the past month.
CREATE TABLE malware_activity (id INT,ip_address VARCHAR(15),malware_type VARCHAR(255),region VARCHAR(100),last_seen DATE); INSERT INTO malware_activity (id,ip_address,malware_type,region,last_seen) VALUES (1,'192.168.1.1','ransomware','Asia-Pacific','2021-11-01'),(2,'10.0.0.1','virut','North America','2021-12-05'),(3,'192.168.1.1','ransomware','Asia-Pacific','2021-12-12'),(4,'10.0.0.2','wannacry','South America','2021-12-08');
SELECT COUNT(DISTINCT ip_address) FROM malware_activity WHERE region = 'South America' AND last_seen >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
Which brands have received the most cruelty-free certifications?
CREATE TABLE Brands (Brand_ID INT PRIMARY KEY,Brand_Name TEXT); CREATE TABLE Certifications (Certification_ID INT PRIMARY KEY,Certification_Name TEXT,Brand_ID INT); INSERT INTO Brands (Brand_ID,Brand_Name) VALUES (1,'Ethical Beauty'),(2,'Pure Cosmetics'),(3,'Green Earth'),(4,'Eco Living'),(5,'Sustainable Solutions'); INSERT INTO Certifications (Certification_ID,Certification_Name,Brand_ID) VALUES (1,'Leaping Bunny',1),(2,'Cruelty Free International',1),(3,'People for the Ethical Treatment of Animals (PETA)',2),(4,'Leaping Bunny',2),(5,'Cruelty Free International',3),(6,'Leaping Bunny',3),(7,'People for the Ethical Treatment of Animals (PETA)',4),(8,'Leaping Bunny',4),(9,'Cruelty Free International',5),(10,'People for the Ethical Treatment of Animals (PETA)',5);
SELECT b.Brand_Name, COUNT(c.Certification_ID) AS Cruelty_Free_Certifications_Count FROM Brands b JOIN Certifications c ON b.Brand_ID = c.Brand_ID GROUP BY b.Brand_ID;
What is the total revenue generated by tourism in Bali in 2020?
CREATE TABLE bali_tourism (id INT,year INT,revenue INT); INSERT INTO bali_tourism (id,year,revenue) VALUES (1,2019,10000000),(2,2020,5000000);
SELECT SUM(revenue) FROM bali_tourism WHERE year = 2020;
List the companies that have not received any funding.
CREATE TABLE companies (id INT,name TEXT); CREATE TABLE fundings (id INT,company_id INT,round TEXT); INSERT INTO companies (id,name) VALUES (1,'Acme Inc'),(2,'Zebra Corp'),(3,'Dino Tech'),(4,'Elephant Inc'); INSERT INTO fundings (id,company_id,round) VALUES (1,1,'Seed'),(2,1,'Series A'),(3,2,'Seed'),(4,2,'Series A');
SELECT companies.name FROM companies LEFT JOIN fundings ON companies.id = fundings.company_id WHERE fundings.id IS NULL;
What is the average monthly donation per donor category?
CREATE TABLE monthly_donations_category (id INT,donor_category VARCHAR(50),donor_name VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO monthly_donations_category (id,donor_category,donor_name,donation_amount,donation_date) VALUES (1,'Regular','John Doe',50,'2022-01-01'),(2,'One-time','Jane Smith',75,'2022-01-15'),(3,'Regular','John Doe',60,'2022-02-01');
SELECT donor_category, AVG(donation_amount) as avg_monthly_donation FROM monthly_donations_category GROUP BY donor_category;
What is the average revenue per day for the month of January for a given year?
CREATE TABLE Sales (sale_id INT PRIMARY KEY,sale_date DATE,item_sold VARCHAR(255),quantity INT,sale_price DECIMAL(5,2));
SELECT AVG(SUM(quantity * sale_price)) FROM Sales WHERE sale_date BETWEEN '2022-01-01' AND '2022-01-31';
Insert a new row with id '4', name 'Dana', project 'protein folding' into the 'researchers' table.
CREATE TABLE researchers (id INT,name VARCHAR(50),project VARCHAR(50)); INSERT INTO researchers (id,name,project) VALUES (1,'Alice','gene sequencing'),(2,'Bob','biosensor development'),(3,'Charlie','gene sequencing');
INSERT INTO researchers (id, name, project) VALUES (4, 'Dana', 'protein folding');
List all vessels inspected in 'Africa' during 2021 and 2022.
CREATE TABLE Vessels_4 (id INT,name VARCHAR(255),region VARCHAR(255),year INT); INSERT INTO Vessels_4 (id,name,region,year) VALUES (1,'African Wave','Africa',2021); INSERT INTO Vessels_4 (id,name,region,year) VALUES (2,'Ocean Splash','Africa',2022); INSERT INTO Vessels_4 (id,name,region,year) VALUES (3,'Marine Journey','Africa',2021); INSERT INTO Vessels_4 (id,name,region,year) VALUES (4,'Sea Explorer','Africa',2022);
SELECT name FROM Vessels_4 WHERE region = 'Africa' AND year IN (2021, 2022);
Insert new records of art programs for underrepresented communities, each with a budget of 10000 and a public funding source.
CREATE TABLE programs (name VARCHAR(25),budget INT,funding_source VARCHAR(15));
INSERT INTO programs (name, budget, funding_source) VALUES ('Art for Indigenous Youth', 10000, 'public'), ('Art for Disability Community', 10000, 'public');
What is the percentage change in the number of language preservation programs offered in Asia between 2015 and 2020?
CREATE TABLE asia_lang_progs (id INT,org_name TEXT,year INT,num_progs INT); INSERT INTO asia_lang_progs (id,org_name,year,num_progs) VALUES (1,'Shanghai Language Institute',2015,100),(2,'Tokyo Language School',2016,120),(3,'Beijing Language University',2017,150),(4,'New Delhi Language Academy',2018,180),(5,'Seoul Language Institute',2019,210),(6,'Hong Kong Language School',2020,240);
SELECT (SUM(CASE WHEN year = 2020 THEN num_progs ELSE 0 END) - SUM(CASE WHEN year = 2015 THEN num_progs ELSE 0 END)) * 100.0 / SUM(CASE WHEN year = 2015 THEN num_progs ELSE 0 END) as pct_change FROM asia_lang_progs WHERE org_name IN ('Shanghai Language Institute', 'Tokyo Language School', 'Beijing Language University', 'New Delhi Language Academy', 'Seoul Language Institute', 'Hong Kong Language School') AND year IN (2015, 2020);
Find the number of unique users who have streamed a song on each day in the US.
CREATE TABLE users (user_id INT,user_country VARCHAR(255)); CREATE TABLE streams (stream_id INT,song_id INT,user_id INT,stream_date DATE);
SELECT stream_date, COUNT(DISTINCT user_id) as unique_users FROM streams st JOIN users u ON st.user_id = u.user_id WHERE u.user_country = 'United States' GROUP BY stream_date;
List the number of carbon capture and storage facilities in the United States, Germany, and Saudi Arabia, as of 2020.
CREATE TABLE carbon_storage (country VARCHAR(50),operational BOOLEAN,year INT); INSERT INTO carbon_storage (country,operational,year) VALUES ('United States',true,2020),('Germany',true,2020),('Saudi Arabia',true,2020),('Norway',false,2020);
SELECT country, COUNT(*) FROM carbon_storage WHERE country IN ('United States', 'Germany', 'Saudi Arabia') AND operational = true GROUP BY country;
What is the highest level of education achieved by immigrants in Germany?
CREATE TABLE immigrants (id INT,name VARCHAR(100),education VARCHAR(50)); INSERT INTO immigrants (id,name,education) VALUES (1,'Immigrant 1','High School'); INSERT INTO immigrants (id,name,education) VALUES (2,'Immigrant 2','Bachelor’s Degree');
SELECT education FROM (SELECT education, ROW_NUMBER() OVER (ORDER BY education DESC) as row_num FROM immigrants) immigrants_ranked WHERE row_num = 1;
Show environmental impact score for site 'Z' and 'W'.
CREATE SCHEMA if not exists mining;CREATE TABLE mining.impact (id INT,site STRING,ias_score INT);INSERT INTO mining.impact (id,site,ias_score) VALUES (1,'site Z',65),(2,'site W',75),(3,'site X',85);
SELECT ias_score FROM mining.impact WHERE site IN ('site Z', 'site W');
What is the maximum loan amount for socially responsible lending in the United States?
CREATE TABLE socially_responsible_lending (id INT,loan_amount FLOAT,country VARCHAR(255)); INSERT INTO socially_responsible_lending (id,loan_amount,country) VALUES (1,5000,'USA'),(2,7000,'USA'),(3,8000,'USA');
SELECT MAX(loan_amount) FROM socially_responsible_lending WHERE country = 'USA';
What was the R&D expenditure for each drug in Q1 2023, pivoted by division?
CREATE TABLE r_d_expenditure (drug VARCHAR(20),division VARCHAR(20),date DATE,expenditure NUMERIC(12,2)); INSERT INTO r_d_expenditure (drug,division,date,expenditure) VALUES ('DrugA','Oncology','2023-01-01',150000.00),('DrugB','Cardiology','2023-01-01',120000.00),('DrugA','Neurology','2023-01-01',90000.00),('DrugB','Oncology','2023-01-01',155000.00),('DrugA','Cardiology','2023-01-01',123000.00),('DrugB','Neurology','2023-01-01',915000.00);
SELECT drug, SUM(CASE WHEN division = 'Oncology' THEN expenditure ELSE 0 END) AS oncology_expenditure, SUM(CASE WHEN division = 'Cardiology' THEN expenditure ELSE 0 END) AS cardiology_expenditure FROM r_d_expenditure WHERE date BETWEEN '2023-01-01' AND '2023-03-31' GROUP BY drug;
How many employees have undergone diversity training in the Sales department?
CREATE TABLE TrainingData (EmployeeID INT,Department TEXT,Training TEXT); INSERT INTO TrainingData (EmployeeID,Department,Training) VALUES (1,'Sales','Diversity');
SELECT COUNT(*) FROM TrainingData WHERE Department = 'Sales' AND Training = 'Diversity';
Update the name of food product with id 1 to 'Organic Quinoa Puffs'
CREATE TABLE food_products (id INT PRIMARY KEY,name TEXT,safety_recall BOOLEAN);
UPDATE food_products SET name = 'Organic Quinoa Puffs' WHERE id = 1;
What is the average rating for 'boutique' hotels in 'Sydney' on 'Agoda'?
CREATE TABLE Ratings (hotel_id INT,ota TEXT,city TEXT,hotel_class TEXT,rating FLOAT); INSERT INTO Ratings (hotel_id,ota,city,hotel_class,rating) VALUES (1,'Agoda','Sydney','boutique',4.7),(2,'Agoda','Sydney','boutique',4.6),(3,'Agoda','Sydney','non-boutique',4.3);
SELECT AVG(rating) FROM Ratings WHERE ota = 'Agoda' AND city = 'Sydney' AND hotel_class = 'boutique';
How many cases were handled by each caseworker in the justice department, with the total number of cases and cases per caseworker?
CREATE TABLE cases (id INT,caseworker_id INT,date DATE); INSERT INTO cases (id,caseworker_id,date) VALUES (1,101,'2020-01-01'),(2,101,'2020-01-10'),(3,102,'2020-02-01');
SELECT COUNT(*) OVER (PARTITION BY caseworker_id) AS cases_per_caseworker, COUNT(*) AS total_cases FROM cases;
Add a new language preservation project in 'Mexico'
CREATE TABLE language_preservation (id INT PRIMARY KEY,name TEXT,location TEXT);
INSERT INTO language_preservation (id, name, location) VALUES (1, 'Mixtec Language', 'Mexico');
Find brands that use ingredients from 'India' and have no safety records after 2022-01-01
CREATE TABLE ingredient (product_id INT,ingredient TEXT,origin TEXT);
SELECT brand FROM ingredient INNER JOIN (SELECT product_id FROM safety_record WHERE report_date > '2022-01-01' EXCEPT SELECT product_id FROM safety_record) ON ingredient.product_id = product_id WHERE origin = 'India';
What is the total square footage of sustainable building projects?
CREATE TABLE sustainable_projects (project_id SERIAL PRIMARY KEY,square_footage INTEGER,is_sustainable BOOLEAN); INSERT INTO sustainable_projects (project_id,square_footage,is_sustainable) VALUES (1,15000,true),(2,20000,false),(3,25000,true);
SELECT SUM(square_footage) FROM sustainable_projects WHERE is_sustainable = true;
What is the average duration of space missions per agency?
CREATE TABLE SpaceAgency (ID INT,Name VARCHAR(50),Country VARCHAR(50)); CREATE TABLE SpaceMission (AgencyID INT,Name VARCHAR(50),LaunchDate DATE,Duration INT);
SELECT sa.Name, AVG(sm.Duration) AS AvgDuration FROM SpaceAgency sa JOIN SpaceMission sm ON sa.ID = sm.AgencyID GROUP BY sa.Name;
Which countries have had the most security incidents in the last 6 months?
CREATE TABLE security_incidents (id INT,country VARCHAR(255),timestamp TIMESTAMP);
SELECT country, COUNT(*) FROM security_incidents WHERE timestamp >= NOW() - INTERVAL 6 MONTH GROUP BY country ORDER BY COUNT(*) DESC LIMIT 10;
What is the average budget for assistive technology programs in the Midwest region?
CREATE TABLE midwest_region (region VARCHAR(20),budget INT); INSERT INTO midwest_region (region,budget) VALUES ('Midwest',50000); INSERT INTO midwest_region (region,budget) VALUES ('Midwest',75000);
SELECT AVG(budget) FROM midwest_region WHERE region = 'Midwest';
List the number of satellites deployed per year by each organization.
CREATE TABLE SatelliteDeployments (id INT,organization VARCHAR(50),launch_year INT,launch_success BOOLEAN); INSERT INTO SatelliteDeployments (id,organization,launch_year,launch_success) VALUES (1,'NASA',2010,true),(2,'NASA',2015,true),(3,'SpaceX',2017,true),(4,'SpaceX',2018,false),(5,'ISRO',2020,true);
SELECT organization, launch_year, COUNT(*) as total_satellites FROM SatelliteDeployments GROUP BY organization, launch_year ORDER BY organization, launch_year;
Update the name of the project to 'Soil Conservation' in the 'agricultural_practices' table
CREATE TABLE agricultural_practices (id INT,project_name VARCHAR(255),country VARCHAR(255));
UPDATE agricultural_practices SET project_name = 'Soil Conservation' WHERE id = 1;
What is the average severity of vulnerabilities in the healthcare sector in the last quarter?
CREATE TABLE vulnerabilities (id INT,sector VARCHAR(255),severity FLOAT,discovered_at TIMESTAMP); INSERT INTO vulnerabilities (id,sector,severity,discovered_at) VALUES (1,'healthcare',7.0,'2021-04-01 12:00:00'),(2,'finance',5.5,'2021-05-05 14:30:00');
SELECT AVG(severity) FROM vulnerabilities WHERE discovered_at >= DATE_SUB(NOW(), INTERVAL 3 MONTH) AND sector = 'healthcare';
What is the prevalence of diabetes in rural areas of India, Pakistan, and Bangladesh?
CREATE TABLE diabetes_patients_asia (name TEXT,location TEXT,country TEXT); INSERT INTO diabetes_patients_asia (name,location,country) VALUES ('Patient 1','Rural India','India'),('Patient 2','Rural Pakistan','Pakistan'),('Patient 3','Urban Pakistan','Pakistan'),('Patient 4','Rural Bangladesh','Bangladesh');
SELECT country, ROUND(COUNT(*)*100.0/((SELECT COUNT(*) FROM diabetes_patients_asia WHERE country = t.country)::FLOAT), 2) AS prevalence FROM diabetes_patients_asia t WHERE location LIKE 'Rural%' GROUP BY country
Find the total number of vehicle recalls for each make in the 'recalls_data' table.
CREATE TABLE recalls_data (id INT,recall_date DATE,make VARCHAR(50),model VARCHAR(50),num_recalled INT);
SELECT make, SUM(num_recalled) FROM recalls_data GROUP BY make;
List the names of community health workers who serve the most mental health providers.
CREATE TABLE MentalHealthProvider (ProviderID INT,WorkerID INT,WorkerName VARCHAR(50)); INSERT INTO MentalHealthProvider (ProviderID,WorkerID,WorkerName) VALUES (1,1,'John'),(2,2,'Jane'),(3,3,'Jim'),(4,4,'Joan'),(5,5,'Jake'),(6,1,'Jill'),(7,2,'Jeff'),(8,3,'Jessica'),(9,4,'Jeremy'),(10,5,'Jamie');
SELECT WorkerName, COUNT(*) as NumProviders FROM MentalHealthProvider GROUP BY WorkerName ORDER BY NumProviders DESC LIMIT 1;
Display the hourly breakdown of tram delays for the second half of 2021
CREATE TABLE trams (id INT PRIMARY KEY,delay INT,delay_time TIMESTAMP);
SELECT HOUR(delay_time) AS delay_hour, AVG(delay) AS avg_delay FROM trams WHERE delay_time >= '2021-07-01 00:00:00' AND delay_time < '2022-01-01 00:00:00' GROUP BY delay_hour;
What's the total number of shelters and their capacities in urban areas of Colombia and Peru?
CREATE TABLE shelters (id INT,name TEXT,capacity INT,area TEXT); INSERT INTO shelters (id,name,capacity,area) VALUES (1,'ShelterA',200,'urban'),(2,'ShelterB',150,'urban'),(3,'ShelterC',300,'rural');
SELECT capacity FROM shelters WHERE area = 'urban' AND (area = 'colombia' OR area = 'peru')
What is the average price of neodymium produced in Australia?
CREATE TABLE neodymium_prices (country VARCHAR(20),price DECIMAL(5,2),year INT); INSERT INTO neodymium_prices (country,price,year) VALUES ('Australia',85.00,2020),('Australia',88.50,2021);
SELECT AVG(price) FROM neodymium_prices WHERE country = 'Australia';
What are the names and protection levels of heritage sites in East Asia?
CREATE TABLE heritage_sites (id INT,site_name TEXT,location TEXT,protection_level TEXT); INSERT INTO heritage_sites (id,site_name,location,protection_level) VALUES (1,'Great Wall of China','China','UNESCO World Heritage Site'),(2,'Temple of Heaven','China','National Heritage Site');
SELECT site_name, protection_level FROM heritage_sites WHERE location LIKE '%%East Asia%%';
What is the total value of loans issued to customers in each state?
CREATE TABLE loans (id INT,customer_id INT,state VARCHAR(50),value DECIMAL(10,2)); INSERT INTO loans (id,customer_id,state,value) VALUES (1,1,'California',10000.00),(2,2,'New York',20000.00),(3,3,'Texas',15000.00);
SELECT state, SUM(value) FROM loans GROUP BY state;
On which dates did California have a drought impact greater than 0.8?
CREATE TABLE DroughtImpact (Id INT,Location VARCHAR(50),Impact DECIMAL(5,2),Date DATE); INSERT INTO DroughtImpact (Id,Location,Impact,Date) VALUES (1,'California',0.9,'2021-06-15'); INSERT INTO DroughtImpact (Id,Location,Impact,Date) VALUES (2,'California',0.7,'2021-07-01');
SELECT Date, AVG(Impact) FROM DroughtImpact WHERE Location = 'California' GROUP BY Date HAVING AVG(Impact) > 0.8;
What is the total number of international tourists visiting Brazil, grouped by their countries of origin?
CREATE TABLE international_visitors (visitor_country VARCHAR(50),total_visits INT); INSERT INTO international_visitors (visitor_country,total_visits) VALUES ('Brazil',30000);
SELECT visitor_country, SUM(total_visits) FROM international_visitors WHERE visitor_country = 'Brazil' GROUP BY visitor_country;
What is the total number of co-owned properties in the city of Portland?
CREATE TABLE properties (property_id INT,city VARCHAR(50),co_owned BOOLEAN,price INT); INSERT INTO properties (property_id,city,co_owned,price) VALUES (1,'Portland',TRUE,400000); INSERT INTO properties (property_id,city,co_owned,price) VALUES (2,'Portland',TRUE,450000); INSERT INTO properties (property_id,city,co_owned,price) VALUES (3,'Portland',FALSE,300000); INSERT INTO properties (property_id,city,co_owned,price) VALUES (4,'Portland',FALSE,500000); INSERT INTO properties (property_id,city,co_owned,price) VALUES (5,'Portland',FALSE,550000);
SELECT COUNT(*) AS total_co_owned FROM properties WHERE city = 'Portland' AND co_owned = TRUE;
What is the average horsepower of electric vehicles in the 'green_cars' table?
CREATE TABLE green_cars (id INT PRIMARY KEY,make VARCHAR(50),model VARCHAR(50),year INT,horsepower INT,is_electric BOOLEAN);
SELECT AVG(horsepower) FROM green_cars WHERE is_electric = TRUE;
List all smart city projects in the 'infrastructure' table for the 'Asia' region.
CREATE TABLE infrastructure (id INT,project_name TEXT,location TEXT,project_type TEXT); INSERT INTO infrastructure (id,project_name,location,project_type) VALUES (1,'Smart City 1','Singapore','smart_city'),(2,'Green Building 1','Japan','green_building');
SELECT project_name FROM infrastructure WHERE location LIKE '%Asia%' AND project_type = 'smart_city';
What is the total installed renewable energy capacity for the top 5 countries in 2020?
CREATE TABLE RenewableCapacity (Country TEXT,Year INT,Capacity NUMBER); INSERT INTO RenewableCapacity (Country,Year,Capacity) VALUES ('China',2020,750000),('United States',2020,500000),('Germany',2020,300000),('India',2020,250000),('Brazil',2020,200000),('Australia',2020,150000);
SELECT Country, SUM(Capacity) AS Total_Capacity FROM RenewableCapacity WHERE Year = 2020 GROUP BY Country ORDER BY Total_Capacity DESC LIMIT 5;
Display the policy numbers and claim dates for claims that were processed between '2021-01-01' and '2021-12-31'
CREATE TABLE claims (claim_id INT,policy_number INT,claim_amount DECIMAL(10,2),claim_date DATE);
SELECT policy_number, claim_date FROM claims WHERE claim_date BETWEEN '2021-01-01' AND '2021-12-31';
What is the distribution of ratings for movies produced in the USA?
CREATE TABLE movies (id INT,title VARCHAR(255),rating FLOAT,production_country VARCHAR(50)); INSERT INTO movies (id,title,rating,production_country) VALUES (1,'MovieA',7.5,'USA'),(2,'MovieB',8.2,'Spain'),(3,'MovieC',6.8,'USA'),(4,'MovieD',9.0,'USA');
SELECT rating, COUNT(*) FROM movies WHERE production_country = 'USA' GROUP BY rating;
What is the total climate finance committed by development banks in the Middle East and North Africa?
CREATE TABLE climate_finance_commitments (commitment_id INT,commitment_amount DECIMAL(10,2),funder VARCHAR(50),region VARCHAR(50)); INSERT INTO climate_finance_commitments (commitment_id,commitment_amount,funder,region) VALUES (1,1500000.00,'European Investment Bank','Middle East and North Africa'),(2,2000000.00,'World Bank','Middle East and North Africa'),(3,1000000.00,'German Development Bank','Middle East and North Africa');
SELECT SUM(commitment_amount) FROM climate_finance_commitments WHERE region = 'Middle East and North Africa';
Calculate the total amount of oil and gas resources in each Arctic country.
CREATE TABLE Resources (id INT PRIMARY KEY,resource VARCHAR(255),location VARCHAR(255),quantity INT); INSERT INTO Resources (id,resource,location,quantity) VALUES (1,'oil','Russia',10000000); INSERT INTO Resources (id,resource,location,quantity) VALUES (2,'gas','Norway',8000000);
SELECT location, SUM(CASE WHEN resource IN ('oil', 'gas') THEN quantity ELSE 0 END) as total_quantity FROM Resources GROUP BY location;
Which public works projects were completed in the last 5 years, and what was their budget?
CREATE TABLE Projects (id INT,name TEXT,completion_date DATE,budget INT); INSERT INTO Projects (id,name,completion_date,budget) VALUES (1,'I-405 Widening','2022-01-01',2000000),(2,'LA River Revitalization','2020-12-31',15000000);
SELECT name, budget FROM Projects WHERE completion_date > (CURRENT_DATE - INTERVAL '5 years')
What is the average age of rural healthcare workers by position?
CREATE TABLE healthcare_workers (id INT,name TEXT,age INT,position TEXT,hospital_id INT); INSERT INTO healthcare_workers (id,name,age,position,hospital_id) VALUES (1,'John Doe',45,'Doctor',2),(2,'Jane Smith',30,'Nurse',2); CREATE TABLE rural_hospitals (id INT,name TEXT,location TEXT,state TEXT); INSERT INTO rural_hospitals (id,name,location,state) VALUES (2,'Hospital B','Rural Area 2','California');
SELECT position, AVG(age) FROM healthcare_workers WHERE hospital_id IN (SELECT id FROM rural_hospitals) GROUP BY position;
How many healthcare providers in each state have completed cultural competency training?
CREATE TABLE healthcare_providers_training (id INT,provider_id INT,state VARCHAR(20),completed_training BOOLEAN); INSERT INTO healthcare_providers_training (id,provider_id,state,completed_training) VALUES (1,1,'California',TRUE),(2,2,'New York',FALSE),(3,3,'Texas',TRUE);
SELECT state, SUM(completed_training) as providers_trained FROM healthcare_providers_training GROUP BY state;
Determine the difference in average transaction amounts between customers from 'North America' and 'Asia'.
CREATE TABLE transaction_amounts (customer_id INT,region VARCHAR(20),transaction_amount NUMERIC(12,2)); INSERT INTO transaction_amounts (customer_id,region,transaction_amount) VALUES (1,'Asia',1000),(2,'Europe',1500),(3,'Africa',750),(4,'North America',2000),(5,'South America',1200),(6,'Australia',1750),(7,'Asia',1500),(8,'Europe',2000),(9,'Africa',1000),(10,'North America',2500);
SELECT AVG(transaction_amount) as avg_asia FROM transaction_amounts WHERE region = 'Asia' INTERSECT SELECT AVG(transaction_amount) as avg_north_america FROM transaction_amounts WHERE region = 'North America';
What is the total number of defense contracts awarded to companies in Europe in 2021?
CREATE TABLE defense_contract_companies (id INT,company VARCHAR(50),country VARCHAR(50),year INT,contract_value FLOAT); INSERT INTO defense_contract_companies (id,company,country,year,contract_value) VALUES (1,'BAE Systems','UK',2021,5000000); INSERT INTO defense_contract_companies (id,company,country,year,contract_value) VALUES (2,'Airbus Group','France',2021,1000000);
SELECT SUM(contract_value) FROM defense_contract_companies WHERE country IN ('UK', 'France', 'Germany', 'Italy', 'Spain') AND year = 2021;
What are the top 5 most common vulnerabilities in the 'web application' asset type in the last quarter?
CREATE TABLE webapp_vulnerabilities (id INT,asset_type VARCHAR(50),vulnerability_count INT,vulnerability_date DATE);
SELECT asset_type, vulnerability_count, vulnerability_date, RANK() OVER (PARTITION BY asset_type ORDER BY vulnerability_count DESC) as rank FROM webapp_vulnerabilities WHERE asset_type = 'web application' AND vulnerability_date >= DATEADD(quarter, -1, GETDATE()) AND rank <= 5;
Calculate the percentage of reported thefts in the 'downtown' and 'westside' precincts in the month of August 2021.
CREATE TABLE crimes (id INT,type VARCHAR(20),location VARCHAR(20),report_date DATE); INSERT INTO crimes (id,type,location,report_date) VALUES (1,'theft','downtown','2021-08-01');
SELECT (COUNT(*) FILTER (WHERE type = 'theft')) * 100.0 / COUNT(*) FROM crimes WHERE location IN ('downtown', 'westside') AND report_date BETWEEN '2021-08-01' AND '2021-08-31';
Identify the defense projects that have experienced delays of over 6 months?
CREATE TABLE defense_projects(id INT,project_name VARCHAR(50),start_date DATE,end_date DATE);
SELECT project_name FROM defense_projects WHERE DATEDIFF(end_date, start_date) > 180;
List all fabrics and their certifications that are expiring in the next 3 months.
CREATE TABLE Textile_Certifications (id INT,fabric VARCHAR(20),certification VARCHAR(50),expiration_date DATE); INSERT INTO Textile_Certifications (id,fabric,certification,expiration_date) VALUES (1,'Cotton','GOTS','2023-06-01'),(2,'Polyester','OEKO-TEX','2023-07-15'),(3,'Wool','RWS','2023-08-30'),(4,'Silk','Organic Content Standard','2023-04-20'),(5,'Denim','Global Recycled Standard','2023-09-10');
SELECT fabric, certification FROM Textile_Certifications WHERE expiration_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 MONTH);
Which team received the most penalties in the FIFA World Cup?
CREATE TABLE fifa_world_cup (team VARCHAR(50),penalties INT); INSERT INTO fifa_world_cup (team,penalties) VALUES ('Germany',12),('Brazil',10),('France',11),('Croatia',10);
SELECT team, SUM(penalties) AS total_penalties FROM fifa_world_cup GROUP BY team ORDER BY total_penalties DESC LIMIT 1;
Which organizations have received donations from donors aged 25-34 in the past year?
CREATE TABLE donors (id INT,age INT,name VARCHAR(255)); INSERT INTO donors (id,age,name) VALUES (1,27,'Effective Altruism Funds'); CREATE TABLE donations (id INT,donor_id INT,organization_id INT,amount DECIMAL(10,2),donation_date DATE); INSERT INTO donations (id,donor_id,organization_id,amount,donation_date) VALUES (1,1,3,5000,'2021-06-15');
SELECT organizations.name FROM donations JOIN donors ON donations.donor_id = donors.id JOIN organizations ON donations.organization_id = organizations.id WHERE donors.age BETWEEN 25 AND 34 AND donation_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND CURRENT_DATE;
List all farmers who cultivate 'Rice' and their corresponding regions.
CREATE TABLE farmer (id INT PRIMARY KEY,name VARCHAR(50),crop_id INT,region_id INT); CREATE TABLE crop (id INT PRIMARY KEY,name VARCHAR(50)); CREATE TABLE region (id INT PRIMARY KEY,name VARCHAR(50)); INSERT INTO crop (id,name) VALUES (1,'Rice'); INSERT INTO region (id,name) VALUES (1,'Delta Region'); INSERT INTO farmer (id,name,crop_id,region_id) VALUES (1,'John Doe',1,1);
SELECT f.name, r.name AS region_name FROM farmer f INNER JOIN crop c ON f.crop_id = c.id INNER JOIN region r ON f.region_id = r.id WHERE c.name = 'Rice';
List faculty diversity metrics including the number of female, male, and non-binary faculty members
CREATE TABLE Faculty (id INT,name VARCHAR(255),gender VARCHAR(10),department_id INT); INSERT INTO Faculty (id,name,gender,department_id) VALUES (1,'John Doe','Male',1),(2,'Jane Smith','Female',1),(3,'Jamie Johnson','Non-binary',2),(4,'Alice Davis','Female',3),(5,'Bob Brown','Male',3);
SELECT f.department_id, f.gender, COUNT(*) as num_faculty FROM Faculty f GROUP BY f.department_id, f.gender;
What is the total number of AI safety incidents, grouped by the type of AI system involved?
CREATE TABLE ai_safety_incidents_type (id INT,incident_name VARCHAR(50),date_reported DATE,ai_system_type VARCHAR(50)); INSERT INTO ai_safety_incidents_type (id,incident_name,date_reported,ai_system_type) VALUES (1,'Self-driving car crash','2022-03-15','Autonomous Vehicles'),(2,'Medical diagnosis error','2021-11-27','Healthcare AI'),(3,'Financial loss due to algorithmic trading','2022-01-10','Finance AI');
SELECT ai_system_type, COUNT(*) FROM ai_safety_incidents_type GROUP BY ai_system_type;
Find total number of articles by each author, published in 2020
CREATE TABLE authors (id INT PRIMARY KEY,name TEXT NOT NULL); CREATE TABLE articles (id INT PRIMARY KEY,title TEXT NOT NULL,author_id INT,published_at DATE);
SELECT authors.name, COUNT(articles.id) as total_articles FROM authors INNER JOIN articles ON authors.id = articles.author_id WHERE YEAR(published_at) = 2020 GROUP BY authors.name;
What is the maximum ESG score for companies in the financial sector?
CREATE TABLE companies (id INT,name VARCHAR(255),sector VARCHAR(255),ESG_score FLOAT); INSERT INTO companies (id,name,sector,ESG_score) VALUES (1,'JPMorgan Chase','Financial',80.1); INSERT INTO companies (id,name,sector,ESG_score) VALUES (2,'Visa','Financial',85.6); INSERT INTO companies (id,name,sector,ESG_score) VALUES (3,'Bank of America','Financial',79.2); CREATE TABLE sectors (id INT,sector VARCHAR(255)); INSERT INTO sectors (id,sector) VALUES (1,'Financial'); INSERT INTO sectors (id,sector) VALUES (2,'Healthcare');
SELECT MAX(ESG_score) AS max_ESG_score FROM companies c JOIN sectors s ON c.sector = s.sector WHERE s.sector = 'Financial';
Calculate the total workout duration in minutes for each country, in the last month.
CREATE TABLE membership (member_id INT,membership_type VARCHAR(20),country VARCHAR(30)); INSERT INTO membership (member_id,membership_type,country) VALUES (1,'Platinum','USA'),(2,'Gold','Canada'),(3,'Platinum','Mexico'); CREATE TABLE workout_data (member_id INT,duration INT,timestamp TIMESTAMP); INSERT INTO workout_data (member_id,duration,timestamp) VALUES (1,180,'2022-02-01 10:00:00'),(1,240,'2022-02-01 11:00:00'),(2,300,'2022-02-01 10:00:00'),(2,360,'2022-02-01 11:00:00'),(3,90,'2022-02-01 10:00:00'),(3,120,'2022-02-01 11:00:00');
SELECT country, SUM(duration)/60 as total_minutes FROM workout_data w JOIN membership m ON w.member_id = m.member_id WHERE timestamp BETWEEN '2022-02-01 00:00:00' AND '2022-02-28 23:59:59' GROUP BY country;
Update the budget of a specific military innovation project.
CREATE TABLE military_innovation (id INT,project VARCHAR(255),budget INT);
UPDATE military_innovation SET budget = 5000000 WHERE project = 'Stealth Drone';
What is the maximum daily revenue recorded in the database?
CREATE TABLE daily_revenue (sale_date DATE,revenue DECIMAL(10,2)); INSERT INTO daily_revenue (sale_date,revenue) VALUES ('2022-01-01',5000.00),('2022-01-02',6000.00),('2022-01-03',4000.00),('2022-01-04',7000.00),('2022-01-05',8000.00),('2022-01-06',3000.00),('2022-01-07',9000.00);
SELECT MAX(revenue) FROM daily_revenue;
Find the top 10 product categories with the highest sales in the last quarter
CREATE TABLE sales (sale_id INT,product_id INT,product_category VARCHAR(255),sales FLOAT,sale_date DATE); INSERT INTO sales (sale_id,product_id,product_category,sales,sale_date) VALUES (1,1,'Electronics',100,'2022-01-01'),(2,2,'Clothing',200,'2022-01-02'),(3,3,'Electronics',150,'2022-01-03');
SELECT product_category, SUM(sales) FROM sales WHERE sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY product_category ORDER BY SUM(sales) DESC LIMIT 10;
Find the total number of smart contracts associated with digital assets having a value greater than 80?
CREATE TABLE digital_assets (asset_id INT,asset_name VARCHAR(50),value DECIMAL(10,2)); INSERT INTO digital_assets (asset_id,asset_name,value) VALUES (1,'Asset1',50.5),(2,'Asset2',100.2),(3,'Asset3',75.0); CREATE TABLE smart_contracts (contract_id INT,asset_id INT,contract_name VARCHAR(50)); INSERT INTO smart_contracts (contract_id,asset_id,contract_name) VALUES (101,1,'Contract1'),(102,2,'Contract2'),(103,3,'Contract3');
SELECT COUNT(*) FROM smart_contracts INNER JOIN digital_assets ON smart_contracts.asset_id = digital_assets.asset_id WHERE digital_assets.value > 80;
What is the total number of climate adaptation projects in Asia with a budget less than $30,000?
CREATE TABLE climate_adaptation (id INT,project_name TEXT,budget INT,location TEXT); INSERT INTO climate_adaptation (id,project_name,budget,location) VALUES (1,'Flood Prevention',75000,'Asia'); INSERT INTO climate_adaptation (id,project_name,budget,location) VALUES (2,'Drought Resistance',40000,'Africa');
SELECT COUNT(*) FROM climate_adaptation WHERE location = 'Asia' AND budget < 30000;
Find all meals containing genetically modified ingredients served in our California restaurants.
CREATE TABLE Meals (MealID INT,MealName VARCHAR(50),ContainsGMO BOOLEAN); INSERT INTO Meals VALUES (1,'Meal1',true); INSERT INTO Meals VALUES (2,'Meal2',false); CREATE TABLE Restaurants (RestaurantID INT,MealID INT,City VARCHAR(20)); INSERT INTO Restaurants VALUES (1,1); INSERT INTO Restaurants VALUES (2,2);
SELECT Meals.MealName FROM Meals INNER JOIN Restaurants ON Meals.MealID = Restaurants.MealID WHERE Restaurants.City = 'California' AND Meals.ContainsGMO = true;
How many green building projects have been implemented in each country?
CREATE TABLE green_buildings (id INT,name VARCHAR(50),country VARCHAR(50),energy_consumption INT); INSERT INTO green_buildings (id,name,country,energy_consumption) VALUES (1,'GreenHub','USA',1200),(2,'EcoTower','Canada',1500),(3,'SolarVista','Mexico',1800),(4,'WindHaven','USA',1000),(5,'SolarCity','China',1600),(6,'EcoRail','Japan',2000);
SELECT country, COUNT(*) FROM green_buildings GROUP BY country;
What is the rank of each union by total safety score, partitioned by region?
CREATE TABLE unions (id INT,name TEXT,location TEXT); INSERT INTO unions (id,name,location) VALUES (1,'Union X','USA'),(2,'Union Y','Canada'),(3,'Union Z','Mexico'); CREATE TABLE regions (id INT,region TEXT); INSERT INTO regions (id,region) VALUES (1,'North'),(2,'South'),(3,'Central'); CREATE TABLE safety_scores (id INT,union_id INT,region_id INT,score INT); INSERT INTO safety_scores (id,union_id,region_id,score) VALUES (1,1,1,85),(2,1,2,90),(3,2,1,70),(4,2,3,80),(5,3,2,85);
SELECT u.name, RANK() OVER (PARTITION BY r.region ORDER BY SUM(s.score) DESC) as rank FROM safety_scores s JOIN unions u ON s.union_id = u.id JOIN regions r ON s.region_id = r.id GROUP BY u.name, r.region;