System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )

[User] How many patients have provided both a phone_number and emergency_contact_phone?

[Assistant] SELECT COUNT(*) FROM healthcare.patients WHERE phone_number IS NOT NULL AND emergency_contact_phone IS NOT NULL;

[User] Find pairs of patients who share the same last name. Show the patient IDs, full names, and the shared last name.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.patient_id < p2.patient_id;

[User] Now, only include pairs where they also share the same date of birth.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name, p1.date_of_birth AS shared_date_of_birth FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.date_of_birth = p2.date_of_birth AND p1.patient_id < p2.patient_id;

[User] Could you also restrict the results to only include pairs where at least one patient has a non-null phone number?

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name, p1.date_of_birth AS shared_date_of_birth FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.date_of_birth = p2.date_of_birth AND p1.patient_id < p2.patient_id WHERE p1.phone_number IS NOT NULL OR p2.phone_number IS NOT NULL;

[User] Finally, sort the results by shared last name, then date of birth, ascending.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name AS patient1_first_name, p1.last_name AS patient1_last_name, p2.patient_id AS patient2_id, p2.first_name AS patient2_first_name, p2.last_name AS patient2_last_name, p1.last_name AS shared_last_name, p1.date_of_birth AS shared_date_of_birth FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.last_name = p2.last_name AND p1.date_of_birth = p2.date_of_birth AND p1.patient_id < p2.patient_id WHERE p1.phone_number IS NOT NULL OR p2.phone_number IS NOT NULL ORDER BY shared_last_name ASC, shared_date_of_birth ASC;

[User] List the patient_id, first_name, last_name, and phone_number for all patients whose gender is 'Female', and whose emergency_contact_name is not null. Also, only include patients who have an email address.

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE gender = 'Female' AND emergency_contact_name IS NOT NULL AND email IS NOT NULL;

[User] Can you only include those patients whose phone_number begins with '+1'?

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE gender = 'Female' AND emergency_contact_name IS NOT NULL AND email IS NOT NULL AND phone_number LIKE '+1%';

[User] I got more results than I expected. Can you add a filter to only include patients born after January 1, 1990?

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE gender = 'Female' AND emergency_contact_name IS NOT NULL AND email IS NOT NULL AND phone_number LIKE '+1%' AND date_of_birth > '1990-01-01';

[User] Find pairs of patients where patient A's emergency contact phone matches patient B's phone number, and patient B's emergency contact phone matches patient A's phone number. Include both patient IDs, their full names, patient A's phone, and patient B's phone.

[Assistant] SELECT p1.patient_id AS patient_a_id, p1.first_name AS patient_a_first_name, p1.last_name AS patient_a_last_name, p2.patient_id AS patient_b_id, p2.first_name AS patient_b_first_name, p2.last_name AS patient_b_last_name, p1.phone_number AS patient_a_phone, p2.phone_number AS patient_b_phone FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.emergency_contact_phone = p2.phone_number AND p2.emergency_contact_phone = p1.phone_number AND p1.patient_id != p2.patient_id;

[User] Show all pairs of patients who share the same email domain. Return patient1_id, patient2_id, and the shared domain, but do not pair a patient with themselves.

[Assistant] SELECT p1.patient_id AS patient1_id, p2.patient_id AS patient2_id, SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) AS shared_domain FROM healthcare.patients p1 JOIN healthcare.patients p2 ON SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) = SUBSTRING(p2.email FROM POSITION('@' IN p2.email) + 1) AND p1.patient_id <> p2.patient_id WHERE p1.email IS NOT NULL AND p2.email IS NOT NULL;

[User] Get a list of all patients and all medications they could potentially take. Include patient_id, full name, medication_id, and medication_name.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m;

[User] Only include patients whose email ends with '@gmail.com'.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m
WHERE p.email LIKE '%@gmail.com';

[User] Also include the medication's generic_name in the results.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name, m.generic_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m
WHERE p.email LIKE '%@gmail.com';

[User] Finally, filter the medications to only those manufactured by 'Pfizer'.

[Assistant]
SELECT p.patient_id, p.first_name || ' ' || p.last_name AS full_name, m.medication_id, m.medication_name, m.generic_name
FROM healthcare.patients p
CROSS JOIN healthcare.medications m
WHERE p.email LIKE '%@gmail.com'
  AND m.manufacturer = 'Pfizer';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )

[User] Find all patients who have never received any diagnoses. Show patient ID, first_name, and last_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name
FROM healthcare.patients p
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] Only include those who have had at least one appointment.

[Assistant]
SELECT DISTINCT p.patient_id,
                p.first_name,
                p.last_name
FROM healthcare.patients p
JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] How many patients are there in each gender category?

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender;

[User] Limit this to categories with more than 50 patients.

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender
HAVING COUNT(*) > 50;

[User] I need to get a list of all patients who had an appointment in the last 30 days, including patient ID, first and last name, appointment_time, and any associated diagnosis description.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days';

[User] Exclude any appointments with status 'Cancelled'.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days'
  AND a.status <> 'Cancelled';

[User] Also, sort the results by appointment_time descending.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days'
  AND a.status <> 'Cancelled'
ORDER BY a.appointment_time DESC;

[User] Show me the full names of all patients who have received a diagnosis for 'hypertension', along with the appointment time and the doctor's full name for each related appointment.

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension';

[User] Actually, can you update the query to only include those appointments that are currently marked as 'scheduled'?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';

