instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total revenue generated by each country?
CREATE TABLE Countries (id INT,name VARCHAR(50)); INSERT INTO Countries (id,name) VALUES (1,'USA'),(2,'Italy'),(3,'Japan'); CREATE TABLE Transactions (id INT,country_id INT,revenue INT); INSERT INTO Transactions (id,country_id,revenue) VALUES (1,1,500),(2,2,700),(3,1,800),(4,3,600);
SELECT c.name, SUM(t.revenue) as total_revenue FROM Transactions t JOIN Countries c ON t.country_id = c.id GROUP BY c.name;
Delete the soccer team from the teams table
CREATE TABLE teams (team_id INT,team VARCHAR(50)); INSERT INTO teams (team_id,team) VALUES (1,'Basketball'),(2,'Soccer');
DELETE FROM teams WHERE team = 'Soccer';
What is the total carbon sequestration of 'Oak' species in Asia?
CREATE TABLE regions (id INT PRIMARY KEY,name VARCHAR(255)); INSERT INTO regions (id,name) VALUES (1,'Europe'); INSERT INTO regions (id,name) VALUES (2,'North America'); INSERT INTO regions (id,name) VALUES (3,'Asia'); CREATE TABLE species (id INT PRIMARY KEY,name VARCHAR(255)); INSERT INTO species (id,name) VALUES (1,'Spruce'); INSERT INTO species (id,name) VALUES (2,'Pine'); INSERT INTO species (id,name) VALUES (3,'Oak'); CREATE TABLE carbon_sequestration (region_id INT,species_id INT,sequestration INT); INSERT INTO carbon_sequestration (region_id,species_id,sequestration) VALUES (3,3,12000000);
SELECT SUM(carbon_sequestration.sequestration) FROM carbon_sequestration INNER JOIN regions ON carbon_sequestration.region_id = regions.id INNER JOIN species ON carbon_sequestration.species_id = species.id WHERE species.name = 'Oak' AND regions.name = 'Asia';
Delete records of patients who are over 65 and have not visited a rural clinic in California in the past year.
CREATE TABLE patient_visits (patient_id INT,clinic_id INT,last_visit_date DATE); INSERT INTO patient_visits (patient_id,clinic_id,last_visit_date) VALUES (1,4,'2022-01-01'),(2,5,'2021-12-25'),(3,6,'2022-02-03'),(4,4,'2021-05-10');
DELETE FROM patient_visits WHERE patient_id IN (SELECT patient_id FROM patient_visits p JOIN (SELECT patient_id, MAX(last_visit_date) AS max_date FROM patient_visits WHERE clinic_id IN (SELECT clinic_id FROM rural_clinics WHERE state = 'California') GROUP BY patient_id) t ON p.patient_id = t.patient_id AND p.last_visit_date < t.max_date - INTERVAL '1 year') AND age > 65;
What is the nutritional information for all organic products?
CREATE TABLE Nutrition_Facts (Product_ID INT,Calories INT,Sodium_Milligrams INT,Sugar_Grams INT); CREATE TABLE Organic_Certified_Products (Product_ID INT,Organic_Certified INT); CREATE VIEW Organic_Products_Nutrition AS SELECT Nutrition_Facts.*,Organic_Certified_Products.Organic_Certified FROM Nutrition_Facts INNER JOIN Organic_Certified_Products ON Nutrition_Facts.Product_ID = Organic_Certified_Products.Product_ID WHERE Organic_Certified_Products.Organic_Certified = 1;
SELECT * FROM Organic_Products_Nutrition;
What is the average monthly income for clients who have received Shariah-compliant loans?
CREATE TABLE shariah_loans (id INT,client_id INT,amount DECIMAL,date DATE); INSERT INTO shariah_loans (id,client_id,amount,date) VALUES (1,101,5000,'2021-01-05'); CREATE TABLE client_info (id INT,name VARCHAR,monthly_income DECIMAL); INSERT INTO client_info (id,name,monthly_income) VALUES (101,'Ahmed',3000);
SELECT AVG(monthly_income) FROM client_info JOIN shariah_loans ON client_info.id = shariah_loans.client_id;
What is the maximum number of ethical AI certifications obtained by companies in the healthcare sector?
CREATE TABLE Companies (id INT,name TEXT,sector TEXT,num_ethical_ai_certifications INT); INSERT INTO Companies (id,name,sector,num_ethical_ai_certifications) VALUES (1,'HealthTech','healthcare',5),(2,'AIforGood','non-profit',3),(3,'GreenAI','environment',4),(4,'Tech4Health','healthcare',6),(5,'SmartCities','government',2),(6,'AIforAccessibility','non-profit',7);
SELECT MAX(num_ethical_ai_certifications) FROM Companies WHERE sector = 'healthcare';
Add a new solar farm to the "renewable_energy" table
CREATE TABLE renewable_energy (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),capacity FLOAT,type VARCHAR(255));
INSERT INTO renewable_energy (id, name, location, capacity, type) VALUES (1, 'SolarFarm 1', 'New York', 50.0, 'Solar');
Insert a new diversity metric for the startup with id 2 in the 'diversity' table
diversity(id,startup_id,gender_diversity,ethnic_diversity)
INSERT INTO diversity (id, startup_id, gender_diversity, ethnic_diversity) VALUES (3, 2, 0.7, 0.3);
What are the top 3 cruelty-free cosmetic brands most preferred by consumers in the USA, sorted by the number of preferences?
CREATE TABLE Brands (Brand_ID INT,Brand_Name TEXT,Is_Cruelty_Free BOOLEAN); INSERT INTO Brands (Brand_ID,Brand_Name,Is_Cruelty_Free) VALUES (1,'Lush',true),(2,'The Body Shop',true),(3,'Estée Lauder',false); CREATE TABLE Consumer_Preferences (Preference_ID INT,Consumer_ID INT,Brand_ID INT); INSERT INTO Consumer_Preferences (Preference_ID,Consumer_ID,Brand_ID) VALUES (1,1001,1),(2,1001,2),(3,1002,2),(4,1003,3),(5,1004,1),(6,1005,2);
SELECT B.Brand_Name, COUNT(CP.Brand_ID) AS Preferences_Count FROM Brands B INNER JOIN Consumer_Preferences CP ON B.Brand_ID = CP.Brand_ID WHERE B.Is_Cruelty_Free = true GROUP BY B.Brand_Name ORDER BY Preferences_Count DESC LIMIT 3;
What is the average CO2 emissions reduction achieved by carbon offset initiatives in Africa in the last 5 years?
CREATE TABLE africa_offset (id INT,country VARCHAR(20),co2_reduction FLOAT,year INT); INSERT INTO africa_offset (id,country,co2_reduction,year) VALUES (1,'Kenya',1200000,2018),(2,'Nigeria',1500000,2019),(3,'South Africa',800000,2020);
SELECT AVG(co2_reduction) FROM africa_offset WHERE year BETWEEN 2016 AND 2021;
What is the total cargo weight for each accident type?
CREATE TABLE accident_cargo (id INT,accident_type VARCHAR(50),trip_id INT,cargo_weight INT); INSERT INTO accident_cargo VALUES (1,'Collision',1,500),(2,'Collision',2,700),(3,'Grounding',1,600),(4,'Fire',3,800);
SELECT accident_type, SUM(cargo_weight) FROM accident_cargo GROUP BY accident_type;
What is the total construction spending in each region?
CREATE TABLE construction_spending (spending_id INT,region VARCHAR(20),amount DECIMAL(10,2)); INSERT INTO construction_spending (spending_id,region,amount) VALUES (1,'Northeast',50000),(2,'Southeast',60000),(3,'Midwest',45000);
SELECT region, SUM(amount) as total_spending FROM construction_spending GROUP BY region;
Delete records of players who haven't participated in esports events in the past year.
CREATE TABLE Players (PlayerID INT PRIMARY KEY,PlayerName VARCHAR(100),LastEventDate DATE); INSERT INTO Players VALUES (1,'Bob','2021-06-01');
DELETE FROM Players WHERE LastEventDate < DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
What is the daily recycling rate for the region of Andalusia?
CREATE TABLE region_recycling (region VARCHAR(255),recycling_rate DECIMAL(5,2),total_waste INT,day INT); INSERT INTO region_recycling (region,recycling_rate,total_waste,day) VALUES ('Andalusia',0.35,150000,5);
SELECT recycling_rate FROM region_recycling WHERE region='Andalusia' AND day=5;
List the names of all aquaculture sites in Vietnam where the salinity level is between 25 and 32 ppt?
CREATE TABLE vietnam_aquaculture_sites (site_id INT,site_name TEXT,salinity FLOAT,country TEXT); INSERT INTO vietnam_aquaculture_sites (site_id,site_name,salinity,country) VALUES (1,'Site L',28.5,'Vietnam'),(2,'Site M',30.2,'Vietnam'),(3,'Site N',22.8,'Vietnam');
SELECT site_name FROM vietnam_aquaculture_sites WHERE salinity BETWEEN 25 AND 32;
How many songs were created by each artist and the total sales for those songs?
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(50)); CREATE TABLE Songs (SongID INT,ArtistID INT,SongName VARCHAR(50),Sales INT);
SELECT A.ArtistName, COUNT(DISTINCT S.SongID) as SongCount, SUM(S.Sales) as TotalSales FROM Songs S JOIN Artists A ON S.ArtistID = A.ArtistID GROUP BY A.ArtistName;
Insert records into Health Equity Metrics table
CREATE TABLE HealthEquityMetrics (ID INT PRIMARY KEY,MetricName VARCHAR(100),Score INT);
INSERT INTO HealthEquityMetrics (ID, MetricName, Score) VALUES (1, 'Accessibility', 80), (2, 'QualityOfCare', 90), (3, 'LanguageServices', 85);
How many electric buses were in service in Mumbai in 2021?
CREATE TABLE electric_buses (bus_id INT,service_date DATE,in_service INT); INSERT INTO electric_buses (bus_id,service_date,in_service) VALUES (1,'2021-01-01',1),(2,'2021-01-02',1),(3,'2021-01-03',0);
SELECT COUNT(*) FROM electric_buses WHERE in_service = 1 AND service_date BETWEEN '2021-01-01' AND '2021-12-31';
Identify the top three countries with the highest number of marine protected areas?
CREATE TABLE marine_protected_areas (country VARCHAR(255),area_count INT); INSERT INTO marine_protected_areas (country,area_count) VALUES ('USA',100),('Canada',150),('Mexico',50),('Indonesia',200),('Australia',250),('China',300);
SELECT country, area_count, RANK() OVER(ORDER BY area_count DESC) as rank FROM marine_protected_areas;
Delete all records of expeditions that reached a depth greater than 6000 meters?
CREATE TABLE Expeditions(ExpeditionID INT,LeaderName VARCHAR(20),MaxDepth INT); INSERT INTO Expeditions(ExpeditionID,LeaderName,MaxDepth) VALUES (1,'Alice',6500),(2,'Bob',4200),(3,'Charlie',2100),(4,'Dana',5100),(5,'Eve',7000);
DELETE FROM Expeditions WHERE MaxDepth > 6000;
Find the top 3 largest properties by state.
CREATE TABLE properties (id INT,state VARCHAR(255),size INT); INSERT INTO properties (id,state,size) VALUES (1,'NY',3000),(2,'NY',4000),(3,'CA',5000),(4,'CA',6000),(5,'TX',7000),(6,'TX',8000);
SELECT state, size FROM (SELECT state, size, ROW_NUMBER() OVER (PARTITION BY state ORDER BY size DESC) as rank FROM properties) t WHERE rank <= 3;
Insert a new record into the "ai_ethics" table with the values 'BlueAI', 'India', '2022-07-01', 8
CREATE TABLE ai_ethics (tool_name VARCHAR(255),country VARCHAR(255),date DATE,impact_score INT);
INSERT INTO ai_ethics (tool_name, country, date, impact_score) VALUES ('BlueAI', 'India', '2022-07-01', 8);
Update 'safety_rating' to '3' for all records in 'safety_records' table where 'record_date' is in '2019'
CREATE TABLE safety_records (record_id INT PRIMARY KEY,record_date DATE,safety_rating INT);
UPDATE safety_records SET safety_rating = '3' WHERE record_date BETWEEN '2019-01-01' AND '2019-12-31';
Find the total number of members from each country, excluding Canada and Mexico.
CREATE TABLE members (id INT,name VARCHAR(50),country VARCHAR(50),joined DATE); INSERT INTO members (id,name,country,joined) VALUES (1,'John Doe','USA','2020-01-01'); INSERT INTO members (id,name,country,joined) VALUES (2,'Jane Smith','Canada','2019-06-15'); INSERT INTO members (id,name,country,joined) VALUES (3,'Pedro Alvarez','Mexico','2021-02-20');
SELECT country, COUNT(*) as total_members FROM members WHERE country NOT IN ('Canada', 'Mexico') GROUP BY country;
What is the average cost of military equipment by type, for equipment costing more than $5,000,000?
CREATE TABLE MilitaryEquipment (id INT,equipment_type VARCHAR(255),cost FLOAT); INSERT INTO MilitaryEquipment (id,equipment_type,cost) VALUES (1,'Aircraft Carrier',12000000),(2,'Destroyer',5000000),(3,'Stealth Bomber',8000000);
SELECT equipment_type, AVG(cost) FROM MilitaryEquipment WHERE cost > 5000000 GROUP BY equipment_type;
What are the average speeds of vessels in the 'Container Ship' category in the last month?
CREATE TABLE vessels (id INT,name TEXT,type TEXT);CREATE TABLE trips (id INT,vessel_id INT,departure_date DATE,arrival_date DATE); INSERT INTO vessels (id,name,type) VALUES (1,'Vessel A','Container Ship'),(2,'Vessel B','Tanker'); INSERT INTO trips (id,vessel_id,departure_date,arrival_date) VALUES (1,1,'2021-05-01','2021-05-10'),(2,1,'2021-06-01','2021-06-05');
SELECT vessels.type, AVG(DATEDIFF('day', departure_date, arrival_date) * 1.0 / (DATEDIFF('day', departure_date, arrival_date) + 1)) FROM trips JOIN vessels ON trips.vessel_id = vessels.id WHERE vessels.type = 'Container Ship' AND departure_date >= DATEADD('month', -1, CURRENT_DATE) GROUP BY vessels.type;
Find the total quantity of recycled materials used in production.
CREATE TABLE production (production_id INT,recycled_materials INT); INSERT INTO production (production_id,recycled_materials) VALUES (1,250),(2,750);
SELECT SUM(recycled_materials) FROM production;
Which financial institutions have not issued any Shariah-compliant loans in the last year?
CREATE TABLE financial_institutions (institution_id INT,institution_name TEXT); CREATE TABLE shariah_compliant_loans (loan_id INT,institution_id INT,issue_date DATE,amount INT); INSERT INTO financial_institutions VALUES (1,'Islamic Bank'); INSERT INTO financial_institutions VALUES (2,'Community Credit Union'); INSERT INTO shariah_compliant_loans VALUES (1,1,'2021-02-15',10000); INSERT INTO shariah_compliant_loans VALUES (2,1,'2021-06-10',12000);
SELECT institution_name FROM financial_institutions WHERE institution_id NOT IN (SELECT institution_id FROM shariah_compliant_loans WHERE issue_date >= DATEADD(year, -1, GETDATE())) AND institution_name != 'N/A';
Insert records for new clients from the Shariah-compliant finance database
CREATE TABLE shariah_client (client_id INT PRIMARY KEY,name VARCHAR(100),age INT,religion VARCHAR(20));CREATE TABLE shariah_loan (loan_id INT PRIMARY KEY,client_id INT,loan_amount DECIMAL(10,2),loan_date DATE);INSERT INTO shariah_client (client_id,name,age,religion) VALUES (2,'Ali',35,'Islam'),(3,'Farah',45,'Islam');
INSERT INTO client (client_id, name, age, gender) SELECT client_id, name, age, 'Islam' as gender FROM shariah_client WHERE NOT EXISTS (SELECT 1 FROM client c WHERE c.client_id = shariah_client.client_id);
Identify the top 2 soccer teams with the highest number of wins in the 2020-2021 English Premier League.
CREATE TABLE epl_season (team_id INT,team_name VARCHAR(50),games_played INT,wins INT,losses INT); INSERT INTO epl_season (team_id,team_name,games_played,wins,losses) VALUES (1,'Manchester City',38,27,5);
SELECT team_name, wins, RANK() OVER (ORDER BY wins DESC) as rank FROM epl_season WHERE rank <= 2;
What is the total quantity of goods imported by each commodity?
CREATE TABLE Commodity (CommodityID INT,CommodityName VARCHAR(50)); INSERT INTO Commodity (CommodityID,CommodityName) VALUES (1,'Electronics'); INSERT INTO Commodity (CommodityID,CommodityName) VALUES (2,'Textiles'); CREATE TABLE Customs (CustomID INT,VoyageID INT,CommodityID INT,Quantity INT,ImportValue FLOAT); INSERT INTO Customs (CustomID,VoyageID,CommodityID,Quantity,ImportValue) VALUES (1,1,1,100,50000); INSERT INTO Customs (CustomID,VoyageID,CommodityID,Quantity,ImportValue) VALUES (2,2,2,200,80000);
SELECT c.CommodityName, SUM(Quantity) as TotalQuantity FROM Commodity c JOIN Customs cs ON c.CommodityID = cs.CommodityID GROUP BY c.CommodityName;
How many artworks were created by artists from Asia in the 20th century?
CREATE TABLE artworks (id INT,name VARCHAR(255),year INT,artist_name VARCHAR(255),artist_birthplace VARCHAR(255)); INSERT INTO artworks (id,name,year,artist_name,artist_birthplace) VALUES (1,'Painting',1920,'John','Japan'),(2,'Sculpture',1930,'Sara','China'),(3,'Print',1940,'Alex','Korea');
SELECT COUNT(*) FROM artworks WHERE artist_birthplace LIKE 'Asia%' AND year BETWEEN 1900 AND 1999;
How many soil moisture sensors have a temperature below 15 degrees in 'Field007'?
CREATE TABLE soil_moisture_sensors (id INT,field_id VARCHAR(10),sensor_id VARCHAR(10),temperature FLOAT); INSERT INTO soil_moisture_sensors (id,field_id,sensor_id,temperature) VALUES (1,'Field007','SM007',14.1),(2,'Field007','SM008',16.9);
SELECT COUNT(*) FROM soil_moisture_sensors WHERE field_id = 'Field007' AND temperature < 15;
Find the number of mental health parity violations by state.
CREATE TABLE mental_health_parity (state VARCHAR(2),violations INT); INSERT INTO mental_health_parity (state,violations) VALUES ('CA',25),('NY',18),('TX',30);
SELECT state, SUM(violations) FROM mental_health_parity GROUP BY state;
How many workers are employed in fair trade factories in India?
CREATE TABLE Employment (factory VARCHAR(255),country VARCHAR(255),workers INT); INSERT INTO Employment (factory,country,workers) VALUES ('FairTradeFactoryA','India',300);
SELECT SUM(workers) FROM Employment WHERE factory LIKE '%Fair Trade%' AND country = 'India';
Find the maximum number of albums released in a year?
CREATE TABLE albums (album_id INT,album_name VARCHAR(100),release_year INT,artist_id INT); CREATE TABLE artists (artist_id INT,artist_name VARCHAR(100),country VARCHAR(50)); INSERT INTO albums (album_id,album_name,release_year,artist_id) VALUES (1,'AlbumA',2010,1),(2,'AlbumB',2011,2),(3,'AlbumC',2010,3),(4,'AlbumD',2012,1),(5,'AlbumE',2011,3); INSERT INTO artists (artist_id,artist_name,country) VALUES (1,'Artist1','USA'),(2,'Artist2','Canada'),(3,'Artist3','Mexico');
SELECT MAX(year_cnt) FROM (SELECT release_year, COUNT(*) AS year_cnt FROM albums GROUP BY release_year) AS t;
What is the total number of research grants awarded by funding agency and year?
CREATE TABLE funding_agency (id INT,name TEXT); CREATE TABLE research_grants (id INT,funding_agency_id INT,amount INT,year INT);
SELECT f.name, r.year, SUM(r.amount) FROM funding_agency f JOIN research_grants r ON f.id = r.funding_agency_id GROUP BY f.name, r.year;
Find the total water usage in cubic meters for each city in the 'water_usage' table
CREATE TABLE water_usage (city VARCHAR(50),water_usage FLOAT,meter_type VARCHAR(50));
SELECT city, SUM(water_usage) as total_water_usage FROM water_usage GROUP BY city;
Delete all claims processed by 'Jane Doe'.
CREATE TABLE claim (claim_id INT,processed_by VARCHAR(50)); INSERT INTO claim VALUES (1,'Laura Smith'); INSERT INTO claim VALUES (2,'Jane Doe');
DELETE FROM claim WHERE processed_by = 'Jane Doe';
What is the average trip duration for wildlife enthusiasts from Brazil?
CREATE TABLE wildlife_tourists (id INT,name VARCHAR,country VARCHAR,trip_duration FLOAT); INSERT INTO wildlife_tourists (id,name,country,trip_duration) VALUES (1,'Ana Silva','Brazil',10.3);
SELECT AVG(trip_duration) FROM wildlife_tourists WHERE country = 'Brazil';
Insert a new record into the 'Project_Timeline' table for the 'Sustainable City' project in the 'East' region.
CREATE TABLE Project_Timeline (id INT,region VARCHAR(20),project VARCHAR(30),phase VARCHAR(20),start_date DATE,end_date DATE,labor_cost FLOAT);
INSERT INTO Project_Timeline (id, region, project, phase, start_date, end_date, labor_cost) VALUES (4, 'East', 'Sustainable City', 'Planning', '2022-10-01', '2023-01-31', 100000.00);
Who is the maintenance technician responsible for bus 456?
CREATE TABLE vehicles (vehicle_id INT,type VARCHAR(255),technician_id INT); INSERT INTO vehicles (vehicle_id,type,technician_id) VALUES (456,'Bus',789),(124,'Tram',321); CREATE TABLE technicians (technician_id INT,name VARCHAR(255)); INSERT INTO technicians (technician_id,name) VALUES (789,'Susan Johnson'),(321,'Ali Ahmed');
SELECT technicians.name FROM vehicles INNER JOIN technicians ON vehicles.technician_id = technicians.technician_id WHERE vehicle_id = 456;
Find artists who have never exhibited their works in 'Art Gallery of New York'.
CREATE TABLE ArtGalleryNY (artist_id INT); INSERT INTO ArtGalleryNY (artist_id) VALUES (1),(3); CREATE TABLE ArtistsExhibitions (artist_id INT,gallery_id INT); INSERT INTO ArtistsExhibitions (artist_id,gallery_id) VALUES (1,1),(2,1),(2,2);
SELECT artist_id FROM ArtistsExhibitions WHERE gallery_id != (SELECT gallery_id FROM ArtGalleryNY);
What is the total greenhouse gas emissions reduction due to energy efficiency projects in the EU?
CREATE TABLE greenhouse_gas_emissions (id INT PRIMARY KEY,source_type VARCHAR(50),country VARCHAR(50),year INT,amount DECIMAL(10,2));CREATE TABLE energy_efficiency_projects (id INT PRIMARY KEY,project_type VARCHAR(50),country VARCHAR(50),year INT,energy_savings DECIMAL(10,2));CREATE VIEW v_eu_energy_efficiency_projects AS SELECT eep.project_type,eep.country,SUM(eep.energy_savings) AS total_energy_savings FROM energy_efficiency_projects eep WHERE eep.country LIKE 'EU%' GROUP BY eep.project_type,eep.country;CREATE VIEW v_ghg_emissions_reductions AS SELECT ghe.source_type,ghe.country,SUM(ghe.amount) * -1 AS total_reduction FROM greenhouse_gas_emissions ghe JOIN v_eu_energy_efficiency_projects eep ON ghe.country = eep.country WHERE ghe.source_type = 'Energy' GROUP BY ghe.source_type,ghe.country;
SELECT total_reduction FROM v_ghg_emissions_reductions WHERE source_type = 'Energy';
How many indigenous food systems in the 'agroecology' table are located in the 'Andes' region?
CREATE TABLE agroecology (id INT,name TEXT,location TEXT,type TEXT); INSERT INTO agroecology (id,name,location,type) VALUES (1,'System 1','Andes','Indigenous'); INSERT INTO agroecology (id,name,location,type) VALUES (2,'System 2','Amazon','Agroforestry');
SELECT COUNT(*) FROM agroecology WHERE location = 'Andes' AND type = 'Indigenous';
Create table for sustainable fabric
CREATE TABLE sustainable_fabric (id INT PRIMARY KEY,fabric VARCHAR(25),country_of_origin VARCHAR(20));
CREATE TABLE sustainable_fabric (id INT PRIMARY KEY, fabric VARCHAR(25), country_of_origin VARCHAR(20));
What is the minimum flight duration for a flight with safety incidents?
CREATE TABLE flight_safety (id INT,flight_number VARCHAR(255),duration INT,incidents BOOLEAN);
SELECT MIN(duration) FROM flight_safety WHERE incidents = TRUE;
Insert new healthcare access metric for a specific community type
CREATE TABLE healthcare_access_v3 (id INT,community_type VARCHAR(20),access_score INT);
INSERT INTO healthcare_access_v3 (id, community_type, access_score) VALUES (7, 'Remote', 63);
List all suppliers with ethical labor certifications in Europe.
CREATE TABLE suppliers (supplier_id INT,name VARCHAR(255),country VARCHAR(50),ethical_certification VARCHAR(50)); INSERT INTO suppliers (supplier_id,name,country,ethical_certification) VALUES (1,'Green Supplies','Germany','Fair Trade'),(2,'Eco Goods','France',NULL);
SELECT * FROM suppliers WHERE country = 'Europe' AND ethical_certification IS NOT NULL;
What is the average number of research grants awarded per faculty member in the College of Engineering?
CREATE TABLE department (id INT,name TEXT);CREATE TABLE faculty (id INT,department_id INT);CREATE TABLE research_grant (id INT,faculty_id INT,amount INT);
SELECT AVG(rg.count) FROM (SELECT faculty_id, COUNT(*) AS count FROM research_grant rg GROUP BY faculty_id) rg JOIN faculty f ON rg.faculty_id = f.id JOIN department d ON f.department_id = d.id WHERE d.name = 'College of Engineering';
What are the names and functions of all communication satellites in Geostationary Orbit (GEO)?
CREATE TABLE Satellite (Id INT,Name VARCHAR(100),LaunchDate DATETIME,Country VARCHAR(50),Function VARCHAR(50),OrbitType VARCHAR(50),Altitude INT); INSERT INTO Satellite (Id,Name,LaunchDate,Country,Function,OrbitType,Altitude) VALUES (8,'Intelsat 901','2001-06-09','Luxembourg','Communications','Geostationary Orbit (GEO)',35786);
SELECT Name, Function FROM Satellite WHERE Function = 'Communications' AND OrbitType = 'Geostationary Orbit (GEO)';
What are the articles and videos longer than 10 minutes in the 'media_library'?
CREATE TABLE media_library (id INT,type VARCHAR(10),title VARCHAR(50),length FLOAT,source VARCHAR(50)); INSERT INTO media_library (id,type,title,length,source) VALUES (1,'article','Sample Article 1',5.5,'BBC'); INSERT INTO media_library (id,type,title,length,source) VALUES (2,'video','Sample Video 1',12.3,'CNN');
SELECT * FROM media_library WHERE (type = 'article' OR type = 'video') AND length > 10;
Delete records of astronaut medical conditions in 2019.
CREATE TABLE Medical (id INT,astronaut_id INT,medical_condition VARCHAR,year INT); INSERT INTO Medical (id,astronaut_id,medical_condition,year) VALUES (1,1,'Anemia',2020),(2,2,'Flu',2019);
DELETE FROM Medical WHERE year = 2019;
What is the average salary of developers who work on ethical AI projects?
CREATE TABLE developers (developer_id INT,name VARCHAR(50),salary DECIMAL(10,2),project VARCHAR(50)); INSERT INTO developers (developer_id,name,salary,project) VALUES (1,'Alice',80000,'Ethical AI'); INSERT INTO developers (developer_id,name,salary,project) VALUES (2,'Bob',85000,'Ethical AI'); INSERT INTO developers (developer_id,name,salary,project) VALUES (3,'Charlie',90000,'Accessibility Tech');
SELECT AVG(salary) FROM developers WHERE project = 'Ethical AI';
How many marine species are listed as endangered in the Southern Ocean?
CREATE TABLE marine_species (name VARCHAR(255),status VARCHAR(255),location VARCHAR(255)); INSERT INTO marine_species (name,status,location) VALUES ('Southern Right Whale','Endangered','Southern Ocean'),('Leopard Seal','Endangered','Southern Ocean');
SELECT COUNT(*) FROM marine_species WHERE status = 'Endangered' AND location = 'Southern Ocean';
List projects, their team members, and the number of safety protocols associated with each chemical used in the projects.
CREATE TABLE projects (id INT PRIMARY KEY,name VARCHAR(255),start_date DATE,end_date DATE); CREATE TABLE project_team_members (id INT PRIMARY KEY,project_id INT,employee_id INT,role VARCHAR(255),FOREIGN KEY (project_id) REFERENCES projects(id),FOREIGN KEY (employee_id) REFERENCES employees(id)); CREATE TABLE project_chemicals (id INT PRIMARY KEY,project_id INT,chemical_name VARCHAR(255),FOREIGN KEY (project_id) REFERENCES projects(id),FOREIGN KEY (chemical_name) REFERENCES chemical_inventory(chemical_name)); CREATE TABLE safety_protocols (id INT PRIMARY KEY,chemical_name VARCHAR(255),protocol VARCHAR(255),FOREIGN KEY (chemical_name) REFERENCES chemical_inventory(chemical_name));
SELECT projects.name, employees.name AS team_member, COUNT(safety_protocols.id) AS safety_protocols_count FROM projects INNER JOIN project_team_members ON projects.id = project_team_members.project_id INNER JOIN employees ON project_team_members.employee_id = employees.id INNER JOIN project_chemicals ON projects.id = project_chemicals.project_id INNER JOIN chemical_inventory ON project_chemicals.chemical_name = chemical_inventory.chemical_name INNER JOIN safety_protocols ON chemical_inventory.chemical_name = safety_protocols.chemical_name GROUP BY projects.id, employees.id;
What is the name and type of areas ('rural_areas', 'urban_areas', 'suburban_areas', 'development_areas', 'refugee_camps') where there are at least 5 organizations?
CREATE TABLE rural_areas (id INT,num_orgs INT,type VARCHAR(50));CREATE TABLE urban_areas (id INT,num_orgs INT,type VARCHAR(50));CREATE TABLE suburban_areas (id INT,num_orgs INT,type VARCHAR(50));CREATE TABLE development_areas (id INT,num_orgs INT,type VARCHAR(50));CREATE TABLE refugee_camps (id INT,num_orgs INT,type VARCHAR(50));
SELECT 'rural_areas' AS area, num_orgs FROM rural_areas WHERE num_orgs >= 5 UNION SELECT 'urban_areas' AS area, num_orgs FROM urban_areas WHERE num_orgs >= 5 UNION SELECT 'suburban_areas' AS area, num_orgs FROM suburban_areas WHERE num_orgs >= 5 UNION SELECT 'development_areas' AS area, num_orgs FROM development_areas WHERE num_orgs >= 5 UNION SELECT 'refugee_camps' AS area, num_orgs FROM refugee_camps WHERE num_orgs >= 5;
What is the total R&D expenditure for each drug, including the drug name and its approval date, grouped by the pharmaceutical company that developed it?
CREATE TABLE drugs (drug_id INT,name VARCHAR(255),approval_date DATE,company_id INT);CREATE TABLE rd_expenditures (expenditure_id INT,drug_id INT,amount INT,year INT);CREATE TABLE companies (company_id INT,name VARCHAR(255));
SELECT c.name as company_name, d.name as drug_name, d.approval_date, SUM(re.amount) as total_expenditure FROM drugs d JOIN rd_expenditures re ON d.drug_id = re.drug_id JOIN companies c ON d.company_id = c.company_id GROUP BY c.name, d.name, d.approval_date;
What are the drug names and total revenue for drugs sold in India through direct to consumer channels?
CREATE TABLE market_access_strategies (drug_name VARCHAR(255),market VARCHAR(255),strategy VARCHAR(255)); INSERT INTO market_access_strategies (drug_name,market,strategy) VALUES ('DrugF','India','Direct to Consumer'); CREATE TABLE drug_sales (drug_name VARCHAR(255),qty INT,revenue FLOAT,sale_date DATE,market VARCHAR(255)); INSERT INTO drug_sales (drug_name,qty,revenue,sale_date,market) VALUES ('DrugF',150,25000.00,'2020-01-01','India');
SELECT s.drug_name, SUM(s.revenue) as total_revenue FROM drug_sales s JOIN market_access_strategies m ON s.drug_name = m.drug_name WHERE s.market = 'India' AND m.strategy = 'Direct to Consumer' GROUP BY s.drug_name;
How many intangible cultural heritage elements are associated with each country, ordered by the number of elements in descending order?
CREATE TABLE intangible_cultural_heritage (id INT,element VARCHAR(50),country VARCHAR(50)); INSERT INTO intangible_cultural_heritage (id,element,country) VALUES (1,'Flamenco','Spain'),(2,'Tango','Argentina'),(3,'Capoeira','Brazil'),(4,'Ulurú','Australia'),(5,'Reggae','Jamaica'),(6,'Fado','Portugal'),(7,'Kathak','India'),(8,'Haka','New Zealand');
SELECT country, COUNT(*) OVER (PARTITION BY country) as total_elements FROM intangible_cultural_heritage ORDER BY total_elements DESC;
What is the maximum production value in 'european_mines'?
CREATE SCHEMA if not exists europe_schema;CREATE TABLE europe_schema.european_mines (id INT,name VARCHAR,production_value DECIMAL);INSERT INTO europe_schema.european_mines (id,name,production_value) VALUES (1,'N mining',1200000.00),(2,'B mining',1800000.00);
SELECT MAX(production_value) FROM europe_schema.european_mines;
What's the average content rating for TV shows produced by studios in the UK?
CREATE TABLE Studios (studio_id INT,studio_name VARCHAR(255),country VARCHAR(255)); INSERT INTO Studios (studio_id,studio_name,country) VALUES (1,'Studio D','UK'),(2,'Studio E','USA'),(3,'Studio F','Canada'); CREATE TABLE TV_Shows (show_id INT,show_name VARCHAR(255),studio_id INT,content_rating DECIMAL(3,2)); INSERT INTO TV_Shows (show_id,show_name,studio_id,content_rating) VALUES (1,'Show P',1,4.5),(2,'Show Q',1,4.7),(3,'Show R',2,5.0),(4,'Show S',3,4.2);
SELECT AVG(t.content_rating) FROM TV_Shows t JOIN Studios s ON t.studio_id = s.studio_id WHERE s.country = 'UK';
Which destinations received the most sustainable tourism awards in 2018 and 2019?
CREATE TABLE destinations (name VARCHAR(50),year INT,awards INT);CREATE TABLE sustainable_tourism_awards (destination_name VARCHAR(50),year INT,category VARCHAR(50));
SELECT name FROM destinations WHERE awards IN (SELECT MAX(awards) FROM destinations WHERE year IN (2018, 2019)) AND year IN (2018, 2019) UNION SELECT destination_name FROM sustainable_tourism_awards WHERE category = 'Sustainable Tourism' AND year IN (2018, 2019) GROUP BY destination_name HAVING COUNT(*) > 1;
What is the minimum price per gram of any cannabis product sold in Seattle?
CREATE TABLE products (id INT,name TEXT,type TEXT,price_per_gram DECIMAL,city TEXT); INSERT INTO products (id,name,type,price_per_gram,city) VALUES (1,'Green Crack','flower',10.0,'Seattle'),(2,'Blue Dream','concentrate',50.0,'Seattle');
SELECT MIN(price_per_gram) FROM products WHERE city = 'Seattle';
What is the total revenue for each restaurant in the last month?
CREATE TABLE sales (id INT,restaurant_id INT,sale_date DATE,revenue INT);
SELECT restaurant_id, SUM(revenue) FROM sales WHERE sale_date >= DATEADD(month, -1, GETDATE()) GROUP BY restaurant_id;
How many returns were there from Germany with a value greater than 1000 Euros?
CREATE TABLE Returns (id INT,return_country VARCHAR(50),return_value FLOAT); INSERT INTO Returns (id,return_country,return_value) VALUES (1,'Germany',1200),(2,'Germany',850),(3,'France',900);
SELECT COUNT(*) FROM Returns WHERE return_country = 'Germany' AND return_value > 1000;
Display veteran employment statistics for the top 3 states with the highest employment
CREATE TABLE veteran_employment_extended (state VARCHAR(255),employed INT,unemployed INT,total_veterans INT,total_population INT); INSERT INTO veteran_employment_extended (state,employed,unemployed,total_veterans,total_population) VALUES ('California',50000,3000,55000,40000000),('Texas',40000,4000,45000,30000000),('New York',30000,5000,35000,20000000);
SELECT state, employed FROM veteran_employment_extended ORDER BY employed DESC LIMIT 3;
Increase the landfill capacity for the city of Toronto by 10% for the year 2022.
CREATE TABLE landfill_capacity (city VARCHAR(255),year INT,capacity INT); INSERT INTO landfill_capacity (city,year,capacity) VALUES ('Toronto',2022,500000);
UPDATE landfill_capacity SET capacity = capacity * 1.10 WHERE city = 'Toronto' AND year = 2022;
What is the difference in pH levels between organic and non-organic aquaculture sites?
CREATE TABLE aquaculture_sites_ph (site_id INT,certification VARCHAR(50),pH FLOAT); INSERT INTO aquaculture_sites_ph VALUES (1,'Organic',8.1),(2,'Non-organic',7.8),(3,'Organic',7.9),(4,'Non-organic',8.0),(5,'Organic',7.6);
SELECT certification, AVG(pH) AS avg_ph FROM aquaculture_sites_ph GROUP BY certification;
What is the minimum balance for clients with investment accounts in the Seattle branch?
CREATE TABLE clients (client_id INT,name TEXT,dob DATE,branch TEXT);CREATE TABLE accounts (account_id INT,client_id INT,account_type TEXT,balance DECIMAL);INSERT INTO clients VALUES (4,'Emily Johnson','1990-02-14','Seattle');INSERT INTO accounts VALUES (104,4,'Investment',8000);
SELECT MIN(accounts.balance) FROM clients INNER JOIN accounts ON clients.client_id = accounts.client_id WHERE accounts.account_type = 'Investment' AND clients.branch = 'Seattle';
What is the total quantity of clothing products manufactured in the USA in 2021?
CREATE TABLE clothing_products (id INT,product_name VARCHAR(50),quantity_manufactured INT,country_of_manufacture VARCHAR(50),manufacture_date DATE); INSERT INTO clothing_products (id,product_name,quantity_manufactured,country_of_manufacture,manufacture_date) VALUES (1,'T-Shirt',1000,'USA','2021-01-01'),(2,'Jeans',800,'USA','2021-05-15');
SELECT SUM(quantity_manufactured) FROM clothing_products WHERE country_of_manufacture = 'USA' AND YEAR(manufacture_date) = 2021;
What is the total cargo weight handled by each port in Spain?
CREATE TABLE ports (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO ports (id,name,country) VALUES (1,'Algeciras','Spain'),(2,'Valencia','Spain'),(3,'Barcelona','Spain'); CREATE TABLE cargo (id INT,port_id INT,weight INT); INSERT INTO cargo (id,port_id,weight) VALUES (1,1,1000),(2,1,2000),(3,2,1500),(4,3,2500);
SELECT p.name, SUM(c.weight) as total_weight FROM ports p JOIN cargo c ON p.id = c.port_id WHERE p.country = 'Spain' GROUP BY p.name;
Delete all records of items shipped to Australia in January 2022 from the shipments table.
CREATE TABLE shipments (id INT,item_name VARCHAR(255),quantity INT,shipping_date DATE,origin_country VARCHAR(50),destination_country VARCHAR(50));
DELETE FROM shipments WHERE destination_country = 'Australia' AND shipping_date BETWEEN '2022-01-01' AND '2022-01-31';
What is the total number of mining accidents in each state in the USA?
CREATE TABLE accidents (id INT,state VARCHAR(50),industry VARCHAR(50),num_accidents INT); INSERT INTO accidents (id,state,industry,num_accidents) VALUES (1,'Texas','oil',50); INSERT INTO accidents (id,state,industry,num_accidents) VALUES (2,'California','gas',30); INSERT INTO accidents (id,state,industry,num_accidents) VALUES (3,'Wyoming','coal',20);
SELECT state, SUM(num_accidents) FROM accidents WHERE industry = 'mining' GROUP BY state;
How many citizen feedback submissions were made for parks and recreation services in Chicago?
CREATE TABLE feedback (submission_id INT,submission_date DATE,service VARCHAR(50),city VARCHAR(50)); INSERT INTO feedback (submission_id,submission_date,service,city) VALUES (1,'2022-02-15','Parks and Recreation','Chicago'),(2,'2022-02-20','Waste Management','Chicago'),(3,'2022-02-25','Parks and Recreation','Chicago');
SELECT COUNT(*) FROM feedback WHERE service = 'Parks and Recreation' AND city = 'Chicago';
How many construction projects have been completed in each state in the South?
CREATE TABLE South_CP (project_id INT,state VARCHAR(20),completion_date DATE); INSERT INTO South_CP VALUES (4001,'FL','2022-02-28'),(4002,'GA','2022-03-31'),(4003,'AL','2022-04-30');
SELECT state, COUNT(project_id) OVER (PARTITION BY state) as num_projects FROM South_CP;
What is the overall success rate of Gadolinium mining operations in Canada?
CREATE TABLE GadoliniumMining(operation_id INT,country VARCHAR(50),success BOOLEAN); INSERT INTO GadoliniumMining(operation_id,country,success) VALUES (1,'Canada',TRUE),(2,'Canada',TRUE),(3,'Canada',FALSE),(4,'Canada',TRUE),(5,'Canada',FALSE),(6,'Canada',TRUE);
SELECT (SUM(success) FILTER (WHERE country = 'Canada'))/COUNT(*) FROM GadoliniumMining;
List all circular economy initiatives in the 'Europe' region from the 'circular_economy_initiatives' table
CREATE TABLE circular_economy_initiatives (id INT,region VARCHAR(50),initiative VARCHAR(100));
SELECT initiative FROM circular_economy_initiatives WHERE region = 'Europe';
What is the minimum transaction amount for clients living in Africa?
CREATE TABLE clients (client_id INT,name TEXT,continent TEXT,transaction_amount DECIMAL); INSERT INTO clients (client_id,name,continent,transaction_amount) VALUES (1,'John Doe','Africa',500.00); INSERT INTO clients (client_id,name,continent,transaction_amount) VALUES (2,'Jane Smith','Europe',350.00); INSERT INTO clients (client_id,name,continent,transaction_amount) VALUES (3,'Mike Johnson','Asia',400.00);
SELECT MIN(transaction_amount) FROM clients WHERE continent = 'Africa';
What is the most common type of threat intelligence in the services sector?
CREATE TABLE threat_intelligence (id INT,sector VARCHAR(20),type VARCHAR(50)); INSERT INTO threat_intelligence (id,sector,type) VALUES (1,'Services','Phishing');
SELECT type, COUNT(*) as count FROM threat_intelligence WHERE sector = 'Services' GROUP BY type ORDER BY count DESC LIMIT 1;
List the top 3 items with the highest inventory value for all items?
CREATE TABLE all_inventory (item_id INT,item_name VARCHAR(255),category VARCHAR(255),is_organic BOOLEAN,quantity INT,unit_price DECIMAL(5,2)); INSERT INTO all_inventory (item_id,item_name,category,is_organic,quantity,unit_price) VALUES (1,'Quinoa','Grains',true,50,3.99),(2,'Chicken','Proteins',false,100,1.99),(3,'Almond Milk','Dairy Alternatives',true,40,2.59),(4,'Rice','Grains',false,75,0.99),(5,'Potatoes','Starchy Vegetables',false,60,0.79),(6,'Tofu','Proteins',true,30,2.99);
SELECT item_name, quantity * unit_price as total_value FROM all_inventory ORDER BY total_value DESC LIMIT 3;
What is the highest and lowest listing price for co-owned properties in the database?
CREATE TABLE prop_listings (id INT,city VARCHAR(20),listing_price DECIMAL(10,2)); INSERT INTO prop_listings (id,city,listing_price) VALUES (1,'New York',1000000.00),(2,'Seattle',700000.00),(3,'Oakland',600000.00),(4,'Berkeley',900000.00);
SELECT MIN(listing_price) AS "Lowest Price", MAX(listing_price) AS "Highest Price" FROM prop_listings;
Create a view to show the total number of employees by department and gender
CREATE TABLE employee_demographics (employee_id INTEGER,department VARCHAR(50),gender VARCHAR(10)); INSERT INTO employee_demographics (employee_id,department,gender) VALUES (1,'Engineering','Male'),(2,'Engineering','Female'),(3,'Marketing','Female'),(4,'Human Resources','Non-binary'),(5,'Human Resources','Male');
CREATE VIEW employee_count_by_dept_gender AS SELECT department, gender, COUNT(*) as total FROM employee_demographics GROUP BY department, gender;
List all the unique types of renewable energy sources used in projects globally.
CREATE TABLE renewable_projects (project_id INT,energy_source VARCHAR(30)); INSERT INTO renewable_projects (project_id,energy_source) VALUES (1,'Solar'),(2,'Wind'),(3,'Hydro'),(4,'Geothermal'),(5,'Biomass');
SELECT DISTINCT energy_source FROM renewable_projects;
Update the price of all organic foundation products in Germany.
CREATE TABLE FoundationSales (sale_id INT,product_name VARCHAR(100),category VARCHAR(50),price DECIMAL(10,2),quantity INT,sale_date DATE,country VARCHAR(50),organic BOOLEAN);
UPDATE FoundationSales SET price = 19.99 WHERE category = 'Foundation' AND country = 'Germany' AND organic = TRUE;
How many appointments does each therapist have, grouped by specialty?
CREATE TABLE therapists (id INT,name VARCHAR(50),specialty VARCHAR(50),years_of_experience INT); INSERT INTO therapists (id,name,specialty,years_of_experience) VALUES (1,'Dr. Sarah Lee','CBT',10); INSERT INTO therapists (id,name,specialty,years_of_experience) VALUES (2,'Dr. Carlos Alvarez','Psychodynamic',15); INSERT INTO therapists (id,name,specialty,years_of_experience) VALUES (3,'Dr. Mei Chen','EMDR',8); CREATE TABLE appointments (patient_id INT,therapist_id INT,appointment_date DATE,appointment_time TIME,appointment_duration INT); INSERT INTO appointments (patient_id,therapist_id,appointment_date,appointment_time,appointment_duration) VALUES (3,1,'2023-02-15','14:00:00',60); INSERT INTO appointments (patient_id,therapist_id,appointment_date,appointment_time,appointment_duration) VALUES (4,2,'2023-03-01','09:30:00',90); INSERT INTO appointments (patient_id,therapist_id,appointment_date,appointment_time,appointment_duration) VALUES (5,3,'2023-01-20','11:00:00',60);
SELECT specialty, COUNT(*) as num_appointments FROM appointments JOIN therapists ON appointments.therapist_id = therapists.id GROUP BY specialty;
Count the total number of water quality tests performed in the province of Alberta, Canada in the last month
CREATE TABLE provinces (id INT,name VARCHAR(255)); INSERT INTO provinces (id,name) VALUES (1,'Alberta'); CREATE TABLE water_quality_tests (id INT,province_id INT,test_date DATE); INSERT INTO water_quality_tests (id,province_id) VALUES (1,1);
SELECT COUNT(*) as total_tests FROM water_quality_tests WHERE water_quality_tests.test_date >= (CURRENT_DATE - INTERVAL '1 month')::date AND water_quality_tests.province_id IN (SELECT id FROM provinces WHERE name = 'Alberta');
What is the average donation amount per donor for Indigenous causes in 2021?
CREATE TABLE Donations (id INT,donor_id INT,cause VARCHAR(255),amount DECIMAL(10,2),donation_date DATE,donor_group VARCHAR(255)); INSERT INTO Donations (id,donor_id,cause,amount,donation_date,donor_group) VALUES (1,1001,'Indigenous Education',5000,'2021-01-05','First Nations'),(2,1002,'Indigenous Health',3000,'2021-03-15','Native American'),(3,1003,'Indigenous Environment',7000,'2021-01-30','Maori');
SELECT donor_group, AVG(amount) as avg_donation FROM Donations WHERE donation_date BETWEEN '2021-01-01' AND '2021-12-31' AND cause LIKE 'Indigenous%' GROUP BY donor_group;
List the defense projects that started in 2019, with their corresponding geopolitical risk assessments, if available.
CREATE TABLE defense_projects (project_id INTEGER,start_date DATE,end_date DATE); CREATE TABLE risk_assessments (project_id INTEGER,assessment_date DATE,risk_level TEXT);
SELECT defense_projects.project_id, defense_projects.start_date, risk_assessments.assessment_date, risk_assessments.risk_level FROM defense_projects LEFT JOIN risk_assessments ON defense_projects.project_id = risk_assessments.project_id WHERE defense_projects.start_date BETWEEN '2019-01-01' AND '2019-12-31';
What was the total amount of funding received from each source, broken down by year?
CREATE TABLE Funding (id INT,funding_source VARCHAR(50),funding_amount DECIMAL(10,2),funding_year INT); INSERT INTO Funding (id,funding_source,funding_amount,funding_year) VALUES (1,'City Grant',5000.00,2021),(2,'Private Donation',7500.00,2021),(3,'Government Grant',2500.00,2020);
SELECT funding_source, funding_year, SUM(funding_amount) as total_funding FROM Funding GROUP BY funding_source, funding_year;
What is the average temperature in April for cities in the 'crop_weather' table?
CREATE TABLE crop_weather (city VARCHAR(50),temperature INT,month INT); INSERT INTO crop_weather (city,temperature,month) VALUES ('CityA',15,4),('CityA',18,4),('CityB',20,4),('CityB',22,4);
SELECT city, AVG(temperature) as avg_temp FROM crop_weather WHERE month = 4 GROUP BY city;
What are the most common types of vulnerabilities detected in the last month, partitioned by software, and ranked by frequency?
CREATE TABLE vulnerabilities (id INT,software VARCHAR(255),type VARCHAR(255),detected_date DATE); INSERT INTO vulnerabilities (id,software,type,detected_date) VALUES (1,'Software A','SQL Injection','2021-09-01'),(2,'Software B','Cross-Site Scripting','2021-09-03'),(3,'Software A','Cross-Site Scripting','2021-09-05');
SELECT software, type, ROW_NUMBER() OVER (PARTITION BY software ORDER BY COUNT(*) DESC) as rank FROM vulnerabilities WHERE detected_date >= DATEADD(month, -1, GETDATE()) GROUP BY software, type;
What is the total number of students who have ever experienced mental health issues in 'OpenSchool' district?
CREATE TABLE Student (StudentID INT,District VARCHAR(20)); CREATE TABLE MentalHealth (StudentID INT,Issue DATE); INSERT INTO Student (StudentID,District) VALUES (1,'OpenSchool'); INSERT INTO Student (StudentID,District) VALUES (2,'ClosedSchool'); INSERT INTO MentalHealth (StudentID,Issue) VALUES (1,'2020-01-01'); CREATE VIEW StudentMentalHealthView AS SELECT * FROM Student s JOIN MentalHealth m ON s.StudentID = m.StudentID;
SELECT COUNT(*) FROM StudentMentalHealthView WHERE District = 'OpenSchool';
What is the average billing amount for cases handled by female attorneys in the 'London' office?
CREATE TABLE attorneys (attorney_id INT,gender VARCHAR(10),office VARCHAR(50)); INSERT INTO attorneys VALUES (1,'female','London'); CREATE TABLE cases (case_id INT,attorney_id INT,billing_amount DECIMAL(10,2));
SELECT AVG(billing_amount) FROM cases INNER JOIN attorneys ON cases.attorney_id = attorneys.attorney_id WHERE attorneys.gender = 'female' AND attorneys.office = 'London';
How many patients were treated for anxiety disorders in Q1 2022?
CREATE TABLE diagnoses (patient_id INT,diagnosis_name VARCHAR(50),diagnosis_date DATE); INSERT INTO diagnoses (patient_id,diagnosis_name,diagnosis_date) VALUES (1,'Anxiety Disorder','2022-01-05'); INSERT INTO diagnoses (patient_id,diagnosis_name,diagnosis_date) VALUES (4,'Anxiety Disorder','2022-03-28'); INSERT INTO diagnoses (patient_id,diagnosis_name,diagnosis_date) VALUES (5,'Anxiety Disorder','2022-03-12');
SELECT COUNT(*) FROM diagnoses WHERE diagnosis_name = 'Anxiety Disorder' AND QUARTER(diagnosis_date) = 1 AND YEAR(diagnosis_date) = 2022;
How many VR games have been designed by players who are older than 30 and have participated in an esports event?
CREATE TABLE vr_games (game_id INT,genre VARCHAR(10),vr BOOLEAN);
SELECT COUNT(*) FROM vr_games INNER JOIN (SELECT player_id FROM players INNER JOIN esports_participants ON players.player_id = esports_participants.player_id WHERE players.age > 30) AS older_players ON vr_games.game_id = older_players.player_id WHERE vr_games.vr = TRUE;
List the names of the top 5 donors who made the largest donations to habitat preservation efforts.
CREATE TABLE donors (donor_name VARCHAR(50),donation_amount DECIMAL(10,2));
SELECT donor_name FROM (SELECT donor_name, RANK() OVER (ORDER BY donation_amount DESC) as rank FROM donors) WHERE rank <= 5;
Find the total number of visits for each community outreach program in 2022.
CREATE TABLE CommunityOutreach (id INT,program VARCHAR(50),year INT,visits INT); INSERT INTO CommunityOutreach (id,program,year,visits) VALUES (1,'Summer Camp',2022,250),(2,'Senior Tour',2022,300),(3,'Education Day',2021,400);
SELECT program, SUM(visits) FROM CommunityOutreach WHERE year = 2022 GROUP BY program
What is the number of students who received each type of accommodation for exams?
CREATE TABLE Exam_Accommodations (Student_ID INT,Student_Name TEXT,Accommodation_Type TEXT); INSERT INTO Exam_Accommodations (Student_ID,Student_Name,Accommodation_Type) VALUES (10,'Fatima Ahmed','Extended Time'),(11,'Daniel Park','Scribe'),(12,'Hannah Johnson','None');
SELECT Accommodation_Type, COUNT(*) FROM Exam_Accommodations GROUP BY Accommodation_Type;