instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the average donation amount from repeat donors in Canada?
CREATE TABLE donations (id INT,donor_name VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE,donor_country VARCHAR(50)); INSERT INTO donations (id,donor_name,donation_amount,donation_date,donor_country) VALUES (1,'John Doe',50.00,'2021-01-05','Canada'),(2,'Jane Smith',100.00,'2021-03-15','Canada'),(3,'Alice Johnson',75.00,'2021-01-20','USA'),(4,'Bob Brown',150.00,'2021-02-01','Canada'),(5,'Alice Johnson',100.00,'2022-01-01','Canada');
SELECT AVG(donation_amount) FROM donations d1 WHERE donor_country = 'Canada' AND id IN (SELECT id FROM donations d2 WHERE d1.donor_name = d2.donor_name GROUP BY donor_name HAVING COUNT(DISTINCT donation_date) > 1);
Who are the top 3 contributors to defense diplomacy in the last decade?
CREATE TABLE diplomacy_contributions (contribution_id INT,country VARCHAR(255),amount INT,year INT); INSERT INTO diplomacy_contributions (contribution_id,country,amount,year) VALUES (1,'United States',5000000,2012),(2,'United Kingdom',3000000,2013),(3,'France',4000000,2014),(4,'Germany',2500000,2015),(5,'Japan',3500000,2016),(6,'Italy',4500000,2017),(7,'Canada',5500000,2018),(8,'Australia',6000000,2019),(9,'Spain',7000000,2020),(10,'South Korea',8000000,2021);
SELECT country, SUM(amount) as total_amount FROM diplomacy_contributions WHERE year BETWEEN (SELECT YEAR(CURRENT_DATE) - 10) AND YEAR(CURRENT_DATE) GROUP BY country ORDER BY total_amount DESC LIMIT 3;
What is the maximum payment amount for claims in Florida?
CREATE TABLE Claims (ClaimID INT,Payment DECIMAL(5,2),State VARCHAR(20)); INSERT INTO Claims VALUES (1,500.00,'California'),(2,1500.00,'Texas'),(3,800.00,'California'),(4,1200.00,'Florida');
SELECT MAX(Payment) FROM Claims WHERE State = 'Florida';
What is the most common type of crime committed in each borough, in the last year?
CREATE TABLE crimes (id INT,date DATE,borough VARCHAR(50),type VARCHAR(50));
SELECT borough, type, COUNT(*) as count FROM crimes WHERE date >= DATEADD(YEAR, -1, GETDATE()) GROUP BY borough, type ORDER BY borough, count DESC;
Find the number of sustainable destinations in each country in Africa and the total number of visitors to those destinations.
CREATE TABLE AfricaDestinations (destination_id INT,name VARCHAR(50),country VARCHAR(50),sustainability_rating INT); INSERT INTO AfricaDestinations (destination_id,name,country,sustainability_rating) VALUES (1,'Eco Lodge','Kenya',5); INSERT INTO AfricaDestinations (destination_id,name,country,sustainability_rating) VALUES (2,'Green Safari','Tanzania',4);
SELECT country, COUNT(*), SUM(visitor_count) FROM AfricaDestinations JOIN VisitorStatistics ON AfricaDestinations.name = VisitorStatistics.destination GROUP BY country;
What is the total funding received by dance events in the United States?
CREATE TABLE Events (EventID INT,EventType TEXT,Country TEXT); INSERT INTO Events (EventID,EventType,Country) VALUES (1,'Dance','USA'),(2,'Theatre','Canada'),(3,'Dance','USA'),(4,'Music','USA'); CREATE TABLE Funding (FundingID INT,EventID INT,Amount DECIMAL); INSERT INTO Funding (FundingID,EventID,Amount) VALUES (1,1,5000.00),(2,1,7500.00),(3,2,2500.00),(4,3,3000.00),(5,4,4500.00);
SELECT SUM(Amount) FROM Funding F JOIN Events E ON F.EventID = E.EventID WHERE E.EventType = 'Dance' AND E.Country = 'USA';
Find total assets of all Shariah-compliant banks for the year 2020
CREATE TABLE shariah_compliant_banks (bank_id INT,bank_name VARCHAR(50),total_assets DECIMAL(18,2));
SELECT SUM(total_assets) FROM shariah_compliant_banks WHERE YEAR(date_column) = 2020;
Present community health worker and cultural competency training data
CREATE TABLE CommunityHealthWorker (WorkerID INT PRIMARY KEY,Name TEXT,Language TEXT,Location TEXT);
SELECT CommunityHealthWorker.Name, CulturalCompetencyTraining.TrainingName, CulturalCompetencyTraining.TrainingDate FROM CommunityHealthWorker FULL OUTER JOIN CulturalCompetencyTraining ON CommunityHealthWorker.WorkerID = CulturalCompetencyTraining.MHW_ID;
What is the employment rate for veterans in the defense industry in California as of 2021?
CREATE TABLE EmploymentStats (state VARCHAR(255),year INT,industry VARCHAR(255),veteran_employment_rate FLOAT); INSERT INTO EmploymentStats (state,year,industry,veteran_employment_rate) VALUES ('California',2021,'Defense',0.15),('New York',2021,'Defense',0.12);
SELECT veteran_employment_rate FROM EmploymentStats WHERE state = 'California' AND year = 2021 AND industry = 'Defense';
What is the total number of animals in protected habitats for each country?
CREATE TABLE Protected_Habitats (id INT,country VARCHAR(50),animal_count INT);
SELECT country, SUM(animal_count) FROM Protected_Habitats GROUP BY country;
Update the conservation status of 'Green Sea Turtle' to 'Endangered' in the 'species' table.
CREATE TABLE species (species_id INT,common_name VARCHAR(50),latin_name VARCHAR(50),conservation_status VARCHAR(50),class VARCHAR(50)); INSERT INTO species (species_id,common_name,latin_name,conservation_status,class) VALUES (1,'Green Sea Turtle','Chelonia mydas','Vulnerable','Reptilia');
UPDATE species SET conservation_status = 'Endangered' WHERE common_name = 'Green Sea Turtle';
What is the maximum number of trips taken by cable cars in Medellin on a single day?
CREATE TABLE public.trips_by_day_cable_car (id SERIAL PRIMARY KEY,transport_type TEXT,city TEXT,trips_on_day INTEGER); INSERT INTO public.trips_by_day_cable_car (transport_type,city,trips_on_day) VALUES ('cable_car','Medellin',15000),('cable_car','Medellin',18000),('cable_car','Medellin',20000);
SELECT MAX(trips_on_day) FROM public.trips_by_day_cable_car WHERE transport_type = 'cable_car' AND city = 'Medellin';
What was the success rate of rural infrastructure projects in Haiti between 2017 and 2020?
CREATE TABLE projects (id INT,country VARCHAR(50),start_date DATE,end_date DATE,success BOOLEAN); INSERT INTO projects (id,country,start_date,end_date,success) VALUES (1,'Haiti','2017-01-01','2018-12-31',true),(2,'Haiti','2018-01-01','2019-12-31',false),(3,'Haiti','2019-01-01','2020-12-31',true),(4,'Haiti','2020-01-01','2021-12-31',false);
SELECT AVG(success) FROM projects WHERE country = 'Haiti' AND YEAR(start_date) BETWEEN 2017 AND 2020;
What was the average price of a menu item in the "Italian" cuisine type?
CREATE TABLE menu_items (menu_item_id INT,name VARCHAR(255),cuisine_type VARCHAR(255),price DECIMAL(10,2),sales INT); INSERT INTO menu_items (menu_item_id,name,cuisine_type,price,sales) VALUES (1,'Spaghetti Bolognese','Italian',15.99,50),(2,'Margherita Pizza','Italian',12.99,30),(3,'Tiramisu','Italian',6.99,40);
SELECT AVG(price) FROM menu_items WHERE cuisine_type = 'Italian';
How many new employees were hired in Q2 of 2021?
CREATE TABLE hiring (id INT,hire_date DATE); INSERT INTO hiring (id,hire_date) VALUES (1,'2021-04-01'),(2,'2021-05-15'),(3,'2021-07-01');
SELECT COUNT(*) FROM hiring WHERE hire_date BETWEEN '2021-04-01' AND '2021-06-30';
What is the obesity rate among children in East Africa in 2020?
CREATE TABLE obesity (country VARCHAR(255),region VARCHAR(255),year INT,rate DECIMAL(5,2)); INSERT INTO obesity (country,region,year,rate) VALUES ('Country C','East Africa',2020,0.05),('Country D','East Africa',2020,0.06);
SELECT AVG(rate) FROM obesity WHERE region = 'East Africa' AND year = 2020;
How many users from South Africa and Kenya interacted with posts about women's rights in the last year?
CREATE TABLE posts (post_id INT,post_country VARCHAR(255),post_topic VARCHAR(255),post_date DATE); CREATE TABLE user_interactions (interaction_id INT,user_id INT,post_id INT,interaction_type VARCHAR(10)); INSERT INTO posts (post_id,post_country,post_topic,post_date) VALUES (1,'South Africa','women''s rights','2022-01-01'),(2,'Kenya','women''s rights','2022-01-05'); INSERT INTO user_interactions (interaction_id,user_id,post_id,interaction_type) VALUES (1,1,1,'like'),(2,2,1,'share'),(3,3,2,'comment');
SELECT SUM(interaction_type = 'like') + SUM(interaction_type = 'share') + SUM(interaction_type = 'comment') AS total_interactions FROM user_interactions WHERE post_id IN (SELECT post_id FROM posts WHERE post_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND CURRENT_DATE AND post_country IN ('South Africa', 'Kenya') AND post_topic = 'women''s rights');
Insert new record into 'mine_sites' table with 'site_id' as '013', 'site_name' as 'Granite Mountain' and 'region' as 'Southwest'
CREATE TABLE mine_sites (site_id INT PRIMARY KEY,site_name VARCHAR(255),region VARCHAR(255));
INSERT INTO mine_sites (site_id, site_name, region) VALUES (13, 'Granite Mountain', 'Southwest');
How many electric vehicles were sold in the 'Northeast' region in the sales_data table for the year 2020?
CREATE TABLE sales_data (id INT,region TEXT,sales_channel TEXT,vehicle_type TEXT,fuel_type TEXT,year INT,quantity_sold INT); INSERT INTO sales_data (id,region,sales_channel,vehicle_type,fuel_type,year,quantity_sold) VALUES (1,'Northeast','Online','Car','Electric',2020,200),(2,'Southeast','Dealership','SUV','Gasoline',2020,300),(3,'Northeast','Online','Car','Electric',2019,150);
SELECT region, fuel_type, SUM(quantity_sold) as total_sold FROM sales_data WHERE region = 'Northeast' AND fuel_type = 'Electric' AND year = 2020 GROUP BY region, fuel_type;
What is the total amount of climate finance provided to Indigenous communities in the Arctic by national governments each year since 2016?
CREATE TABLE ClimateFinance (year INT,region VARCHAR(255),recipient VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO ClimateFinance (year,region,recipient,amount) VALUES (2016,'Arctic','National Governments',50000),(2017,'Arctic','National Governments',55000),(2018,'Arctic','National Governments',60000),(2019,'Arctic','National Governments',65000),(2020,'Arctic','National Governments',70000);
SELECT year, SUM(amount) AS total_climate_finance FROM ClimateFinance WHERE region = 'Arctic' AND recipient = 'National Governments' GROUP BY year;
What is the total number of mobile and broadband customers in the city of Houston?
CREATE TABLE service_locations (id INT,city VARCHAR(50),service VARCHAR(50)); INSERT INTO service_locations (id,city,service) VALUES (1,'Houston','mobile'),(2,'Dallas','broadband'),(3,'Houston','mobile'),(4,'Miami','broadband');
SELECT COUNT(*) FROM service_locations WHERE city = 'Houston';
What is the number of cases opened by each attorney in the San Francisco office?
CREATE TABLE attorneys (attorney_id INT,attorney_name TEXT,office_location TEXT); INSERT INTO attorneys (attorney_id,attorney_name,office_location) VALUES (1,'John Doe','San Francisco'),(2,'Jane Smith','New York'); CREATE TABLE cases (case_id INT,attorney_id INT,open_date DATE); INSERT INTO cases (case_id,attorney_id,open_date) VALUES (1,1,'2021-01-01'),(2,1,'2021-02-01'),(3,2,'2021-03-01'),(4,2,'2021-04-01');
SELECT a.attorney_name, COUNT(*) as cases_opened FROM attorneys a JOIN cases c ON a.attorney_id = c.attorney_id WHERE a.office_location = 'San Francisco' GROUP BY a.attorney_name;
What is the most common age group among healthcare workers in Canada?
CREATE TABLE healthcare_workers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),location VARCHAR(50)); INSERT INTO healthcare_workers (id,name,age,gender,location) VALUES (1,'Emily Chen',27,'Female','Canada'); INSERT INTO healthcare_workers (id,name,age,gender,location) VALUES (2,'Mohammed Ahmed',35,'Male','Canada');
SELECT age, COUNT(*) FROM healthcare_workers WHERE location = 'Canada' GROUP BY age ORDER BY COUNT(*) DESC LIMIT 1;
What is the maximum number of workshops attended by a teacher in 'Summer 2022'?
CREATE TABLE teacher_pd (teacher_id INT,workshop_name VARCHAR(255),date DATE); INSERT INTO teacher_pd (teacher_id,workshop_name,date) VALUES (1,'Open Pedagogy','2022-06-01'); CREATE VIEW summer_2022_pd AS SELECT teacher_id,COUNT(*) as num_workshops FROM teacher_pd WHERE date BETWEEN '2022-06-01' AND '2022-08-31' GROUP BY teacher_id;
SELECT MAX(num_workshops) as max_workshops FROM summer_2022_pd;
What is the average volume of plastic waste in the Indian Ocean over the last 5 years?
CREATE TABLE plastic_waste (year INT,region VARCHAR(255),volume FLOAT);INSERT INTO plastic_waste (year,region,volume) VALUES (2016,'Indian Ocean',12000),(2017,'Indian Ocean',15000),(2018,'Indian Ocean',18000),(2019,'Indian Ocean',20000),(2020,'Indian Ocean',22000);
SELECT AVG(volume) FROM plastic_waste WHERE region = 'Indian Ocean' AND year BETWEEN 2016 AND 2020;
What is the total number of workplace safety violations in the manufacturing sector in 2020?
CREATE TABLE manufacturing (id INT,year INT,violations INT); INSERT INTO manufacturing (id,year,violations) VALUES (1,2018,10),(2,2019,15),(3,2020,20),(4,2021,25);
SELECT SUM(violations) FROM manufacturing WHERE year = 2020 AND sector = 'manufacturing';
How many 'Assault' and 'Robbery' crimes were reported in each district for 2021, from the 'CrimeStats' table?
CREATE TABLE CrimeStats (district VARCHAR(20),crimeType VARCHAR(20),year INT,number INT);
SELECT district, crimeType, SUM(number) FROM CrimeStats WHERE (crimeType IN ('Assault', 'Robbery') AND year = 2021) GROUP BY district, crimeType;
How many autonomous driving research papers were published in 2020?
CREATE TABLE research_papers (year INT,topic VARCHAR(255),count INT); INSERT INTO research_papers (year,topic,count) VALUES (2020,'Autonomous Driving',150),(2020,'Artificial Intelligence',200);
SELECT count FROM research_papers WHERE year = 2020 AND topic = 'Autonomous Driving';
What is the maximum number of sustainable accommodations in each city?
CREATE TABLE accommodation (id INT,name TEXT,city TEXT,sustainable INT); INSERT INTO accommodation (id,name,city,sustainable) VALUES (1,'Green Retreat','Sydney',1); INSERT INTO accommodation (id,name,city,sustainable) VALUES (2,'Eco Lodge','Melbourne',1); INSERT INTO accommodation (id,name,city,sustainable) VALUES (3,'Eco Villa','Brisbane',1);
SELECT city, MAX(sustainable) as max_sustainable FROM accommodation GROUP BY city;
What is the maximum number of public hospitals in the state of "Texas"?
CREATE TABLE hospitals (hospital_id INT,hospital_name TEXT,state TEXT,type TEXT); INSERT INTO hospitals (hospital_id,hospital_name,state,type) VALUES (1,'Texas Medical Center','Texas','Public'),(2,'Methodist Hospital','Texas','Private'),(3,'Memorial Hermann Hospital','Texas','Public');
SELECT MAX(hospital_id) FROM hospitals WHERE state = 'Texas' AND type = 'Public';
What is the count of cases and count of distinct case types for each attorney, based on the 'attorney_id' column in the 'attorneys' table?
CREATE TABLE attorneys (attorney_id INT,attorney_state VARCHAR(255)); CREATE TABLE cases (case_id INT,case_number INT,attorney_id INT,case_type VARCHAR(255));
SELECT a.attorney_id, COUNT(c.case_id) as case_count, COUNT(DISTINCT c.case_type) as case_type_count FROM attorneys a INNER JOIN cases c ON a.attorney_id = c.attorney_id GROUP BY a.attorney_id;
What is the obesity rate by ethnicity in Illinois in 2020?
CREATE TABLE health_survey_2 (id INT,ethnicity TEXT,state TEXT,year INT,obese BOOLEAN); INSERT INTO health_survey_2 (id,ethnicity,state,year,obese) VALUES (1,'Hispanic','Illinois',2020,true);
SELECT ethnicity, AVG(obese::INT) as obesity_rate FROM health_survey_2 WHERE state = 'Illinois' AND year = 2020 GROUP BY ethnicity;
List the genetic research data entries for gene 'ABC123'?
CREATE TABLE genetic_data (id INT,gene TEXT,data TEXT); INSERT INTO genetic_data (id,gene,data) VALUES (1,'ABC123','ATCG...'); INSERT INTO genetic_data (id,gene,data) VALUES (2,'XYZ456','GCAT...');
SELECT * FROM genetic_data WHERE gene = 'ABC123';
How many electric vehicles were sold in the United States in the last quarter?
CREATE TABLE Sales_Data (id INT,make VARCHAR(255),model VARCHAR(255),sale_date DATE,quantity INT); INSERT INTO Sales_Data (id,make,model,sale_date,quantity) VALUES (1,'Tesla','Model 3','2022-01-01',500); INSERT INTO Sales_Data (id,make,model,sale_date,quantity) VALUES (2,'Chevrolet','Bolt','2022-01-15',300);
SELECT SUM(quantity) FROM Sales_Data WHERE sale_date >= DATEADD(quarter, -1, GETDATE());
Create a new table for storing vendor sustainability ratings
CREATE TABLE vendors (vendor_id INT PRIMARY KEY,vendor_name VARCHAR(255));
CREATE TABLE vendor_sustainability (vendor_id INT, rating INT CHECK (rating >= 1 AND rating <= 5), FOREIGN KEY (vendor_id) REFERENCES vendors(vendor_id));
How many international tourists visited Italy in the last 2 years?
CREATE TABLE tourists (tourist_id INT,visited_date DATE,country TEXT); INSERT INTO tourists (tourist_id,visited_date,country) VALUES (1,'2020-01-01','Italy'),(2,'2019-05-05','USA'),(3,'2018-12-31','Italy');
SELECT COUNT(*) FROM tourists WHERE country = 'Italy' AND visited_date >= DATE_SUB(CURDATE(), INTERVAL 2 YEAR);
Calculate the average claim amount for policyholders in each underwriting group.
CREATE TABLE underwriting (id INT,group VARCHAR(10),name VARCHAR(20),claim_amount DECIMAL(10,2)); INSERT INTO underwriting (id,group,name,claim_amount) VALUES (1,'High Risk','John Doe',5000.00),(2,'Low Risk','Jane Smith',2000.00),(3,'High Risk','Mike Johnson',7000.00),(4,'Low Risk','Emma White',3000.00);
SELECT group, AVG(claim_amount) FROM underwriting GROUP BY group;
Count of clinical trials for Cardiovascular diseases in Germany
CREATE TABLE clinical_trials (trial_id INT,disease_area TEXT,trial_status TEXT,country TEXT); INSERT INTO clinical_trials (trial_id,disease_area,trial_status,country) VALUES (1,'Cardiovascular','Completed','Germany'),(2,'Oncology','In Progress','France');
SELECT COUNT(*) FROM clinical_trials WHERE disease_area = 'Cardiovascular' AND country = 'Germany';
How many energy storage projects are in the database?
CREATE TABLE energy_storage (name VARCHAR(255),type VARCHAR(255)); INSERT INTO energy_storage (name,type) VALUES ('Project1','Battery'),('Project2','Pumped Hydro'),('Project3','Flywheel'),('Project4','Compressed Air');
SELECT COUNT(*) FROM energy_storage;
Insert a new record into the 'biosensors' table for a glucose biosensor with a sensitivity of 0.001 mV/decade
CREATE TABLE biosensors (biosensor_id INT PRIMARY KEY,biosensor_name VARCHAR(50),biosensor_sensitivity DECIMAL(5,3));
INSERT INTO biosensors (biosensor_name, biosensor_sensitivity) VALUES ('Glucose Biosensor', 0.001);
How many heritage sites are located in Oceania and have been updated in the last year?
CREATE TABLE Sites (id INT,site VARCHAR(50),continent VARCHAR(50),last_update DATE); INSERT INTO Sites (id,site,continent,last_update) VALUES (1,'Sydney Opera House','Oceania','2022-01-01'),(2,'Uluru','Oceania','2021-08-15'),(3,'Great Barrier Reef','Oceania','2022-03-27');
SELECT COUNT(*) FROM Sites WHERE continent = 'Oceania' AND last_update >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
List the top 5 genres with the highest number of streams in Canada in 2019.
CREATE TABLE streams (song_id INT,country VARCHAR(50),streams INT); CREATE TABLE songs (id INT,title VARCHAR(100),genre VARCHAR(50)); INSERT INTO streams (song_id,country,streams) VALUES (1,'Canada',10000),(1,'Canada',12000),(2,'Canada',15000),(3,'USA',20000); INSERT INTO songs (id,title,genre) VALUES (1,'Song1','Pop'),(2,'Song2','Rock'),(3,'Song3','Jazz');
SELECT genre, SUM(streams) as total_streams FROM streams JOIN songs ON streams.song_id = songs.id WHERE country = 'Canada' GROUP BY genre ORDER BY total_streams DESC LIMIT 5;
Add a new action movie 'The Last Stand' produced by Red Studios with a budget of 20 million dollars.
CREATE TABLE studio (studio_id INT,name VARCHAR(100)); INSERT INTO studio (studio_id,name) VALUES (1,'Red Studios'); CREATE TABLE movie (movie_id INT,title VARCHAR(100),studio_id INT,genre VARCHAR(50),budget INT);
INSERT INTO movie (movie_id, title, studio_id, genre, budget) VALUES (1, 'The Last Stand', 1, 'Action', 20000000);
What is the total installed capacity (in MW) of solar power projects in the 'europe' region, partitioned by country and ordered by capacity in descending order?
CREATE TABLE solar_projects (id INT,country VARCHAR(50),region VARCHAR(50),capacity FLOAT); INSERT INTO solar_projects (id,country,region,capacity) VALUES (1,'Germany','europe',2345.67),(2,'France','europe',1234.56),(3,'Spain','europe',3456.78);
SELECT region, country, SUM(capacity) as total_capacity FROM solar_projects WHERE region = 'europe' GROUP BY country, region ORDER BY total_capacity DESC;
List the job titles and corresponding average salaries for employees in the IT department.
CREATE TABLE Employees (EmployeeID INT,JobTitle VARCHAR(50),Department VARCHAR(50),Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,JobTitle,Department,Salary) VALUES (1,'Software Engineer','IT',80000.00),(2,'Data Analyst','IT',70000.00);
SELECT JobTitle, AVG(Salary) FROM Employees WHERE Department = 'IT' GROUP BY JobTitle;
Identify the total number of mobile and broadband subscribers who have not made any network infrastructure investments in the last 6 months.
CREATE TABLE investments(id INT,subscriber_id INT,investment_date DATE); INSERT INTO investments(id,subscriber_id,investment_date) VALUES (1,1,'2021-01-01'),(2,2,'2021-02-01'),(3,3,'2021-03-01');
SELECT COUNT(DISTINCT subscribers.id) FROM subscribers LEFT JOIN investments ON subscribers.id = investments.subscriber_id WHERE subscribers.service IN ('Mobile', 'Broadband') AND (investments.investment_date IS NULL OR investments.investment_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH));
Cybersecurity incidents by sector from 2019 to 2021
CREATE TABLE cyber_incidents (sector VARCHAR(50),year INT,incidents INT);
SELECT sector, year, SUM(incidents) OVER (PARTITION BY sector ORDER BY year ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM cyber_incidents WHERE year BETWEEN 2019 AND 2021;
What is the average rating of tourist attractions in Canada, and what are their names?
CREATE TABLE TouristAttractions (id INT,country VARCHAR(50),name VARCHAR(100),rating FLOAT); INSERT INTO TouristAttractions (id,country,name,rating) VALUES (1,'Canada','Niagara Falls',4.7),(2,'Canada','Banff National Park',4.8),(3,'Canada','CN Tower',4.5),(4,'Canada','Whistler Mountain',4.6);
SELECT AVG(rating), name FROM TouristAttractions WHERE country = 'Canada' GROUP BY name;
What's the average age of patients diagnosed with depression?
CREATE TABLE patients (patient_id INT,name VARCHAR(50),age INT,gender VARCHAR(10),condition VARCHAR(50)); INSERT INTO patients (patient_id,name,age,gender,condition) VALUES (1,'John Doe',30,'Male','Anxiety Disorder'); INSERT INTO patients (patient_id,name,age,gender,condition) VALUES (3,'Alice Johnson',40,'Female','Depression');
SELECT AVG(age) FROM patients WHERE condition = 'Depression';
How many biosensor technology patents were filed in Q3 2021?
CREATE TABLE biosensor_patents (id INT,filed_date DATE); INSERT INTO biosensor_patents (id,filed_date) VALUES (1,'2021-07-01'),(2,'2021-08-15'),(3,'2021-09-30');
SELECT COUNT(*) FROM biosensor_patents WHERE filed_date >= '2021-07-01' AND filed_date <= '2021-09-30';
Create a view named 'fish_summary'
CREATE VIEW fish_summary AS SELECT species_name,conservation_status FROM fish_species
CREATE VIEW fish_summary AS SELECT species_name, conservation_status FROM fish_species
How many policyholders are there in each city?
CREATE TABLE Policyholders (Policyholder TEXT,City TEXT); INSERT INTO Policyholders (Policyholder,City) VALUES ('John Doe','New York'),('Jane Smith','Los Angeles'),('Alice Johnson','San Francisco'),('Bob Brown','New York');
SELECT City, COUNT(Policyholder) FROM Policyholders GROUP BY City;
What are the names and locations of healthcare workers in the "rural_healthcenters" table?
CREATE TABLE rural_healthcenters (id INT,name TEXT,location TEXT,position TEXT); INSERT INTO rural_healthcenters (id,name,location,position) VALUES (1,'Healthcenter A','Rural Area 1','Doctor'),(2,'Healthcenter B','Rural Area 2','Nurse'),(3,'Healthcenter C','Rural Area 3','Admin');
SELECT name, location FROM rural_healthcenters;
What is the total fare collected by wheelchair-accessible vehicles in the last quarter?
CREATE TABLE Fares (FareID INT,TripID INT,PaymentMethod VARCHAR(50),FareAmount FLOAT,VehicleType VARCHAR(50)); INSERT INTO Fares (FareID,TripID,PaymentMethod,FareAmount,VehicleType) VALUES (1,1,'Credit Card',5.0,'Standard'),(2,1,'Mobile App',0.5,'Wheelchair Accessible'),(3,2,'Debit Card',2.0,'Standard'),(4,3,'Cash',1.5,'Standard'),(5,4,'Mobile App',1.0,'Wheelchair Accessible'),(6,4,'Credit Card',3.0,'Standard'); CREATE TABLE Dates (DateID INT,Date DATE); INSERT INTO Dates (DateID,Date) VALUES (1,'2022-01-01'),(2,'2022-02-01'),(3,'2022-03-01'),(4,'2022-04-01'),(5,'2022-05-01');
SELECT P.VehicleType, SUM(F.FareAmount) AS TotalFare FROM Fares F JOIN Dates D ON F.TripDateTime >= D.Date AND F.TripDateTime < DATEADD(QUARTER, 1, D.Date) WHERE F.VehicleType = 'Wheelchair Accessible' GROUP BY P.VehicleType;
What is the total number of members in unions with a focus on workplace safety?
CREATE TABLE unions (id INT,name VARCHAR(50),focus_area VARCHAR(50)); INSERT INTO unions (id,name,focus_area) VALUES (1,'Union A','workplace safety'),(2,'Union B','labor rights'),(3,'Union C','collective bargaining');
SELECT COUNT(*) FROM unions WHERE focus_area = 'workplace safety';
What are the total waste generation metrics for each city in the region 'West Coast'?
CREATE TABLE cities (city_name VARCHAR(50),region VARCHAR(50)); INSERT INTO cities (city_name,region) VALUES ('San Francisco','West Coast'),('Los Angeles','West Coast'),('Seattle','West Coast'); CREATE TABLE waste_generation (city_name VARCHAR(50),waste_metric INT); INSERT INTO waste_generation (city_name,waste_metric) VALUES ('San Francisco',1200),('Los Angeles',1500),('Seattle',1800);
SELECT wg.city_name, SUM(waste_metric) as total_waste_metric FROM waste_generation wg JOIN cities c ON wg.city_name = c.city_name WHERE c.region = 'West Coast' GROUP BY wg.city_name;
Compare the number of primary care physicians, by location and specialty.
CREATE TABLE physicians (id INT,name VARCHAR,location VARCHAR,specialty VARCHAR);
SELECT p.specialty, p.location, COUNT(p.id) AS num_physicians FROM physicians p GROUP BY p.specialty, p.location;
What is the percentage of attendees for each event who are from underrepresented communities, and what is the total funding received by each event?
CREATE TABLE events (event_id INT,event_name VARCHAR(50),event_date DATE); CREATE TABLE event_attendance (attendee_id INT,event_id INT,community_representation VARCHAR(20)); CREATE TABLE funding_sources (funding_id INT,event_id INT,source_name VARCHAR(50),funding_amount DECIMAL(10,2)); INSERT INTO events (event_id,event_name,event_date) VALUES (1,'Art Exhibit','2022-04-01'),(2,'Dance Performance','2022-05-01'); INSERT INTO event_attendance (attendee_id,event_id,community_representation) VALUES (1,1,'Underrepresented'),(2,1,'Represented'),(3,2,'Underrepresented'); INSERT INTO funding_sources (funding_id,event_id,source_name,funding_amount) VALUES (1,1,'Local Arts Foundation',3000),(2,2,'National Endowment for the Arts',5000);
SELECT e.event_name, AVG(CASE WHEN ea.community_representation = 'Underrepresented' THEN 1.0 ELSE 0.0 END) AS underrepresented_percentage, SUM(fs.funding_amount) AS total_funding FROM events e INNER JOIN event_attendance ea ON e.event_id = ea.event_id INNER JOIN funding_sources fs ON e.event_id = fs.event_id GROUP BY e.event_name;
What is the total installed capacity of wind turbines in the 'renewable_energy' table?
CREATE TABLE renewable_energy (id INT,project_name TEXT,location TEXT,installed_capacity FLOAT); INSERT INTO renewable_energy (id,project_name,location,installed_capacity) VALUES (1,'Wind Farm 1','USA',50.5),(2,'Wind Farm 2','Germany',60.3);
SELECT SUM(installed_capacity) FROM renewable_energy WHERE project_name LIKE '%wind%';
What is the average property size in 'Sustainable Suburb' of the sustainable_urbanism table?
CREATE TABLE sustainable_urbanism (property_id INT,size FLOAT,location VARCHAR(255)); INSERT INTO sustainable_urbanism (property_id,size,location) VALUES (1,1200,'Sustainable Suburb'),(2,1500,'Green Valley');
SELECT AVG(size) FROM sustainable_urbanism WHERE location = 'Sustainable Suburb';
Delete all records of non-eco-friendly dye types and show the updated table.
CREATE TABLE TextileMills (id INT,mill VARCHAR(50),dye_type VARCHAR(50),quantity INT); INSERT INTO TextileMills (id,mill,dye_type,quantity) VALUES (1,'Mill A','Synthetic Dye',2000),(2,'Mill B','Low-Impact Dye',3000),(3,'Mill C','Synthetic Dye',1500),(4,'Mill D','Natural Dye',2500);
WITH cte AS (DELETE FROM TextileMills WHERE dye_type NOT IN ('Natural Dye', 'Low-Impact Dye')) SELECT * FROM TextileMills;
What is the clinic capacity utilization rate by clinic name, ordered within each province?
CREATE TABLE CapacityUtilization (ProvinceName VARCHAR(50),ClinicName VARCHAR(50),Capacity INT,Utilization INT); INSERT INTO CapacityUtilization (ProvinceName,ClinicName,Capacity,Utilization) VALUES ('Ontario','ClinicA',200,80),('Ontario','ClinicB',250,90),('Quebec','ClinicX',150,70),('British Columbia','ClinicY',200,95),('British Columbia','ClinicZ',175,85);
SELECT ProvinceName, ClinicName, Utilization, PERCENT_RANK() OVER (PARTITION BY ProvinceName ORDER BY Utilization DESC) AS PercentRank FROM CapacityUtilization
How many sustainable fashion brands are there?
CREATE TABLE FashionBrands (id INT,name VARCHAR(25),is_sustainable BOOLEAN);
SELECT COUNT(*) FROM FashionBrands WHERE is_sustainable = TRUE;
What are the 'names' of 'machines' in 'factory2'?
CREATE TABLE machines (location VARCHAR(50),machine_name VARCHAR(100)); INSERT INTO machines (location,machine_name) VALUES ('factory1','machine1'),('factory2','machine2'),('factory3','machine3');
SELECT machine_name FROM machines WHERE location = 'factory2';
What is the total fare collected for buses and trams in Melbourne in the last week of February 2022?
CREATE TABLE tram_routes (route_id INT,vehicle_type VARCHAR(10),fare DECIMAL(5,2)); CREATE TABLE public_transport_fares (fare_id INT,route_id INT,fare_amount DECIMAL(5,2),fare_collection_date DATE); INSERT INTO tram_routes VALUES (1,'Tram',3.50),(2,'Tram',4.50); INSERT INTO public_transport_fares VALUES (1,1,3.50,'2022-02-22'),(2,1,3.50,'2022-02-23'),(3,2,4.50,'2022-02-24');
SELECT SUM(f.fare_amount) FROM public_transport_fares f JOIN tram_routes br ON f.route_id = br.route_id WHERE f.fare_collection_date BETWEEN '2022-02-22' AND '2022-02-28' AND br.vehicle_type IN ('Bus', 'Tram');
What is the market share of ride-hailing services in London?
CREATE TABLE ride_hailing (id INT,type VARCHAR(255),city VARCHAR(255),country VARCHAR(255),market_share FLOAT); INSERT INTO ride_hailing VALUES (1,'Uber','London','UK',0.5);
SELECT market_share FROM ride_hailing WHERE type = 'Uber' AND city = 'London';
Identify customers who made transactions in both the East and West coast regions.
CREATE TABLE customers (customer_id INT,name VARCHAR(50)); CREATE TABLE transactions (transaction_id INT,customer_id INT,region VARCHAR(20)); INSERT INTO customers (customer_id,name) VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Jim Brown'); INSERT INTO transactions (transaction_id,customer_id,region) VALUES (1,1,'West Coast'),(2,1,'East Coast'),(3,2,'West Coast'),(4,3,'East Coast');
SELECT c.name FROM customers c JOIN transactions t1 ON c.customer_id = t1.customer_id JOIN transactions t2 ON c.customer_id = t2.customer_id WHERE t1.region = 'East Coast' AND t2.region = 'West Coast' GROUP BY c.name HAVING COUNT(DISTINCT region) = 2;
Determine the average wastewater production in cubic meters for the city of Los Angeles in the month of May 2021
CREATE TABLE wastewater_production (id INT,city VARCHAR(50),production FLOAT,date DATE); INSERT INTO wastewater_production (id,city,production,date) VALUES (1,'Los Angeles',4500,'2021-05-01'); INSERT INTO wastewater_production (id,city,production,date) VALUES (2,'Los Angeles',4800,'2021-05-02');
SELECT AVG(production) FROM wastewater_production WHERE city = 'Los Angeles' AND date >= '2021-05-01' AND date <= '2021-05-31';
How many employees in 'ethical_labor' table are there for each 'position'?
CREATE TABLE ethical_labor (employee_id INT,employee_name VARCHAR(50),position VARCHAR(50),country VARCHAR(50),salary DECIMAL(10,2));
SELECT position, COUNT(*) FROM ethical_labor GROUP BY position;
What is the maximum revenue earned by a restaurant in the 'Italian' cuisine category?
CREATE TABLE restaurants (restaurant_id INT,name VARCHAR(50),cuisine VARCHAR(50),revenue INT); INSERT INTO restaurants VALUES (1,'Asian Fusion','Asian',5000),(2,'Tuscan Bistro','Italian',7000),(3,'Baja Coast','Mexican',4000),(4,'Sushi House','Asian',8000),(5,'Pizzeria Rustica','Italian',6000),(6,'Taqueria El Paso','Mexican',4500),(7,'Mexican Grill','Mexican',5500);
SELECT cuisine, MAX(revenue) FROM restaurants WHERE cuisine = 'Italian';
What is the maximum wave height and corresponding location for each ocean?
CREATE TABLE wave_heights (id INT,ocean VARCHAR(50),location VARCHAR(50),max_wave_height FLOAT); INSERT INTO wave_heights (id,ocean,location,max_wave_height) VALUES (1,'Pacific Ocean','Pacific Ocean off the coast of Chile',60); INSERT INTO wave_heights (id,ocean,location,max_wave_height) VALUES (2,'Atlantic Ocean','North Atlantic Ocean off the coast of Iceland',50);
SELECT ocean, MAX(max_wave_height) AS max_wave_height, location FROM wave_heights GROUP BY ocean;
What is the average trip duration for eco-tourists from Canada and the USA?
CREATE TABLE tourism (id INT,country VARCHAR(50),tourist_type VARCHAR(50),trip_duration FLOAT); INSERT INTO tourism (id,country,tourist_type,trip_duration) VALUES (1,'Canada','ecotourist',12.5),(2,'USA','ecotourist',15.0);
SELECT AVG(trip_duration) FROM tourism WHERE tourist_type = 'ecotourist' AND country IN ('Canada', 'USA');
Find the number of aquaculture farms in each continent, sorted by the number of farms in descending order.
CREATE TABLE Continent (id INT,name VARCHAR(50)); CREATE TABLE Farm (id INT,name VARCHAR(50),country VARCHAR(50),continent_id INT);
SELECT c.name, COUNT(f.id) FROM Farm f JOIN Continent c ON f.continent_id = c.id GROUP BY c.name ORDER BY COUNT(f.id) DESC;
What is the total revenue for each genre in the 'gaming' database?
CREATE TABLE games_genres (game_id INT,genre VARCHAR(50),revenue FLOAT); INSERT INTO games_genres (game_id,genre,revenue) VALUES (1,'Action',5000000),(2,'Adventure',7000000),(3,'Strategy',3000000),(4,'Action',6000000),(5,'Adventure',8000000);
SELECT genre, SUM(revenue) as total_revenue FROM games_genres GROUP BY genre;
What are the names of all spacecraft that were launched before the first manned spaceflight by a non-US agency?
CREATE TABLE Spacecraft (id INT,name VARCHAR(50),manufacturer VARCHAR(50),launch_date DATE); INSERT INTO Spacecraft (id,name,manufacturer,launch_date) VALUES (1,'Vostok 1','Roscosmos','1961-04-12'),(2,'Mercury-Redstone 3','NASA','1961-05-05'),(3,'Sputnik 1','Roscosmos','1957-10-04');
SELECT s.name FROM Spacecraft s WHERE s.launch_date < (SELECT launch_date FROM Spacecraft WHERE name = 'Vostok 1');
Get the bottom 2 military equipment sales regions by value in 2022
CREATE TABLE military_sales_8 (id INT,region VARCHAR,year INT,value FLOAT);
SELECT region, SUM(value) AS total_value FROM military_sales_8 WHERE year = 2022 GROUP BY region ORDER BY total_value ASC LIMIT 2;
What is the average price of concert tickets for each artist in the Pop genre, in the last year?
CREATE TABLE artists (artist_id INT,artist VARCHAR(100),genre VARCHAR(50)); CREATE TABLE concerts (concert_id INT,artist_id INT,date DATE,price DECIMAL(5,2));
SELECT a.artist, AVG(c.price) AS avg_price FROM artists a JOIN concerts c ON a.artist_id = c.artist_id WHERE a.genre = 'Pop' AND c.date >= DATEADD(year, -1, GETDATE()) GROUP BY a.artist;
Which smart cities in India have a smart grid?
CREATE TABLE smart_cities (id INT,city_name VARCHAR(50),country VARCHAR(50),population INT,smart_grid VARCHAR(50)); INSERT INTO smart_cities (id,city_name,country,population,smart_grid) VALUES (1,'Bangalore','India',12204392,'Yes');
SELECT sc.city_name FROM smart_cities sc WHERE sc.country = 'India' AND sc.smart_grid = 'Yes';
Delete all records in the 'carbon_prices' table with a price higher than 50
CREATE TABLE carbon_prices (id INT PRIMARY KEY,year INT,price FLOAT);
DELETE FROM carbon_prices WHERE price > 50;
Find the number of employees from diverse communities in each mine
CREATE TABLE mine (id INT,name TEXT,location TEXT); CREATE TABLE employee (id INT,mine_id INT,name TEXT,diversity_group TEXT); INSERT INTO mine VALUES (1,'Mine A','Country A'); INSERT INTO mine VALUES (2,'Mine B','Country B'); INSERT INTO employee VALUES (1,1,'John','Underrepresented Group 1'); INSERT INTO employee VALUES (2,1,'Maria','Underrepresented Group 2'); INSERT INTO employee VALUES (3,2,'David','Underrepresented Group 1'); INSERT INTO employee VALUES (4,2,'Sophia','Underrepresented Group 2'); INSERT INTO employee VALUES (5,2,'James','Not Underrepresented');
SELECT mine.name, COUNT(employee.id) AS diverse_employees FROM mine INNER JOIN employee ON mine.id = employee.mine_id WHERE employee.diversity_group IS NOT NULL GROUP BY mine.name;
What is the total claim amount for policyholders living in 'CA' and 'TX'?
CREATE TABLE Claims (PolicyholderID INT,ClaimAmount DECIMAL(10,2),State CHAR(2)); INSERT INTO Claims VALUES (1,2000,'CA'); INSERT INTO Claims VALUES (2,1500,'TX'); INSERT INTO Claims VALUES (3,3000,'NY');
SELECT SUM(ClaimAmount) FROM Claims WHERE State IN ('CA', 'TX');
List the top 3 defense contractors by total contract value for the year 2020, in descending order.
CREATE TABLE DefenseContracts (id INT,Contractor VARCHAR(50),Value FLOAT,Year INT); INSERT INTO DefenseContracts (id,Contractor,Value,Year) VALUES (1,'Lockheed Martin',52000000000,2020),(2,'Boeing',41000000000,2020),(3,'Raytheon',28000000000,2020),(4,'Northrop Grumman',27000000000,2020),(5,'General Dynamics',25000000000,2020);
SELECT Contractor, SUM(Value) as Total FROM DefenseContracts WHERE Year = 2020 GROUP BY Contractor ORDER BY Total DESC LIMIT 3;
What are the total funds allocated for language preservation programs in Oceania?
CREATE TABLE LanguagePreservationOceania (id INT,program VARCHAR(255),start_date DATE,end_date DATE,participants INT,budget DECIMAL(10,2),location VARCHAR(255)); INSERT INTO LanguagePreservationOceania (id,program,start_date,end_date,participants,budget,location) VALUES (1,'Pacific Island Languages Course','2022-02-01','2022-04-30',22,20000,'Oceania'),(2,'Indigenous Australian Languages Workshop','2022-05-01','2022-06-30',18,15000,'Oceania');
SELECT SUM(budget) as total_funds FROM LanguagePreservationOceania WHERE location = 'Oceania';
What is the minimum ocean acidity level in the Atlantic Ocean?
CREATE TABLE ocean_ph (location TEXT,ph FLOAT); INSERT INTO ocean_ph (location,ph) VALUES ('Atlantic Ocean',8.1),('Indian Ocean',8.0),('Southern Ocean',8.1),('North Pacific Ocean',8.2);
SELECT MIN(ph) FROM ocean_ph WHERE location = 'Atlantic Ocean';
Update the issue column in the labor_rights_advocacy table to 'Equal Pay' for all records with a union_id of 004
CREATE TABLE labor_rights_advocacy (la_id SERIAL PRIMARY KEY,union_id VARCHAR(5),issue TEXT,action TEXT,date DATE);
UPDATE labor_rights_advocacy SET issue = 'Equal Pay' WHERE union_id = '004';
What is the distribution of company foundings per year and region?
CREATE TABLE companies (id INT,name TEXT,year INT,region TEXT); INSERT INTO companies (id,name,year,region) VALUES (1,'Nu Pte',2017,'APAC'),(2,'Xi Inc',2018,'NA'),(3,'Omicron LLC',2016,'EMEA'),(4,'Pi Ltd',2019,'APAC');
SELECT year, region, COUNT(*) FROM companies GROUP BY year, region;
How many electric vehicles are there in Canada and Germany?
CREATE TABLE canada_vehicles (vehicle_type VARCHAR(20),quantity INT);CREATE TABLE germany_vehicles (vehicle_type VARCHAR(20),quantity INT);
SELECT SUM(canada_vehicles.quantity) AS canada_total, SUM(germany_vehicles.quantity) AS germany_total FROM canada_vehicles CROSS JOIN germany_vehicles;
What is the minimum number of community policing events held in 'Precinct 10' and 'Precinct 11' last year?
CREATE TABLE community_policing (id INT,precinct VARCHAR(20),year INT,events INT);
SELECT MIN(events) FROM community_policing WHERE precinct IN ('Precinct 10', 'Precinct 11') AND year = 2021;
What was the total revenue for each product category in France in 2021?
CREATE TABLE product_revenue (product_category VARCHAR(20),country VARCHAR(20),year INT,revenue INT); INSERT INTO product_revenue (product_category,country,year,revenue) VALUES ('tops','France',2021,1000000),('bottoms','France',2021,1500000),('dresses','France',2021,1200000);
SELECT product_category, SUM(revenue) FROM product_revenue WHERE country = 'France' AND year = 2021 GROUP BY product_category;
What is the name and capacity of the smallest geothermal power plant in the database?
CREATE TABLE geothermal_plants (id INT,name VARCHAR(100),capacity FLOAT,country VARCHAR(50)); INSERT INTO geothermal_plants (id,name,capacity,country) VALUES (1,'Geothermal Plant 1',50.2,'Iceland'),(2,'Geothermal Plant 2',75.1,'Italy');
SELECT name, capacity FROM geothermal_plants ORDER BY capacity ASC LIMIT 1;
List all ports with their corresponding UN/LOCODEs from the 'ports' table.
CREATE TABLE ports (port_id INT,name VARCHAR(50),un_locode VARCHAR(10)); INSERT INTO ports (port_id,name,un_locode) VALUES (1,'Port of Los Angeles','USLAX'),(2,'Port of Long Beach','USLGB'),(3,'Port of New York','USNYC');
SELECT name, un_locode FROM ports;
What is the average funding amount received by Latinx founders in the Fintech sector?
CREATE TABLE InvestmentRounds (id INT,founder_id INT,funding_amount INT); INSERT INTO InvestmentRounds VALUES (1,2,5000000); CREATE TABLE Founders (id INT,name TEXT,ethnicity TEXT,industry TEXT); INSERT INTO Founders VALUES (2,'Diana','Latinx','Fintech');
SELECT AVG(InvestmentRounds.funding_amount) FROM InvestmentRounds JOIN Founders ON InvestmentRounds.founder_id = Founders.id WHERE Founders.ethnicity = 'Latinx' AND Founders.industry = 'Fintech';
Find the total revenue generated from the mobile and broadband services for each region.
CREATE TABLE region_revenue(region VARCHAR(20),revenue DECIMAL(10,2)); INSERT INTO region_revenue(region,revenue) VALUES ('Urban',250),('Rural',180),('Suburban',220);
SELECT subscribers.region, SUM(revenue.amount) FROM subscribers JOIN revenue ON subscribers.id = revenue.subscriber_id WHERE subscribers.service IN ('Mobile', 'Broadband') GROUP BY subscribers.region;
What is the average number of primary care physicians per rural hospital, ordered by state?
CREATE TABLE primary_care_physicians (physician_id INT,physician_name VARCHAR,specialty VARCHAR,hospital_id INT,state VARCHAR); INSERT INTO primary_care_physicians (physician_id,physician_name,specialty,hospital_id,state) VALUES (1,'Dr. Narayan','Family Medicine',1,'New York'); INSERT INTO primary_care_physicians (physician_id,physician_name,specialty,hospital_id,state) VALUES (2,'Dr. Chen','General Practice',2,'Pennsylvania'); CREATE TABLE hospitals (hospital_id INT,hospital_name VARCHAR,rural_county VARCHAR,state VARCHAR); INSERT INTO hospitals (hospital_id,hospital_name,rural_county,state) VALUES (1,'Rural Hospital A','County X','New York'); INSERT INTO hospitals (hospital_id,hospital_name,rural_county,state) VALUES (2,'Rural Hospital B','County Y','Pennsylvania');
SELECT hospitals.state, AVG(primary_care_physicians.physician_id) AS avg_physicians FROM primary_care_physicians JOIN hospitals ON primary_care_physicians.hospital_id = hospitals.hospital_id WHERE primary_care_physicians.specialty IN ('Family Medicine', 'General Practice') GROUP BY hospitals.state ORDER BY hospitals.state;
List the names of all dispensaries that have never sold a strain containing 'OG' in its name.
CREATE TABLE dispensaries (id INT,name TEXT,state TEXT); CREATE TABLE strains (id INT,name TEXT,dispensary_id INT); INSERT INTO dispensaries (id,name,state) VALUES (1,'The Joint','Washington'); INSERT INTO strains (id,name,dispensary_id) VALUES (1,'Blue Dream',1),(2,'OG Kush',1),(3,'Sour Diesel',2);
SELECT d.name FROM dispensaries d WHERE d.id NOT IN (SELECT s.dispensary_id FROM strains s WHERE s.name LIKE '%OG%');
How many volunteers joined in H2 2021 from underrepresented communities?
CREATE TABLE Volunteers (VolunteerID int,VolunteerName varchar(50),VolunteerDate date,Community varchar(50)); INSERT INTO Volunteers (VolunteerID,VolunteerName,VolunteerDate,Community) VALUES (1,'Alice Johnson','2021-07-01','African American'); INSERT INTO Volunteers (VolunteerID,VolunteerName,VolunteerDate,Community) VALUES (2,'Bob Brown','2021-08-10','Asian');
SELECT COUNT(*) FROM Volunteers WHERE VolunteerDate BETWEEN '2021-07-01' AND '2021-12-31' AND Community IN ('African American', 'Hispanic', 'Native American', 'LGBTQ+', 'People with Disabilities');
What is the average transaction value for each contract address in Q1 2022?
CREATE TABLE IF NOT EXISTS transactions (tx_id INT PRIMARY KEY,contract_address VARCHAR(42),tx_time TIMESTAMP,tx_value DECIMAL(18,2));
SELECT contract_address, AVG(tx_value) FROM transactions WHERE tx_time BETWEEN '2022-01-01 00:00:00' AND '2022-03-31 23:59:59' GROUP BY contract_address;
How are the public health policies in India ordered by start date?
CREATE TABLE public_health_policies (id INT,name VARCHAR,state VARCHAR,country VARCHAR,start_date DATE,end_date DATE); INSERT INTO public_health_policies (id,name,state,country,start_date,end_date) VALUES (1,'Vaccination Program','Maharashtra','India','2021-03-01','2021-12-31'); INSERT INTO public_health_policies (id,name,state,country,start_date,end_date) VALUES (2,'Clean Water Initiative','Delhi','India','2021-01-01','2021-11-30');
SELECT public_health_policies.*, ROW_NUMBER() OVER(PARTITION BY public_health_policies.country ORDER BY public_health_policies.start_date DESC) as rank FROM public_health_policies WHERE public_health_policies.country = 'India';
What is the total revenue generated from concert ticket sales in the state of California?
CREATE TABLE concert_sales (id INT,state VARCHAR,revenue DECIMAL);
SELECT SUM(revenue) FROM concert_sales WHERE state = 'California';
Update subscribers' data usage in the Pacific region by 10%.
CREATE TABLE subscriber_data_usage (subscriber_id INT,data_usage FLOAT,region VARCHAR(20)); INSERT INTO subscriber_data_usage (subscriber_id,data_usage,region) VALUES (1,20.5,'Pacific'),(2,30.7,'Pacific'),(3,18.4,'Pacific');
UPDATE subscriber_data_usage SET data_usage = data_usage * 1.1 WHERE region = 'Pacific';