[User] I got an error: doctor information seems to be incorrect, since doctors shouldn’t be retrieved from the patients table. Can you fix the join so the doctor information comes from the correct table?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.doctors doc ON diag.doctor_id = doc.doctor_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';

[User] Find all patients along with the number of unique diagnoses each has received. Only include patients who have at least two diagnoses.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, COUNT(DISTINCT d.diagnosis_id) AS num_diagnoses
FROM healthcare.patients p
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
GROUP BY p.patient_id, p.first_name, p.last_name
HAVING COUNT(DISTINCT d.diagnosis_id) >= 2;

[User] List all medications whose manufacturer field is not null.

[Assistant]
SELECT medication_id, medication_name, generic_name, manufacturer, ndc_code, description
FROM healthcare.medications
WHERE manufacturer IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )

[User] List the citizen ID, full name, and registration date for all unverified citizens who registered in the year 2022.

[Assistant] SELECT citizen_id, first_name, last_name, registration_date FROM government_services.citizens WHERE is_verified = FALSE AND EXTRACT(YEAR FROM registration_date) = 2022;

[User] Show me the names of all employees along with the names of the agencies they work for, and the number of appointments each employee has scheduled.

[Assistant]
SELECT e.first_name, e.last_name, a.agency_name, COUNT(appt.appointment_id) AS appointment_count
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
LEFT JOIN government_services.appointments appt ON e.employee_id = appt.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name, a.agency_name;

[User] Can you only show employees who have scheduled more than 5 appointments?

[Assistant]
SELECT e.first_name, e.last_name, a.agency_name, COUNT(appt.appointment_id) AS appointment_count
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
LEFT JOIN government_services.appointments appt ON e.employee_id = appt.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name, a.agency_name
HAVING COUNT(appt.appointment_id) > 5;

[User] Show the full name (first and last name) of employees who are assigned to applications with a status of 'Completed'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.employees AS T1 INNER JOIN government_services.applications AS T2 ON T1.employee_id = T2.assigned_employee_id WHERE T2.status = 'Completed';

[User] List the agency names and the total amount received from payments with the status 'Pending'.

[Assistant]
SELECT ag.agency_name, SUM(p.amount) AS total_pending_payments
FROM government_services.payments p
JOIN government_services.services s ON p.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE p.status = 'Pending'
GROUP BY ag.agency_name;

[User] Show the full names and contact emails of all citizens who have made payments for applications assigned to employees with the job title 'Supervisor'.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
WHERE e.job_title = 'Supervisor';

[User] Which citizens have had both applications and appointments for services in the 'Healthcare' category? List their full name, application ID, and appointment ID.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, a.application_id, appt.appointment_id
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
JOIN government_services.services s1 ON a.service_id = s1.service_id
JOIN government_services.appointments appt ON c.citizen_id = appt.citizen_id
JOIN government_services.services s2 ON appt.service_id = s2.service_id
WHERE s1.category = 'Healthcare' AND s2.category = 'Healthcare';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )

[User] Show me all tokens which have a 6-hour price change percentage above 2% and the current price, on the Arbitrum chain.

[Assistant]
SELECT token_symbol, price, price_change_percentage_6h
FROM token_dexpool_info
WHERE chain = 'Arbitrum'
  AND price_change_percentage_6h > 2;

[User] For each chain, which token has the lowest average cost as reported by smart money, and what is its current price and ROI?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Now, I only want to see tokens where the ROI is above 0.5.

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Can you also return the token narrative from the token_basic_info table for each result?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi, tbi.narrative
FROM smart_money_token_performance smtp
JOIN token_basic_info tbi ON smtp.token_symbol = tbi.token_symbol AND smtp.chain = tbi.chain
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi, tbi.narrative;

[User] Show me the top 3 narratives by trend rank, along with their top 3 tokens and 7-day price change percentage.

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d FROM narrative_info n ORDER BY n.trend_rank ASC LIMIT 3;

[User] Can you also include the 24-hour trading volume for these narratives?

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n ORDER BY n.trend_rank ASC LIMIT 3;

[User] Actually, I only want narratives with a 7-day price change percentage above 10%.

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n WHERE n.price_change_percentage_7d > 10 ORDER BY n.trend_rank ASC LIMIT 3;

[User] Now order the results by 24-hour trading volume in descending order.

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n WHERE n.price_change_percentage_7d > 10 ORDER BY n.volume_24h DESC LIMIT 3;

[User] What is the total USD value of tokens held by 'Binance' on the 'BSC' chain according to the latest snapshot?

[Assistant] SELECT SUM(usd_value) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] Also, show the number of distinct token symbols held by Binance on BSC in that same snapshot.

[Assistant] SELECT SUM(usd_value), COUNT(DISTINCT token_symbol) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] For each narrative, what is the average smart money ROI and the total 24-hour trading volume of the narrative?

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative

[User] Only include narratives that have more than 20 tokens and a total 24h trading volume above $1,000,000.

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Also show the average net flow for smart money performance within each of these narratives.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Order the results by average ROI descending and show the top 5.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000 ORDER BY T4.avg_roi DESC LIMIT 5

[User] For each narrative in smart_money_token_inflow, calculate the total usd_value and avg_price from buy transactions (type=1) and include the narrative's token count from narrative_info. Show narrative, chain, total_usd_value, avg_price, and token_num, ordered by total_usd_value descending, limit to 5.

[Assistant]
SELECT i.narrative, i.chain, SUM(i.usd_value) AS total_usd_value, AVG(i.avg_price) AS avg_price, ni.token_num
FROM smart_money_token_inflow AS i
JOIN narrative_info AS ni ON i.narrative = ni.narrative
WHERE i.type = 1
GROUP BY i.narrative, i.chain, ni.token_num
ORDER BY total_usd_value DESC
LIMIT 5;

[User] Please filter results to only include narratives where the total token_amount exceeds 1000.

[Assistant]
SELECT i.narrative, i.chain, SUM(i.usd_value) AS total_usd_value, AVG(i.avg_price) AS avg_price, ni.token_num
FROM smart_money_token_inflow AS i
JOIN narrative_info AS ni ON i.narrative = ni.narrative
WHERE i.type = 1
GROUP BY i.narrative, i.chain, ni.token_num
HAVING SUM(i.token_amount) > 1000
ORDER BY total_usd_value DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] Which locations have received fuel logs greater than 300 liters in total? Please include the location name and city.

[Assistant]
SELECT l.name AS location_name, l.city, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] Can you also include the number of times fuel was logged at each location?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] Actually, could you restrict it to only locations that are in 'New York' city?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
WHERE l.city = 'New York'
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] I got an error about ambiguous column in GROUP BY, can you fix and show only the columns used in SELECT in the GROUP BY?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
WHERE l.city = 'New York'
GROUP BY l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] List every booking together with the route number and description for the trip being booked.

[Assistant]
SELECT b.booking_id, b.passenger_id, b.trip_id, r.route_number, r.description
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id;

[User] Show me the total fuel quantity and cost for each route, grouped by route number, only for trips that have associated fuel logs.

[Assistant]
SELECT r.route_number, SUM(f.quantity) AS total_quantity, SUM(f.total_cost) AS total_cost
FROM transportation.fuel_logs f
JOIN transportation.routes r ON f.trip_id IS NOT NULL AND f.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs
)
JOIN transportation.bookings b ON f.trip_id = b.trip_id
WHERE r.route_id = b.trip_id
GROUP BY r.route_number;

[User] For each city, show how many trips have started there (origin), how many have ended there (destination), and the total number of unique vehicles used in trips that started in that city.

[Assistant]
SELECT l.city,
       COUNT(CASE WHEN t.origin_location_id = l.location_id THEN 1 END) AS trips_started,
       COUNT(CASE WHEN t.destination_location_id = l.location_id THEN 1 END) AS trips_ended,
       COUNT(DISTINCT CASE WHEN t.origin_location_id = l.location_id THEN t.vehicle_id END) AS unique_vehicles_started
FROM transportation.locations l
LEFT JOIN transportation.trips t ON t.origin_location_id = l.location_id OR t.destination_location_id = l.location_id
GROUP BY l.city;

[User] Show all maintenance logs with the vehicle ID, service date, service type, and the name and city of the location where the vehicle's most recent fueling occurred.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id;

[User] I want to see only maintenance logs where the service_type is 'Inspection' and the maintenance cost exceeds 150.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150;

[User] Can you also add the odometer reading from the maintenance log and sort the results by service_date descending?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.odometer_reading, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150
ORDER BY ml.service_date DESC;

[User] Sorry, can you restrict the results to logs from after January 1, 2023?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.odometer_reading, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150 AND ml.service_date > '2023-01-01'
ORDER BY ml.service_date DESC;

[User] For each city that has a fueling location, show the city name and the total quantity of fuel refueled.

[Assistant] SELECT T2.city ,  SUM(T1.quantity) FROM transportation.fuel_logs AS T1 JOIN transportation.locations AS T2 ON T1.location_id  =  T2.location_id GROUP BY T2.city


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] Which token symbol has the highest price among all tokens held by CEXes on the Polygon chain?

[Assistant] SELECT token_symbol, MAX(price) AS max_price FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY max_price DESC LIMIT 1;

[User] Can you also show which exchange holds the largest balance of that token?

[Assistant] SELECT exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 1;

[User] Please include the snapshot_time of the record as well.

[Assistant] SELECT snapshot_time, exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 1;

[User] Instead of only the largest balance, can you list the top 3 addresses by usd_value for that token?

[Assistant] SELECT snapshot_time, exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 3;

[User] For each exchange, compute the percentage change in total USD value of its holdings between snapshots '2023-01-01 00:00:00' and '2023-02-01 00:00:00'. Show exchange, chain, value_jan, value_feb, and pct_change.

[Assistant]
SELECT t1.exchange,
       t1.chain,
       t1.total_usd AS value_jan,
       t2.total_usd AS value_feb,
       ((t2.total_usd - t1.total_usd) / NULLIF(t1.total_usd,0)) * 100 AS pct_change
FROM (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-01-01 00:00:00'
  GROUP BY exchange, chain
) t1
JOIN (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-02-01 00:00:00'
  GROUP BY exchange, chain
) t2
  ON t1.exchange = t2.exchange AND t1.chain = t2.chain;

[User] Please modify the query to compare between '2023-01-01 00:00:00' and the latest available snapshot instead.

[Assistant]
WITH latest AS (
  SELECT MAX(snapshot_time) AS snap FROM cex_token_balance
),
jan AS (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-01-01 00:00:00'
  GROUP BY exchange, chain
),
feb AS (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = (SELECT snap FROM latest)
  GROUP BY exchange, chain
)
SELECT j.exchange,
       j.chain,
       j.total_usd AS value_jan,
       f.total_usd AS value_latest,
       ((f.total_usd - j.total_usd) / NULLIF(j.total_usd,0)) * 100 AS pct_change
FROM jan j
JOIN feb f
  ON j.exchange = f.exchange AND j.chain = f.chain;

[User] List all CEX addresses on the BSC chain that hold more than $1 million USD value in total.

[Assistant] SELECT address, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'BSC' GROUP BY address HAVING SUM(usd_value) > 1000000;

[User] List each blockchain (chain) and the centralized exchange that holds the highest total USD value of tokens, as well as the exchange with the lowest total USD value of tokens. Show chain, max_exchange, max_value, min_exchange, and min_value.

[Assistant]
WITH totals AS (
  SELECT chain, exchange, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  GROUP BY chain, exchange
),
max_totals AS (
  SELECT chain, exchange AS max_exchange, total_usd AS max_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd DESC) AS rn
    FROM totals
  ) t
  WHERE rn = 1
),
min_totals AS (
  SELECT chain, exchange AS min_exchange, total_usd AS min_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd ASC) AS rn
    FROM totals
  ) t
  WHERE rn = 1
)
SELECT m.chain, m.max_exchange, m.max_value, n.min_exchange, n.min_value
FROM max_totals m
JOIN min_totals n USING (chain);

[User] Actually, restrict the analysis to the latest snapshot_time only.

[Assistant]
WITH latest AS (
  SELECT MAX(snapshot_time) AS snap
  FROM cex_token_balance
),
totals AS (
  SELECT chain, exchange, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = (SELECT snap FROM latest)
  GROUP BY chain, exchange
),
max_totals AS (
  SELECT chain, exchange AS max_exchange, total_usd AS max_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd DESC) AS rn
    FROM totals
  ) t WHERE rn = 1
),
min_totals AS (
  SELECT chain, exchange AS min_exchange, total_usd AS min_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd ASC) AS rn
    FROM totals
  ) t WHERE rn = 1
)
SELECT m.chain, m.max_exchange, m.max_value, n.min_exchange, n.min_value
FROM max_totals m
JOIN min_totals n USING (chain);

[User] For the latest snapshot time, list the total `usd_value` held by CEXes for each distinct `token_symbol` across all chains. Order the results by total value descending.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, sum(usd_value) as total_usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
GROUP BY token_symbol
ORDER BY total_usd_value DESC;

[User] Now, filter this list to only include tokens where the total `usd_value` across all CEX holdings is greater than $5,000,000.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, sum(usd_value) as total_usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
GROUP BY token_symbol
HAVING sum(usd_value) > 5000000.0
ORDER BY total_usd_value DESC;

[User] Find all tokens on the 'BSC' chain in the latest snapshot where the individual holding `usd_value` is greater than $1,000,000. Show their symbol, exchange, balance, and USD value.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, exchange, balance, usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
WHERE chain = 'BSC' AND usd_value > 1000000.0;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )

[User] List the top 10 narratives based on their market cap. Display the narrative name, market_cap, and token_num.

[Assistant] SELECT narrative, market_cap, token_num FROM narrative_info ORDER BY market_cap DESC LIMIT 10

[User] List all narratives with a trend rank better than 50, showing the narrative name and their listed 'Top 3 Coins'.

[Assistant] SELECT narrative, top_3_coins FROM narrative_info WHERE trend_rank < 50

[User] Could you also include the 24-hour trading volume for these narratives and only show those where the volume is greater than 10,000,000 USD?

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000

[User] Please order the results by 24-hour trading volume in descending order.

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h DESC

[User] Finally, limit the output to the top 10 and add the total number of tokens for each narrative.

[Assistant] SELECT narrative, top_3_coins, volume_24h, token_num FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h DESC LIMIT 10

[User] Show narratives with a 24-hour trading volume greater than $10,000,000 and a positive 24-hour price change percentage. List the narrative name, volume_24h, and price_change_percentage_24h.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h FROM narrative_info WHERE volume_24h > 10000000 AND price_change_percentage_24h > 0

[User] Refine the results to only include narratives with a trend rank of 20 or better (lower number is better), and order the results by volume_24h in descending order. Also, include the trend_rank in the output.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h, trend_rank FROM narrative_info WHERE volume_24h > 10000000 AND price_change_percentage_24h > 0 AND trend_rank <= 20 ORDER BY volume_24h DESC

[User] The list is too short. Can you adjust the volume filter to be greater than $5,000,000 instead of $10,000,000?

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h, trend_rank FROM narrative_info WHERE volume_24h > 5000000 AND price_change_percentage_24h > 0 AND trend_rank <= 20 ORDER BY volume_24h DESC

[User] Okay, and also add the number of tokens (token_num) for each narrative in the results.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h, trend_rank, token_num FROM narrative_info WHERE volume_24h > 5000000 AND price_change_percentage_24h > 0 AND trend_rank <= 20 ORDER BY volume_24h DESC

[User] List all pairs of narratives where the first narrative has a higher market_cap than the second. Display narrative1, narrative2, cap1, cap2.

[Assistant] SELECT n1.narrative AS narrative1, n2.narrative AS narrative2, n1.market_cap AS cap1, n2.market_cap AS cap2 FROM narrative_info n1 JOIN narrative_info n2 ON n1.market_cap > n2.market_cap;

[User] Filter the result to only include pairs where the difference in market_cap is over 100000000 and order by the difference descending, limit to 10.

[Assistant] SELECT n1.narrative AS narrative1, n2.narrative AS narrative2, n1.market_cap AS cap1, n2.market_cap AS cap2, (n1.market_cap - n2.market_cap) AS diff FROM narrative_info n1 JOIN narrative_info n2 ON n1.market_cap > n2.market_cap WHERE (n1.market_cap - n2.market_cap) > 100000000 ORDER BY diff DESC LIMIT 10;

[User] Show the top 5 narratives by 24h volume, displaying narrative and volume_24h.

[Assistant] SELECT narrative, volume_24h FROM narrative_info ORDER BY volume_24h DESC LIMIT 5;

[User] Find narrative pairs where the sum of their price_change_percentage_1h is greater than 5. Show narrative1, change1, narrative2, change2, and the sum as total_change.

[Assistant] SELECT n1.narrative AS narrative1, n1.price_change_percentage_1h AS change1, n2.narrative AS narrative2, n2.price_change_percentage_1h AS change2, (n1.price_change_percentage_1h + n2.price_change_percentage_1h) AS total_change FROM narrative_info n1 JOIN narrative_info n2 ON n1.narrative <> n2.narrative WHERE (n1.price_change_percentage_1h + n2.price_change_percentage_1h) > 5;

[User] Now only include pairs where both have token_num greater than 10 and order by total_change descending.

[Assistant] SELECT n1.narrative AS narrative1, n1.price_change_percentage_1h AS change1, n2.narrative AS narrative2, n2.price_change_percentage_1h AS change2, (n1.price_change_percentage_1h + n2.price_change_percentage_1h) AS total_change FROM narrative_info n1 JOIN narrative_info n2 ON n1.narrative <> n2.narrative WHERE (n1.price_change_percentage_1h + n2.price_change_percentage_1h) > 5 AND n1.token_num > 10 AND n2.token_num > 10 ORDER BY total_change DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] Count the number of tokens for each contract address.

[Assistant] SELECT contract_address, COUNT(*) AS token_count FROM web3.tokens GROUP BY contract_address;

[User] Only show contracts that have more than 5 tokens.

[Assistant] SELECT contract_address, COUNT(*) AS token_count FROM web3.tokens GROUP BY contract_address HAVING COUNT(*) > 5;

[User] List all users who created a wallet on the same day they registered. Show user ID, username, and the wallet address.

[Assistant] SELECT u.user_id, u.username, w.address FROM web3.users AS u JOIN web3.wallets AS w ON u.user_id = w.user_id WHERE DATE(u.created_at) = DATE(w.created_at);

[User] Find the contract ID, address, and deployer address for all contracts that have not emitted any events.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address FROM web3.contracts AS c LEFT JOIN web3.events AS e ON c.contract_id = e.contract_id WHERE e.event_id IS NULL;

[User] List all users and the total value of all transactions they have initiated. Show user_id, username, and total_transaction_value.

[Assistant]
SELECT u.user_id, u.username, COALESCE(SUM(t.value), 0) AS total_transaction_value
FROM web3.users u
LEFT JOIN web3.wallets w ON u.user_id = w.user_id
LEFT JOIN web3.transactions t ON w.address = t.from_address
GROUP BY u.user_id, u.username;

[User] Actually, only show users who have initiated at least one transaction, and sort them by total_transaction_value descending.

[Assistant]
SELECT u.user_id, u.username, SUM(t.value) AS total_transaction_value
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions t ON w.address = t.from_address
GROUP BY u.user_id, u.username
HAVING SUM(t.value) > 0
ORDER BY total_transaction_value DESC;

[User] Show all contracts and the names of all events they have ever emitted. Include contract_id, contract address, and event_name.

[Assistant]
SELECT c.contract_id, c.address, e.event_name
FROM web3.contracts c
JOIN web3.events e ON c.contract_id = e.contract_id
ORDER BY c.contract_id, e.event_name;

[User] Show all contracts along with the number of events each contract has emitted. Include the contract address and the event count.

[Assistant]
SELECT c.address, COUNT(e.event_id) AS event_count
FROM web3.contracts c
LEFT JOIN web3.events e ON c.contract_id = e.contract_id
GROUP BY c.address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    primary_contact_email character varying(128),
    main_phone_number character varying(32),
    website_url character varying(255),
    established_date date,
    parent_agency_id character varying(64), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] List the agency names and addresses for all service locations in the state of 'Florida'.

[Assistant]
SELECT a.agency_name, l.address
FROM government_services.service_locations l
JOIN government_services.agencies a ON l.agency_id = a.agency_id
WHERE l.state = 'Florida';

[User] Which agencies have at least one service location in a city named 'Austin', and what are their agency names and main phone numbers?

[Assistant]
SELECT DISTINCT a.agency_id, a.agency_name, a.main_phone_number
FROM government_services.agencies a
JOIN government_services.service_locations l ON a.agency_id = l.agency_id
WHERE l.city = 'Austin';

[User] How many documents are set to expire in the year 2025?

[Assistant]
SELECT COUNT(*) AS document_count
FROM government_services.documents
WHERE expiry_date >= '2025-01-01' AND expiry_date < '2026-01-01';

[User] For each application that has pending documents, list the application's reference_number and the corresponding service_name. Only include documents with verification_status = 'Pending'.

[Assistant]
SELECT DISTINCT a.reference_number, s.service_name
FROM government_services.applications a
JOIN government_services.documents d ON a.application_id = d.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE d.verification_status = 'Pending';

[User] Get the name of each agency and the count of accessible service locations it operates in. Only include agencies that have more than two accessible locations.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS accessible_locations
FROM government_services.agencies a
JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.is_accessible = TRUE
GROUP BY a.agency_name
HAVING COUNT(sl.location_id) > 2;

[User] Modify the query so that it counts distinct cities instead of locations.

[Assistant]
SELECT a.agency_name, COUNT(DISTINCT sl.city) AS accessible_cities
FROM government_services.agencies a
JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.is_accessible = TRUE
GROUP BY a.agency_name
HAVING COUNT(DISTINCT sl.city) > 2;

[User] List the reference number and status for all applications that have at least one document associated with them.

[Assistant] SELECT DISTINCT a.reference_number, a.status FROM government_services.applications AS a JOIN government_services.documents AS d ON a.application_id = d.application_id


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.

[User] 特定の職種の従業員情報を取得したいです。従業員ID、名前、職種、雇用日を表示してください。

[Assistant]
db.employees.find(
    { job_title: '<specific_job_title>' },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用日が2020年1月1日以降の従業員だけに絞り込むことはできますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') }
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用ステータスが「Active」の従業員だけをさらに条件に加えられますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] スキル認定情報も結果に含めてください。

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, skill_certifications: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 特定の組み立てラインに関連するすべての手順を取得したいです。ラインIDと手順名、手順番号、必要なスキルレベルを含めてください。

[Assistant]
db.assembly_steps.find(
    { line_id: '<specific_line_id>' },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] さらに、必要なスキルレベルが「Senior Technician」以上の手順だけを表示できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 標準作業時間が3時間以上の手順も条件に追加できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 }
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 最後に、作業場所が「Workstation_B」の手順だけに絞り込んでください。

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 },
        workstation: 'Workstation_B'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 特定の組み立てラインに割り当てられた従業員とそのラインの手順情報を取得したいです。従業員ID、名前、職種と手順名、手順番号を含めてください。

[Assistant]
db.employees.aggregate([
    { $match: { assigned_line_id: '<specific_line_id>' } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 従業員の雇用ステータスが「Active」のデータだけに絞り込むことはできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 手順の必要なスキルレベルが「Junior Technician」以上のものだけを表示するようにできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 最後に、従業員の雇用日も結果に含めて、雇用日順に並べ替えてください。

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        hire_date: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { hire_date: -1, 'steps.step_number': 1 } }
])


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)

[User] For each trip, show the trip ID, vehicle ID, driver ID, and both the actual starting and ending location IDs.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id FROM transportation.trips;

[User] List all unique pairs of origin and destination location IDs that have been used in trips, and count how many trips have occurred for each pair.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY origin_location_id, destination_location_id;

[User] Find pairs of trip IDs where both trips departed on the same calendar day, shared the same origin and destination locations, but were distinct trips.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id;

[User] From those pairs, filter the results to only include pairs where the actual departure times were within 2 hours of each other.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date,
  t1.actual_departure AS actual_departure_1,
  t2.actual_departure AS actual_departure_2
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id
WHERE
  t1.actual_departure IS NOT NULL
  AND t2.actual_departure IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (t1.actual_departure - t2.actual_departure))) <= 7200;

[User] Show me the trip details including actual and scheduled times, and the difference between them for all trips associated with a specific driver, say driver_id 'DRV789'.

[Assistant]
SELECT
  trip_id,
  vehicle_id,
  scheduled_departure,
  actual_departure,
  scheduled_arrival,
  actual_arrival,
  status,
  (actual_departure - scheduled_departure) AS departure_delay,
  (actual_arrival - scheduled_arrival) AS arrival_delay
FROM transportation.trips
WHERE
  driver_id = 'DRV789';

[User] Now, focusing on driver 'DRV789', identify consecutive pairs of trips based on scheduled departure time. Show the trip IDs and scheduled times for both trips in each pair.

[Assistant]
SELECT
  t1.trip_id AS first_trip_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.trip_id AS next_trip_id,
  t2.scheduled_departure AS next_scheduled_departure
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.driver_id = t2.driver_id
WHERE
  t1.driver_id = 'DRV789'
  AND t2.scheduled_departure = (
    SELECT MIN(scheduled_departure)
    FROM transportation.trips AS t3
    WHERE
      t3.driver_id = t1.driver_id
      AND t3.scheduled_departure > t1.scheduled_departure
  )
ORDER BY
  t1.scheduled_departure;

[User] Filter these consecutive trips for driver 'DRV789' to only show pairs where the destination location of the first trip is the same as the origin location of the second trip.

[Assistant]
SELECT
  t1.trip_id AS first_trip_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t1.destination_location_id AS first_trip_destination,
  t2.trip_id AS next_trip_id,
  t2.scheduled_departure AS next_scheduled_departure,
  t2.origin_location_id AS next_trip_origin
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.driver_id = t2.driver_id
WHERE
  t1.driver_id = 'DRV789'
  AND t2.scheduled_departure = (
    SELECT MIN(scheduled_departure)
    FROM transportation.trips AS t3
    WHERE
      t3.driver_id = t1.driver_id
      AND t3.scheduled_departure > t1.scheduled_departure
  )
  AND t1.destination_location_id = t2.origin_location_id
ORDER BY
  t1.scheduled_departure;

[User] Show me all in-progress trips with their current locations (origin_location_id) and destinations, along with the scheduled vs actual departure time difference in minutes.

[Assistant] SELECT trip_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress';

[User] Can you also include the vehicle_id and driver_id, and order by the departure delay in descending order?

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress' ORDER BY departure_delay_minutes DESC;

[User] Now filter to only show trips that have been delayed by more than 30 minutes.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress' AND EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 > 30 ORDER BY departure_delay_minutes DESC;

[User] Show me the count of trips by status for each vehicle, but only include vehicles that have had more than 5 trips total.

[Assistant] SELECT vehicle_id, status, COUNT(*) as trip_count FROM transportation.trips GROUP BY vehicle_id, status HAVING COUNT(*) > 5;

[User] Now filter this to only show vehicles that have had at least 2 cancelled trips.

[Assistant] SELECT vehicle_id, COUNT(*) as cancelled_trips FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2;

[User] Combine both queries to show me vehicles with more than 5 total trips and at least 2 cancelled trips, along with their complete status distribution.

[Assistant] SELECT t.vehicle_id, t.status, COUNT(*) as trip_count FROM transportation.trips t JOIN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 5 INTERSECT SELECT vehicle_id FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2) v ON t.vehicle_id = v.vehicle_id GROUP BY t.vehicle_id, t.status;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Show me all loans with a term longer than 36 months, including their loan_id, account_id, and principal_amount.

[Assistant] SELECT loan_id, account_id, principal_amount FROM financial_services.loans WHERE term_months > 36;

[User] Can you also include their origination_date and current_principal_balance?

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36;

[User] Filter to only show loans that are not yet matured (maturity_date > CURRENT_DATE).

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36 AND maturity_date > CURRENT_DATE;

[User] For each loan type, show the total outstanding principal balance and the number of active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type;

[User] Sort the result by total_outstanding_balance in ascending order.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type ORDER BY total_outstanding_balance ASC;

[User] Only include loan types where there are more than 10 active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type HAVING COUNT(*) > 10 ORDER BY total_outstanding_balance ASC;

[User] Show all loans with a maturity date in the next 60 days, along with their account_id, principal_amount, interest_rate, and maturity_date.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] Only include loans where the status is not 'CLOSED' or 'PAID_OFF'.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] Also, display the loan_type in the result.

[Assistant] SELECT loan_id, account_id, loan_type, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] What is the average interest rate for auto loans (loan_type = 'Auto') with a principal amount between $20,000 and $50,000?

[Assistant] SELECT AVG(interest_rate) AS avg_interest_rate FROM financial_services.loans WHERE loan_type = 'Auto' AND principal_amount BETWEEN 20000 AND 50000;

[User] Show me the total principal amount for each loan type, along with the count of loans and average monthly payment, but only for loans originated in the last 5 years.

[Assistant] SELECT loan_type, SUM(principal_amount) AS total_principal, COUNT(loan_id) AS loan_count, AVG(monthly_payment) AS avg_monthly_payment FROM financial_services.loans WHERE origination_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY loan_type;

[User] What is the average interest rate for loans of type 'Mortgage'?

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage'

[User] Refine this to only include loans with status 'Active'.

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage' AND status = 'Active'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Show conversations that are group chats and have more than 5 participants. List the conversation_id and group_name.

[Assistant] SELECT c.conversation_id, c.group_name FROM social_media.conversations AS c JOIN social_media.conversation_participants AS cp ON c.conversation_id = cp.conversation_id WHERE c.is_group_chat = true GROUP BY c.conversation_id, c.group_name HAVING COUNT(cp.user_id) > 5;

[User] Also, include the total number of messages sent in these group chats.

[Assistant] SELECT c.conversation_id, c.group_name, COUNT(m.message_id) AS total_messages FROM social_media.conversations AS c JOIN social_media.conversation_participants AS cp ON c.conversation_id = cp.conversation_id LEFT JOIN social_media.messages AS m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true GROUP BY c.conversation_id, c.group_name HAVING COUNT(cp.user_id) > 5;

[User] Further filter the results to only include group chats where the last message was sent after '2024-06-01'.

[Assistant] SELECT c.conversation_id, c.group_name, COUNT(m.message_id) AS total_messages FROM social_media.conversations AS c JOIN social_media.conversation_participants AS cp ON c.conversation_id = cp.conversation_id LEFT JOIN social_media.messages AS m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND c.last_message_at > '2024-06-01' GROUP BY c.conversation_id, c.group_name HAVING COUNT(cp.user_id) > 5;

[User] Find posts that have been liked by users the author of the post is following. List the post_id and the user_id of the post author.

[Assistant] SELECT p.post_id, p.user_id AS post_author_user_id FROM social_media.posts AS p JOIN social_media.likes AS l ON p.post_id = l.post_id JOIN social_media.follows AS f ON f.follower_user_id = p.user_id AND f.following_user_id = l.user_id;

[User] Can you refine this to only include posts where the author started following the user *before* the post was created?

[Assistant] SELECT p.post_id, p.user_id AS post_author_user_id FROM social_media.posts AS p JOIN social_media.likes AS l ON p.post_id = l.post_id JOIN social_media.follows AS f ON f.follower_user_id = p.user_id AND f.following_user_id = l.user_id WHERE f.created_at < p.created_at;

[User] List all hashtags that have been used on posts created in the last 90 days. Show the tag_name and the date it was first used on a post within this period.

[Assistant] SELECT h.tag_name, MIN(p.created_at) AS first_use_date_in_period FROM social_media.posts AS p JOIN social_media.post_hashtags AS ph ON p.post_id = ph.post_id JOIN social_media.hashtags AS h ON ph.hashtag_id = h.hashtag_id WHERE p.created_at >= NOW() - INTERVAL '90 days' GROUP BY h.hashtag_id, h.tag_name;

[User] Which users have commented on posts that contain media? Please show the commenter username and the post ID.

[Assistant]
SELECT DISTINCT u.username, c.post_id
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';

[User] Can you also include the content of the comment and the type of media for each post?

[Assistant]
SELECT u.username, c.post_id, c.content AS comment_content, p.media_type
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';

[User] Now only show comments that were created after May 1, 2024, and include the comment creation time.

[Assistant]
SELECT u.username, c.post_id, c.content AS comment_content, p.media_type, c.created_at AS comment_created_at
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> ''
  AND c.created_at > '2024-05-01';

[User] List the message_id, content, sender's username, and group_name for all messages in group chats.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
WHERE c.is_group_chat = TRUE;

[User] Exclude group chats that have fewer than 3 participants.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
JOIN (
  SELECT conversation_id
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) >= 3
) cp ON c.conversation_id = cp.conversation_id
WHERE c.is_group_chat = TRUE;

[User] And only show messages sent after '2024-06-01', ordering by sent_at ascending.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
JOIN (
  SELECT conversation_id
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) >= 3
) cp ON c.conversation_id = cp.conversation_id
WHERE c.is_group_chat = TRUE
  AND m.sent_at > '2024-06-01'
ORDER BY m.sent_at ASC;

[User] Show me the usernames and the group names for each user who has sent at least one message in a group chat.

[Assistant]
SELECT DISTINCT u.username, c.group_name
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.messages m ON c.conversation_id = m.conversation_id AND u.user_id = m.sender_user_id
WHERE c.is_group_chat = true;

[User] Can you include the total number of messages each user has sent in each group chat as well?

[Assistant]
SELECT u.username, c.group_name, COUNT(m.message_id) AS message_count
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.messages m ON c.conversation_id = m.conversation_id AND u.user_id = m.sender_user_id
WHERE c.is_group_chat = true
GROUP BY u.username, c.group_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] List the first name, last name, and email of all customers who live in New York or California.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE state IN ('NY', 'CA');

[User] Find all customers whose email address ends with '@gmail.com'. Please show the customer_id, first name, and email.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com';

[User] Also, restrict this to only customers who are currently 'inactive'.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com' AND status = 'inactive';

[User] How many customers have a non-null phone number in your system?

[Assistant] SELECT COUNT(*) FROM insurance.customers WHERE phone_number IS NOT NULL;

[User] Which cities have more than 10 active customers in the state of Texas? Provide the city name and the customer count.

[Assistant]
SELECT city, COUNT(*) AS customer_count
FROM insurance.customers
WHERE state = 'TX' AND status = 'Active'
GROUP BY city
HAVING COUNT(*) > 10;

[User] How many customers were created in 2023?

[Assistant]
SELECT COUNT(*)
FROM insurance.customers
WHERE EXTRACT(YEAR FROM created_at) = 2023;

[User] Show me the full names and email addresses of all customers who registered after January 1st, 2024.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE created_at > '2024-01-01';

[User] I also want to see their city and state in the result.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01';

[User] Sort the output by the created_at timestamp, newest first.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Limit the result to the top 10 most recently registered customers.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] Show me all group chats with their names and the time they were last active.

[Assistant] SELECT group_name, last_message_at FROM social_media.conversations WHERE is_group_chat = TRUE;

[User] Only show those group chats that were created after March 1, 2024.

[Assistant] SELECT group_name, last_message_at FROM social_media.conversations WHERE is_group_chat = TRUE AND created_at > '2024-03-01';

[User] Can you sort the results by last_message_at in descending order?

[Assistant] SELECT group_name, last_message_at FROM social_media.conversations WHERE is_group_chat = TRUE AND created_at > '2024-03-01' ORDER BY last_message_at DESC;

[User] List group conversation names and the count of messages sent in each conversation after '2024-06-01'.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name;

[User] Only show conversations that have more than 5 messages sent after that date.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name HAVING COUNT(T2.message_id) > 5;

[User] How many conversations are there where the last message was sent before January 1, 2024?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE last_message_at < '2024-01-01';

[User] How many group conversations are there?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = TRUE;

[User] List the names of group conversations and the usernames of participants who joined after '2023-01-01'.

[Assistant] SELECT T1.group_name, T3.username FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01';

[User] Only include conversations where the group name contains the word 'Project'.

[Assistant] SELECT T1.group_name, T3.username FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01' AND T1.group_name LIKE '%Project%';

[User] Can you also include the date each participant joined?

[Assistant] SELECT T1.group_name, T3.username, T2.joined_at FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01' AND T1.group_name LIKE '%Project%';

[User] Order the results by the join date descending.

[Assistant] SELECT T1.group_name, T3.username, T2.joined_at FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01' AND T1.group_name LIKE '%Project%' ORDER BY T2.joined_at DESC;

[User] Provide a breakdown of the total number of conversations, showing how many are group chats and how many are not. Also, show the count of conversations that have a recorded last message time.

[Assistant] SELECT COUNT(*) AS total_conversations, COUNT(CASE WHEN is_group_chat = true THEN 1 END) AS group_chat_count, COUNT(CASE WHEN is_group_chat = false THEN 1 END) AS private_chat_count, COUNT(last_message_at) AS conversations_with_messages_count FROM social_media.conversations;