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 text PRIMARY KEY, 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.service_locations ( location_id text PRIMARY KEY, 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 PRIMARY KEY, 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] Provide the message_subject and agency_name for all notifications that are related to agencies and have a status of 'Sent'.

[Assistant]
SELECT n.message_subject, a.agency_name
FROM government_services.notifications n
JOIN government_services.agencies a ON n.related_entity_id = a.agency_id
WHERE n.related_entity_type = 'agency' AND n.status = 'Sent';

[User] Show me the daily number of notifications sent in March 2024.

[Assistant]
SELECT DATE(sent_at) AS date, COUNT(*) AS notification_count
FROM government_services.notifications
WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
GROUP BY DATE(sent_at);

[User] Now break down those daily counts by channel.

[Assistant]
SELECT DATE(sent_at) AS date, channel, COUNT(*) AS notification_count
FROM government_services.notifications
WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
GROUP BY DATE(sent_at), channel;

[User] Exclude channels that have fewer than 20 notifications total for March 2024.

[Assistant]
WITH daily AS (
  SELECT DATE(sent_at) AS date, channel, COUNT(*) AS notification_count
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY DATE(sent_at), channel
),
channel_totals AS (
  SELECT channel
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY channel
  HAVING COUNT(*) >= 20
)
SELECT d.date, d.channel, d.notification_count
FROM daily d
JOIN channel_totals t ON d.channel = t.channel;

[User] Also include the most recent sent_at timestamp for each channel per day.

[Assistant]
WITH daily AS (
  SELECT DATE(sent_at) AS date,
         channel,
         COUNT(*) AS notification_count,
         MAX(sent_at) AS latest_sent
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY DATE(sent_at), channel
),
channel_totals AS (
  SELECT channel
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY channel
  HAVING COUNT(*) >= 20
)
SELECT d.date, d.channel, d.notification_count, d.latest_sent
FROM daily d
JOIN channel_totals t ON d.channel = t.channel;

[User] List the name of each agency and the total number of service locations it operates in New York State.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS location_count
FROM government_services.agencies a
LEFT JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.state = 'NY'
GROUP BY a.agency_name;

[User] Actually, only include those service locations that are accessible.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS location_count
FROM government_services.agencies a
LEFT JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.state = 'NY' AND sl.is_accessible = TRUE
GROUP BY a.agency_name;

[User] List the first_name, last_name, and registration_date of citizens who registered in 2023 but are still not verified.

[Assistant]
SELECT first_name,
       last_name,
       registration_date
FROM government_services.citizens
WHERE registration_date >= '2023-01-01'
  AND registration_date <  '2024-01-01'
  AND is_verified = FALSE;

[User] Retrieve all notifications with status 'failed' along with the citizen's full name and contact_phone for those notifications that occurred in the past 30 days.

[Assistant]
SELECT n.notification_id,
       n.sent_at,
       n.status,
       c.first_name || ' ' || c.last_name AS full_name,
       c.contact_phone
FROM government_services.notifications n
JOIN government_services.citizens c
  ON n.citizen_id = c.citizen_id
WHERE n.status = 'failed'
  AND n.sent_at >= NOW() - INTERVAL '30 days';


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.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )

[User] Find pairs of consecutive maintenance logs for the same vehicle based on service date. Show the vehicle ID, log IDs, service dates, and odometer readings for both logs in each pair.

[Assistant] SELECT vehicle_id, log_id, service_date, odometer_reading, LAG(log_id) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_log_id, LAG(service_date) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_service_date, LAG(odometer_reading) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_odometer_reading FROM transportation.maintenance_logs ORDER BY vehicle_id, service_date, log_id;

[User] Only show pairs where the odometer reading increased by more than 10000 miles between the consecutive logs.

[Assistant] SELECT vehicle_id, log_id, service_date, odometer_reading, previous_log_id, previous_service_date, previous_odometer_reading FROM ( SELECT vehicle_id, log_id, service_date, odometer_reading, LAG(log_id) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_log_id, LAG(service_date) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_service_date, LAG(odometer_reading) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_odometer_reading FROM transportation.maintenance_logs ) AS subquery WHERE odometer_reading - previous_odometer_reading > 10000 AND previous_log_id IS NOT NULL ORDER BY vehicle_id, service_date;

[User] Also include the service type and cost for the current log entry. Filter results to logs performed in 2023 or later.

[Assistant] SELECT vehicle_id, log_id, service_date, odometer_reading, previous_log_id, previous_service_date, previous_odometer_reading, service_type, cost FROM ( SELECT vehicle_id, log_id, service_date, odometer_reading, service_type, cost, LAG(log_id) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_log_id, LAG(service_date) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_service_date, LAG(odometer_reading) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_odometer_reading FROM transportation.maintenance_logs ) AS subquery WHERE odometer_reading - previous_odometer_reading > 10000 AND previous_log_id IS NOT NULL AND service_date >= '2023-01-01' ORDER BY vehicle_id, service_date;

[User] Show all maintenance logs where the 'next_service_due_date' is before the current date, including the log ID, service date, service type, and the overdue next service date.

[Assistant] SELECT log_id, service_date, service_type, next_service_due_date FROM transportation.maintenance_logs WHERE next_service_due_date < CURRENT_DATE;

[User] List the log ID, vehicle ID, service date, and cost for all maintenance logs where the cost exceeds 2000 and the odometer reading is greater than 100,000.

[Assistant] SELECT log_id, vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE cost > 2000 AND odometer_reading > 100000;

[User] From that list, also include the service type and mechanic name, and filter to only include 'Engine Service' types performed in the year 2023.

[Assistant] SELECT log_id, vehicle_id, service_date, cost, service_type, mechanic_name FROM transportation.maintenance_logs WHERE cost > 2000 AND odometer_reading > 100000 AND service_type = 'Engine Service' AND EXTRACT(YEAR FROM service_date) = 2023;

[User] Show me all maintenance logs that do not have a next service due date recorded. List the log ID, vehicle ID, and service date.

[Assistant] SELECT log_id, vehicle_id, service_date FROM transportation.maintenance_logs WHERE next_service_due_date IS NULL;

[User] For these logs with no next service date, please also include the description and the cost, and sort the results by service date descending.

[Assistant] SELECT log_id, vehicle_id, service_date, description, cost FROM transportation.maintenance_logs WHERE next_service_due_date IS NULL ORDER BY service_date DESC;

[User] Show me all maintenance logs for vehicles that had an 'Oil Change' service in the last 3 months, including the vehicle ID, service date, and cost.

[Assistant] SELECT vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Can you also include the mechanic name and order the results by the most expensive services first?

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' ORDER BY cost DESC;

[User] Now filter these results to only show oil changes that cost more than $100.

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' AND cost > 100 ORDER BY cost 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 transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )

[User] List all trips along with their trip ID and the number of passengers if the trip is currently in progress.

[Assistant] SELECT trip_id, passenger_count FROM transportation.trips WHERE status = 'In Progress';

[User] Add the vehicle_id and driver_id to the result as well.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id FROM transportation.trips WHERE status = 'In Progress';

[User] Actually, I also need the scheduled departure time for these trips.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id, scheduled_departure FROM transportation.trips WHERE status = 'In Progress';

[User] Sort the result by scheduled departure in ascending order.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id, scheduled_departure FROM transportation.trips WHERE status = 'In Progress' ORDER BY scheduled_departure ASC;

[User] Give me all trips where the trip status is 'Completed' with their trip ID, vehicle ID, and number of passengers.

[Assistant] SELECT trip_id, vehicle_id, passenger_count FROM transportation.trips WHERE status = 'Completed';

[User] Now, also include the scheduled and actual arrival times.

[Assistant] SELECT trip_id, vehicle_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed';

[User] I want to filter out trips that had zero passengers.

[Assistant] SELECT trip_id, vehicle_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed' AND passenger_count > 0;

[User] Actually, can you also include the driver ID in the output?

[Assistant] SELECT trip_id, vehicle_id, driver_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed' AND passenger_count > 0;

[User] For each pair of origin and destination location IDs, show the number of completed trips between them.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS completed_trip_count FROM transportation.trips WHERE status = 'Completed' GROUP BY origin_location_id, destination_location_id;

[User] Show all trips with their trip ID, route ID, the ID of their origin location, and the ID of their destination location, where the route ID starts with 'EX'.

[Assistant] SELECT trip_id, route_id, origin_location_id, destination_location_id FROM transportation.trips WHERE route_id LIKE 'EX%';

[User] List all trips where the origin location is different from the destination location and show the trip ID, origin location ID, destination location ID, and route ID.

[Assistant] SELECT trip_id, origin_location_id, destination_location_id, route_id FROM transportation.trips WHERE origin_location_id <> destination_location_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
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)

[User] How many messages currently have a media file attached?

[Assistant] SELECT COUNT(*) FROM social_media.messages WHERE media_url IS NOT NULL;

[User] For each user, show their username and how many unique conversations they have sent at least one message in where the conversation is a group chat.

[Assistant] SELECT T1.username ,  COUNT(DISTINCT T2.conversation_id) FROM users AS T1 JOIN messages AS T2 ON T1.user_id  =  T2.sender_user_id JOIN group_chats AS T3 ON T2.conversation_id  =  T3.conversation_id GROUP BY T1.user_id

[User] Instead, show only users who have sent messages in more than one group chat, and include their email addresses.

[Assistant] SELECT T1.username ,  T1.email ,  COUNT(DISTINCT T2.conversation_id) FROM users AS T1 JOIN messages AS T2 ON T1.user_id  =  T2.sender_user_id JOIN group_chats AS T3 ON T2.conversation_id  =  T3.conversation_id GROUP BY T1.user_id HAVING COUNT(DISTINCT T2.conversation_id)  >  1

[User] Also add the most recent message time sent by each user in these group chats.

[Assistant] SELECT T1.username ,  T1.email ,  COUNT(DISTINCT T2.conversation_id) ,  MAX(T2.sent_at) FROM users AS T1 JOIN messages AS T2 ON T1.user_id  =  T2.sender_user_id JOIN group_chats AS T3 ON T2.conversation_id  =  T3.conversation_id GROUP BY T1.user_id HAVING COUNT(DISTINCT T2.conversation_id)  >  1

[User] List message IDs and their sent time for messages containing media attachments.

[Assistant] SELECT message_id ,  sent_at FROM social_media.messages WHERE media_type IS NOT NULL

[User] List the content and sent time for messages sent by user 'U101'.

[Assistant] SELECT content, sent_at FROM social_media.messages WHERE sender_user_id = 'U101';

[User] Could you also include the group name for those messages and only show messages sent in group chats?

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group';

[User] Now filter to include only messages sent in June 2024 and order them by sent time descending.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC;

[User] Also limit the results to the top 15.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC LIMIT 15;

[User] List the usernames of users who have sent messages containing the word 'urgent', along with the message content and sent time.

[Assistant] SELECT u.username, m.content, m.sent_at FROM social_media.messages m JOIN social_media.users u ON m.sender_user_id = u.user_id WHERE m.content LIKE '%urgent%';

[User] Only include messages sent in private conversations.

[Assistant] SELECT u.username, m.content, m.sent_at FROM social_media.messages m JOIN social_media.users u ON m.sender_user_id = u.user_id JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.content LIKE '%urgent%' AND c.type = 'private';


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.prescriptions ( prescription_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed int, prescription_date timestamp )

[User] Show prescription ID, patient ID, and medication ID for prescriptions that have a start date before their end date.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date;

[User] Only include those where the refills allowed is zero.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0;

[User] Further narrow down to prescriptions with a 'daily' frequency.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0 AND frequency = 'daily';

[User] Count how many such prescriptions were issued by each doctor.

[Assistant] SELECT doctor_id, COUNT(*) FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0 AND frequency = 'daily' GROUP BY doctor_id;

[User] List each doctor and how many prescriptions they have written, sorted by the highest count first.

[Assistant]
SELECT doctor_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY doctor_id
ORDER BY prescription_count DESC;

[User] Find pairs of prescriptions issued to the same patient but for different medications, issued on the same date. Show the patient ID, the prescription IDs of the two prescriptions, and their medication IDs and prescription dates.

[Assistant] SELECT p1.patient_id, p1.prescription_id AS prescription1_id, p1.medication_id AS medication1_id, p2.prescription_id AS prescription2_id, p2.medication_id AS medication2_id, p1.prescription_date FROM healthcare.prescriptions p1 JOIN healthcare.prescriptions p2 ON p1.patient_id = p2.patient_id AND p1.prescription_date = p2.prescription_date AND p1.medication_id <> p2.medication_id AND p1.prescription_id < p2.prescription_id;

[User] Show me all prescriptions, including the prescription ID, medication ID, prescription date, and the prescribing doctor's ID, for patients who have received more than 2 prescriptions.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id
FROM healthcare.prescriptions
WHERE patient_id IN (
  SELECT patient_id
  FROM healthcare.prescriptions
  GROUP BY patient_id
  HAVING COUNT(*) > 2
);

[User] Only show prescriptions where the end_date is null, meaning the prescription is still ongoing.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id
FROM healthcare.prescriptions
WHERE end_date IS NULL
  AND patient_id IN (
    SELECT patient_id
    FROM healthcare.prescriptions
    GROUP BY patient_id
    HAVING COUNT(*) > 2
  );

[User] Add the dosage and quantity_dispensed fields to the result.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id, dosage, quantity_dispensed
FROM healthcare.prescriptions
WHERE end_date IS NULL
  AND patient_id IN (
    SELECT patient_id
    FROM healthcare.prescriptions
    GROUP BY patient_id
    HAVING COUNT(*) > 2
  );

[User] Now, restrict results to prescriptions written after January 1, 2024.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id, dosage, quantity_dispensed
FROM healthcare.prescriptions
WHERE end_date IS NULL
  AND prescription_date > '2024-01-01'
  AND patient_id IN (
    SELECT patient_id
    FROM healthcare.prescriptions
    GROUP BY patient_id
    HAVING COUNT(*) > 2
  );

[User] List all distinct medication IDs that have been prescribed with more than 5 refills allowed.

[Assistant] SELECT DISTINCT medication_id FROM healthcare.prescriptions WHERE refills_allowed > 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 legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )

[User] Show me the full name of every lawyer, their specialization, and the number of cases they are the lead lawyer for.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, l.specialization, COUNT(c.case_id) AS lead_case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
GROUP BY l.first_name, l.last_name, l.specialization;

[User] List all time entries showing the lawyer's full name, the case name, hours spent, and description.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, c.case_name, te.hours_spent, te.description
FROM legal_services.time_entries te
LEFT JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id
LEFT JOIN legal_services.cases c ON te.case_id = c.case_id;

[User] Only show entries where the description contains the word 'hearing'.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, c.case_name, te.hours_spent, te.description
FROM legal_services.time_entries te
LEFT JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id
LEFT JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.description ILIKE '%hearing%';

[User] Now, sort the results by hours spent in descending order and limit it to the top 10 entries.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, c.case_name, te.hours_spent, te.description
FROM legal_services.time_entries te
LEFT JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id
LEFT JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.description ILIKE '%hearing%'
ORDER BY te.hours_spent DESC
LIMIT 10;

[User] Show me the total billable hours and total billed amount for each lawyer who worked on 'Civil Litigation' cases in 2023, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
ORDER BY total_billed_amount DESC;

[User] Actually, I'd like to include only those lawyers who have at least 10 billable entries in that period.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
HAVING COUNT(*) >= 10
ORDER BY total_billed_amount DESC;

[User] Also break down the report by case, listing each lawyer and case_number along with their billable hours and billed amount per case, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       c.case_number,
       SUM(te.hours_spent) AS case_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS case_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id, c.case_number
ORDER BY case_billed_amount DESC;

[User] List all active clients with their client_id, first_name, last_name, and the website of their law firm, matching on company_name = firm_name.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
WHERE cl.status = 'active';

[User] Include only those law firms founded after 2010-01-01 and exclude any with no website.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
WHERE cl.status = 'active'
  AND lf.founded_date > '2010-01-01'
  AND lf.website IS NOT NULL;

[User] Also show the number of cases each client has opened.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website,
       COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
WHERE cl.status = 'active'
  AND lf.founded_date > '2010-01-01'
  AND lf.website IS NOT NULL
GROUP BY cl.client_id, cl.first_name, cl.last_name, lf.website;

[User] Finally, sort the results by case count descending and limit to the top 20.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website,
       COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
WHERE cl.status = 'active'
  AND lf.founded_date > '2010-01-01'
  AND lf.website IS NOT NULL
GROUP BY cl.client_id, cl.first_name, cl.last_name, lf.website
ORDER BY case_count DESC
LIMIT 20;

[User] List all open cases with case_number, case_name, and the client's email and phone.

[Assistant]
SELECT c.case_number,
       c.case_name,
       cl.email,
       cl.phone
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
WHERE c.status = 'Open';

[User] Also include the law_firm name based on the client's company_name, and only include cases opened in the last 6 months.

[Assistant]
SELECT c.case_number,
       c.case_name,
       cl.email,
       cl.phone,
       lf.firm_name
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
LEFT JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
WHERE c.status = 'Open'
  AND c.date_opened >= CURRENT_DATE - INTERVAL '6 months';


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.documents ( document_id text PRIMARY KEY, 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 )

[User] How many documents are in each verification_status?

[Assistant]
SELECT verification_status, COUNT(*) AS document_count
FROM government_services.documents
GROUP BY verification_status;

[User] Only include statuses with more than 100 documents.

[Assistant]
SELECT verification_status, COUNT(*) AS document_count
FROM government_services.documents
GROUP BY verification_status
HAVING COUNT(*) > 100;

[User] Order the results by document_count in descending order.

[Assistant]
SELECT verification_status, COUNT(*) AS document_count
FROM government_services.documents
GROUP BY verification_status
HAVING COUNT(*) > 100
ORDER BY document_count DESC;

[User] Also exclude documents where expiry_date is before today.

[Assistant]
SELECT verification_status, COUNT(*) AS document_count
FROM government_services.documents
WHERE expiry_date >= CURRENT_DATE
GROUP BY verification_status
HAVING COUNT(*) > 100
ORDER BY document_count DESC;

[User] Can you list pairs of documents uploaded by the same citizen? Show both document IDs and the citizen ID.

[Assistant]
SELECT d1.document_id AS document1, d2.document_id AS document2, d1.citizen_id
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.citizen_id = d2.citizen_id
  AND d1.document_id < d2.document_id;

[User] Now, only include pairs where at least one of the documents has a verification_status = 'Pending'.

[Assistant]
SELECT d1.document_id AS document1, d2.document_id AS document2, d1.citizen_id
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.citizen_id = d2.citizen_id
  AND d1.document_id < d2.document_id
WHERE d1.verification_status = 'Pending'
   OR d2.verification_status = 'Pending';

[User] List all document IDs and document types for documents that have been verified by an employee, along with the verification timestamp and the ID of the verifying employee.

[Assistant] SELECT document_id, document_type, verification_timestamp, verified_by_employee_id FROM government_services.documents WHERE verified_by_employee_id IS NOT NULL;

[User] How many documents were uploaded in the month of October 2023?

[Assistant] SELECT COUNT(*) FROM government_services.documents WHERE upload_timestamp >= '2023-10-01 00:00:00' AND upload_timestamp < '2023-11-01 00:00:00';

[User] For each employee who has verified documents, show their full name and the total number of documents they have verified with a status of 'Verified'.

[Assistant] SELECT e.full_name, COUNT(d.document_id) FROM government_services.documents d JOIN employees e ON d.verified_by_employee_id = e.employee_id WHERE d.verification_status = 'Verified' GROUP BY e.full_name;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 train_station_management.train_cars (
    car_id character varying(64) NOT NULL, -- Unique identifier for the train car
    train_id character varying(64) NOT NULL, -- Foreign key referencing trains
    car_number character varying(10) NOT NULL, -- Identifier of the car within the train set
    car_type character varying(64) NOT NULL, -- e.g., Locomotive, Passenger, Sleeper, Dining, Baggage
    class character varying(32), -- e.g., First, Business, Economy (null for non-passenger cars)
    capacity integer, -- Passenger capacity of this specific car (null for non-passenger cars)
    features text, -- Comma-separated list of features (e.g., 'WiFi', 'Power Outlet', 'Accessible Restroom')
    PRIMARY KEY (car_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id)
)

[User] What is the current location of a specific train car with car_id 'TC123'?

[Assistant] I'm sorry, but I can't provide the current location of a specific train car as this information is not stored in the database table. The table only contains static details about train cars such as car type, capacity, and features. For real-time location data, please refer to the train tracking system or contact the relevant department.

[User] Can you help me find the total passenger capacity for each train car on a specific route with route_id 'RT123'?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL;

[User] Can you modify the query to include only passenger cars with a capacity greater than 50?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you also add the route name and description to the result?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity, r.route_name, r.description
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you assist me in finding all staff members assigned to schedules for a specific route with route_id 'RT456', including the train details and schedule status?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.schedules s ON s.train_id = st.primary_station_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] I noticed the query might not be correct. Can you revise it to ensure it connects staff to schedules properly through their primary station or related data?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] Can you filter the results to include only staff with the role of 'Engineer' and schedules with status 'On Time'?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456' AND st.role = 'Engineer' AND s.status = 'On Time';

[User] Can you retrieve the total number of tickets sold for each car type?

[Assistant]
SELECT tc.car_type, COUNT(t.ticket_id) AS total_tickets
FROM train_station_management.train_cars tc
JOIN train_station_management.tickets t ON tc.car_id = t.car_id
GROUP BY tc.car_type;

[User] Can you help me get the total number of passenger cars for each train car type in the database?

[Assistant]
SELECT car_type, COUNT(*) as total_cars
FROM train_station_management.train_cars
WHERE car_type = 'Passenger'
GROUP BY car_type;


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 character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, 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 PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] List all contracts along with the username of the deployer, showing contract_id, contract address, deployed_at, and the username. Order by deployed_at descending.

[Assistant]
SELECT c.contract_id,
       c.address AS contract_address,
       c.deployed_at,
       u.username
FROM web3.contracts c
LEFT JOIN web3.wallets w ON c.deployer_address = w.address
LEFT JOIN web3.users u ON w.user_id = u.user_id
ORDER BY c.deployed_at DESC;

[User] Show each token's symbol, token_name, and the deployer_address and status of the contract where that token was created.

[Assistant]
SELECT t.token_symbol,
       t.token_name,
       c.deployer_address,
       c.status
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address;

[User] Get the total value and average gas_price for each from_address in transactions, but only include senders who have sent more than 5 transactions.

[Assistant]
SELECT from_address,
       SUM(value) AS total_value,
       AVG(gas_price) AS avg_gas_price,
       COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) > 5;

[User] Actually, I also want to include the number of distinct to_address recipients for each sender.

[Assistant]
SELECT from_address,
       SUM(value) AS total_value,
       AVG(gas_price) AS avg_gas_price,
       COUNT(*) AS tx_count,
       COUNT(DISTINCT to_address) AS distinct_recipients
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) > 5;

[User] Find all contracts deployed by users who have also conducted transactions with a value greater than 1 ETH (where 1 ETH = 1e18 wei).

[Assistant] SELECT DISTINCT c.contract_id, c.address, c.deployer_address FROM web3.contracts c JOIN web3.transactions t ON c.deployer_address = t.from_address WHERE t.value > 1e18;

[User] Show the number of wallets created for each user. Return user_id and wallet_count.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id;

[User] Now, can you only show users with more than 2 wallets in the result?

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id
HAVING COUNT(*) > 2;


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 legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )

[User] Can you show me the number of lawyers grouped by specialization?

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization;

[User] Include only specializations that have more than two lawyers.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Also show the average tenure in years for each of those specializations.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Order the result by average tenure in descending order.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2 ORDER BY avg_tenure_years DESC;

[User] Show me the first_name, last_name, and firm_id of all lawyers whose email domain is 'legalfirm.com'.

[Assistant]
SELECT first_name,
       last_name,
       firm_id
FROM legal_services.lawyers
WHERE SPLIT_PART(email, '@', 2) = 'legalfirm.com';

[User] Find all pairs of lawyers who work for the same firm, showing each lawyer's first_name, last_name, email, and firm_id.

[Assistant]
SELECT l1.first_name AS lawyer1_first_name,
       l1.last_name AS lawyer1_last_name,
       l1.email AS lawyer1_email,
       l2.first_name AS lawyer2_first_name,
       l2.last_name AS lawyer2_last_name,
       l2.email AS lawyer2_email,
       l1.firm_id
FROM legal_services.lawyers l1
JOIN legal_services.lawyers l2
  ON l1.firm_id = l2.firm_id
  AND l1.lawyer_id < l2.lawyer_id;

[User] Show me the number of lawyers for each law firm, along with the firm's ID.

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count FROM legal_services.lawyers GROUP BY firm_id;

[User] Can you also include the number of partners per firm in the result?

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count, SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) AS partner_count FROM legal_services.lawyers GROUP BY firm_id;

[User] Please restrict the results to only those firms that have more than 3 partners.

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count, SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) AS partner_count FROM legal_services.lawyers GROUP BY firm_id HAVING SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) > 3;

[User] How many lawyers are there in each specialization, and what is the count per specialization?

[Assistant]
SELECT specialization,
       COUNT(*) AS lawyer_count
FROM legal_services.lawyers
GROUP BY specialization;


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] 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] How many group conversations are there?

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


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 legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)

[User] Show me the first name, last name, and email for all clients registered in January 2023.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1;

[User] Only show those who have provided a phone number.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL;

[User] Also, exclude any clients whose status is 'inactive'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive';

[User] Order the results by last name, then first name.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive' ORDER BY last_name, first_name;

[User] Show me the full name and email of clients whose status is 'prospect' and who registered before 2023-01-01.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE status = 'prospect' AND date_registered < '2023-01-01';

[User] Among these, list only those who do *not* have a company name specified.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE status = 'prospect' AND date_registered < '2023-01-01' AND company_name IS NULL;

[User] Actually, refine it further to only include those who registered in the year 2022, and order the results by last name.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE status = 'prospect' AND date_registered >= '2022-01-01' AND date_registered < '2023-01-01' AND company_name IS NULL ORDER BY last_name;

[User] Find all clients who do not have a company name listed and show their full name and email.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE company_name IS 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 web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] Provide the count of transfers for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count
FROM web3.token_transfers
GROUP BY token_id;

[User] Actually, also include the total transferred value for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count,
       SUM(value) AS total_transferred_value
FROM web3.token_transfers
GROUP BY token_id;

[User] Find all addresses that have only sent tokens (appear in from_address) but have never received any (do not appear in to_address).

[Assistant] SELECT DISTINCT from_address FROM web3.token_transfers WHERE from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers);

[User] For these addresses that have only sent tokens, show the total value of tokens each has sent.

[Assistant] SELECT t1.from_address, SUM(t1.value) AS total_sent_value FROM web3.token_transfers AS t1 WHERE t1.from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers) GROUP BY t1.from_address;

[User] List the top 5 addresses that have received the most token transfers.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count FROM web3.token_transfers GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;

[User] Okay, but only for token_id '0xabc123...' and also show the total value received by each of these addresses for that token.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count, SUM(value) AS total_received_value FROM web3.token_transfers WHERE token_id = '0xabc123...' GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;

[User] For each recipient address, count how many token transfers they have received.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address;

[User] Only show addresses that have received more than 100 transfers.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address HAVING COUNT(*) > 100;

[User] Find token transfers within the same transaction where the recipient of an earlier transfer (based on log_index) becomes the sender of a later transfer. List the transaction ID, the earlier transfer ID, the later transfer ID, the shared address, and the value transferred in both cases.

[Assistant] SELECT t1.transaction_id, t1.transfer_id AS earlier_transfer_id, t2.transfer_id AS later_transfer_id, t1.to_address AS shared_address, t1.value AS earlier_transfer_value, t2.value AS later_transfer_value FROM web3.token_transfers AS t1 JOIN web3.token_transfers AS t2 ON t1.transaction_id = t2.transaction_id WHERE t1.to_address = t2.from_address AND t1.log_index < t2.log_index;


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 gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] Show the total number of game sessions played on each server that is currently 'online'. Include the server name, region, and the count of sessions.

[Assistant] SELECT s.server_name, s.region, COUNT(gs.session_id) AS total_sessions FROM gaming_technology.game_sessions gs JOIN gaming_technology.servers s ON gs.server_id = s.server_id WHERE s.status = 'online' AND gs.server_id IS NOT NULL GROUP BY s.server_name, s.region ORDER BY total_sessions DESC;

[User] Show each player's ID along with the name and quantity of every item they have in their inventory. Join the player inventory with item details.

[Assistant] SELECT pi.player_id, igi.item_name, pi.quantity FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id;

[User] Filter this list to only include items where the quantity is greater than 5 and the item type is 'Consumable'. Order by player_id and then by item_name.

[Assistant] SELECT pi.player_id, igi.item_name, pi.quantity FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id WHERE pi.quantity > 5 AND igi.item_type = 'Consumable' ORDER BY pi.player_id, igi.item_name;

[User] For each game and month, I'd like to see how many sessions started, showing game_id, title, and start_month.

[Assistant]
SELECT g.game_id,
       g.title,
       DATE_TRUNC('month', gs.start_time) AS start_month,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
GROUP BY g.game_id, g.title, DATE_TRUNC('month', gs.start_time);

[User] Can you filter to only include months where the session_count is greater than 100 and also add the average session duration?

[Assistant]
SELECT g.game_id,
       g.title,
       DATE_TRUNC('month', gs.start_time) AS start_month,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
GROUP BY g.game_id, g.title, DATE_TRUNC('month', gs.start_time)
HAVING COUNT(gs.session_id) > 100;

[User] I would like to get the total number of sessions and the average score for each game, showing game_id and title.

[Assistant]
SELECT g.game_id, g.title, COUNT(gs.session_id) AS total_sessions, AVG(gs.score) AS average_score
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
GROUP BY g.game_id, g.title;

[User] Could you exclude ongoing sessions from the calculation (where end_time is null)?

[Assistant]
SELECT g.game_id, g.title, COUNT(gs.session_id) AS total_sessions, AVG(gs.score) AS average_score
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
WHERE gs.end_time IS NOT NULL
GROUP BY g.game_id, g.title;

[User] Actually, only include games that have more than 50 sessions.

[Assistant]
SELECT g.game_id, g.title, COUNT(gs.session_id) AS total_sessions, AVG(gs.score) AS average_score
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
WHERE gs.end_time IS NOT NULL
GROUP BY g.game_id, g.title
HAVING COUNT(gs.session_id) > 50;

[User] Please also show the developer_id for each game.

[Assistant]
SELECT g.game_id, g.title, g.developer_id, COUNT(gs.session_id) AS total_sessions, AVG(gs.score) AS average_score
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
WHERE gs.end_time IS NOT NULL
GROUP BY g.game_id, g.title, g.developer_id
HAVING COUNT(gs.session_id) > 50;

[User] I need the total quantity of items each player has acquired, showing player_id and total_quantity.

[Assistant]
SELECT player_id, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id;

[User] Actually, limit this to acquisitions in the last 7 days.

[Assistant]
SELECT player_id, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
WHERE acquired_at >= NOW() - INTERVAL '7 days'
GROUP BY player_id;

[User] Also include the count of distinct item types each player acquired in that period.

[Assistant]
SELECT player_id,
       COUNT(DISTINCT item_id) AS distinct_items,
       SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
WHERE acquired_at >= NOW() - INTERVAL '7 days'
GROUP BY player_id;

[User] Finally, only show players whose total_quantity exceeds 100.

[Assistant]
SELECT player_id,
       COUNT(DISTINCT item_id) AS distinct_items,
       SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
WHERE acquired_at >= NOW() - INTERVAL '7 days'
GROUP BY player_id
HAVING SUM(quantity) > 100;


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_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )

[User] List all active SUI coins (status 'exists') with their `coin_type`, `symbol`, `name`, and the total balance across all owners.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
GROUP BY sc.coin_type, sm.symbol, sm.name;

[User] Only include coins where the description contains 'staking'.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
  AND sm.description LIKE '%staking%'
GROUP BY sc.coin_type, sm.symbol, sm.name;

[User] Also show the number of distinct owners per `coin_type`.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
  AND sm.description LIKE '%staking%'
GROUP BY sc.coin_type, sm.symbol, sm.name;

[User] Finally, sort by `total_balance` descending and limit to the top 3 coins.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
  AND sm.description LIKE '%staking%'
GROUP BY sc.coin_type, sm.symbol, sm.name
ORDER BY total_balance DESC
LIMIT 3;

[User] Which SUI coins are currently marked as 'exists' and have a balance over 500000 for any owner? Please show the coin_type, balance, and owner.

[Assistant] SELECT coin_type, balance, owner FROM sui_coins WHERE status = 'exists' AND CAST(balance AS bigint) > 500000;

[User] Can you also include the symbol and name of each coin by joining with the sui_coins_metadata table?

[Assistant] SELECT sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND CAST(sc.balance AS bigint) > 500000;

[User] Only include coins where the description in the metadata contains the word 'reward'.

[Assistant] SELECT sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND CAST(sc.balance AS bigint) > 500000 AND scm.description ILIKE '%reward%';

[User] Actually, limit the results to the top 10 coins with the highest balance.

[Assistant] SELECT sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND CAST(sc.balance AS bigint) > 500000 AND scm.description ILIKE '%reward%' ORDER BY CAST(sc.balance AS bigint) DESC LIMIT 10;

[User] List all ERC20 tokens (from token_metas) that have 'Governance' in their name.

[Assistant] SELECT contract_address, symbol, name FROM token_metas WHERE is_erc20 = 1 AND name ILIKE '%Governance%';

[User] For these tokens, show their total_supply and decimals as well.

[Assistant] SELECT contract_address, symbol, name, total_supply, decimals FROM token_metas WHERE is_erc20 = 1 AND name ILIKE '%Governance%';

[User] Now, join with token_prices_latest to add the latest price for each token.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.name ILIKE '%Governance%';

[User] Restrict results to only tokens with a latest price above 5.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.name ILIKE '%Governance%' AND tpl.price > 5;

[User] List the ERC20 tokens (from token_metas) with exactly 6 decimals. Show their symbol, contract_address, and name.

[Assistant] SELECT symbol, contract_address, name FROM token_metas WHERE is_erc20 = 1 AND decimals = 6;

[User] Can you also include the total current supply for each token?

[Assistant] SELECT symbol, contract_address, name, total_supply FROM token_metas WHERE is_erc20 = 1 AND decimals = 6;

[User] Now, join with token_prices_latest to also include the latest price for each token.

[Assistant]
SELECT tm.symbol, tm.contract_address, tm.name, tm.total_supply, tpl.price AS latest_price
FROM token_metas tm
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
WHERE tm.is_erc20 = 1 AND tm.decimals = 6;

[User] Only include tokens where the latest price is between 0.5 and 2.0 USD, and limit the result to the top 5 tokens by price descending.

[Assistant]
SELECT tm.symbol, tm.contract_address, tm.name, tm.total_supply, tpl.price AS latest_price
FROM token_metas tm
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
WHERE tm.is_erc20 = 1 AND tm.decimals = 6 AND tpl.price BETWEEN 0.5 AND 2.0
ORDER BY tpl.price DESC
LIMIT 5;

[User] Show all SUI coins owned by each address where the coin's status is 'exists'. Include the coin_type, owner, and balance.

[Assistant]
SELECT coin_type, owner, balance
FROM sui_coins
WHERE status = 'exists';

[User] Can you add the symbol and name for each coin by joining with sui_coins_metadata where the metadata status is also 'exists'?

[Assistant]
SELECT sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists';

[User] Only include coins where the balance is greater than 1,000,000 and sort by balance descending. Limit to the top 10 results.

[Assistant]
SELECT sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists' AND sc.balance > '1000000'
ORDER BY sc.balance 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 healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)

[User] I need to find all pairs of diagnoses for the same patient where one diagnosis is chronic and the other is non-chronic. Show patient_id, chronic diagnosis_id as chronic_id, non-chronic diagnosis_id as acute_id, chronic diagnosis_date, and acute diagnosis_date.

[Assistant]
SELECT d1.patient_id,
       d1.diagnosis_id AS chronic_id,
       d2.diagnosis_id AS acute_id,
       d1.diagnosis_date AS chronic_date,
       d2.diagnosis_date AS acute_date
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.patient_id = d2.patient_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = FALSE;

[User] Actually, only include pairs where the chronic diagnosis date is after the acute diagnosis date.

[Assistant]
SELECT d1.patient_id,
       d1.diagnosis_id AS chronic_id,
       d2.diagnosis_id AS acute_id,
       d1.diagnosis_date AS chronic_date,
       d2.diagnosis_date AS acute_date
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.patient_id = d2.patient_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = FALSE
  AND d1.diagnosis_date > d2.diagnosis_date;

[User] Also restrict the results to diagnoses made in 2023.

[Assistant]
SELECT d1.patient_id,
       d1.diagnosis_id AS chronic_id,
       d2.diagnosis_id AS acute_id,
       d1.diagnosis_date AS chronic_date,
       d2.diagnosis_date AS acute_date
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.patient_id = d2.patient_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = FALSE
  AND d1.diagnosis_date > d2.diagnosis_date
  AND d1.diagnosis_date BETWEEN '2023-01-01' AND '2023-12-31'
  AND d2.diagnosis_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Which diagnosis codes have been used for more than 5 different patients? Show the diagnosis_code and the patient count.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.diagnoses GROUP BY diagnosis_code HAVING COUNT(DISTINCT patient_id) > 5;

[User] Please also show the code_type for each diagnosis_code in the results.

[Assistant] SELECT diagnosis_code, code_type, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.diagnoses GROUP BY diagnosis_code, code_type HAVING COUNT(DISTINCT patient_id) > 5;

[User] Provide the count of diagnoses by status.

[Assistant]
SELECT status,
       COUNT(*) AS count
FROM healthcare.diagnoses
GROUP BY status;

[User] Now only include statuses with more than 10 diagnoses.

[Assistant]
SELECT status,
       COUNT(*) AS count
FROM healthcare.diagnoses
GROUP BY status
HAVING COUNT(*) > 10;

[User] Find the diagnosis code and description for all non-chronic diagnoses for patient 'patient_789' made by doctor 'doctor_abc'.

[Assistant] SELECT diagnosis_code, description FROM healthcare.diagnoses WHERE patient_id = 'patient_789' AND doctor_id = 'doctor_abc' AND is_chronic = false;

[User] List all pairs of diagnoses that belong to the same medical record. Show record_id, diagnosis_id from the first entry as diag1_id, and diagnosis_id from the second entry as diag2_id.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id;

[User] Only include pairs where both diagnoses are chronic.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = TRUE;


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 hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] List all reviews that have a staff response, including the review comment, staff response text, and the ID of the staff who responded.

[Assistant] SELECT comment, staff_response, response_staff_id FROM hospitality_technology.reviews WHERE staff_response IS NOT NULL

[User] Filter this list to only include reviews submitted in 2023 with an overall rating of 3 or less.

[Assistant] SELECT comment, staff_response, response_staff_id FROM hospitality_technology.reviews WHERE staff_response IS NOT NULL AND EXTRACT(YEAR FROM review_date) = 2023 AND rating_overall <= 3

[User] Now, only show responses from staff members whose position is 'Front Desk'.

[Assistant] SELECT r.comment, r.staff_response, s.staff_id, s.first_name, s.last_name, s.position FROM hospitality_technology.reviews r JOIN hospitality_technology.staff s ON r.response_staff_id = s.staff_id WHERE r.staff_response IS NOT NULL AND EXTRACT(YEAR FROM r.review_date) = 2023 AND r.rating_overall <= 3 AND s.position = 'Front Desk'

[User] Which room types have a base rate above 250 USD, and what are their maximum occupancies?

[Assistant]
SELECT room_type_id, type_name, base_rate, max_occupancy
FROM hospitality_technology.room_types
WHERE base_rate > 250;

[User] For these room types, can you also add the property_id?

[Assistant]
SELECT room_type_id, property_id, type_name, base_rate, max_occupancy
FROM hospitality_technology.room_types
WHERE base_rate > 250;

[User] Now join this with the payments table to show the total payment amount for each property where such a room type exists.

[Assistant]
SELECT r.property_id, SUM(p.amount) AS total_payment_amount
FROM hospitality_technology.room_types r
JOIN hospitality_technology.payments p ON r.property_id = p.reservation_id
WHERE r.base_rate > 250
GROUP BY r.property_id;

[User] Retrieve all room types with a base_rate above 150 for each property.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150;

[User] Also filter to only include room types with max_occupancy >= 3.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150
  AND max_occupancy >= 3;

[User] Finally, show guest first and last names of guests created after '2023-01-01' who could book these room types.

[Assistant]
SELECT g.first_name, g.last_name, rt.property_id, rt.type_name, rt.base_rate
FROM hospitality_technology.room_types rt
CROSS JOIN hospitality_technology.guests g
WHERE rt.base_rate > 150
  AND rt.max_occupancy >= 3
  AND g.created_at > '2023-01-01';

[User] List all staff members hired in 2024, showing their first name, last name, and hire date.

[Assistant] SELECT first_name, last_name, hire_date FROM hospitality_technology.staff WHERE EXTRACT(YEAR FROM hire_date) = 2024

[User] Now, only include those whose position is 'Manager'.

[Assistant] SELECT first_name, last_name, hire_date FROM hospitality_technology.staff WHERE EXTRACT(YEAR FROM hire_date) = 2024 AND position = 'Manager'

[User] Show me the full name of guests who have left reviews along with the overall rating they gave.

[Assistant] SELECT g.first_name, g.last_name, r.rating_overall FROM hospitality_technology.reviews r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id

[User] Filter this list to only include reviews with an overall rating of 4 or higher and order the results by overall rating descending then by review date descending.

[Assistant] SELECT g.first_name, g.last_name, r.rating_overall FROM hospitality_technology.reviews r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id WHERE r.rating_overall >= 4 ORDER BY r.rating_overall DESC, r.review_date 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 financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)

[User] For each customer, provide a summary of their account statuses, showing their full name, account status, and the count of accounts for each status.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status ORDER BY c.last_name, c.first_name, a.status;

[User] Refine this to only include customers who have accounts in at least two different statuses.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status HAVING c.customer_id IN ( SELECT customer_id FROM financial_services.accounts GROUP BY customer_id HAVING COUNT(DISTINCT status) >= 2 ) ORDER BY c.last_name, c.first_name, a.status;

[User] For each customer, show their full name and the average amount of all transactions linked to any of their accounts.

[Assistant] SELECT c.first_name || ' ' || c.last_name AS customer_full_name, AVG(t.amount) AS average_transaction_amount FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id JOIN financial_services.transactions AS t ON a.account_id = t.account_id OR a.account_id = t.related_account_id GROUP BY c.customer_id, customer_full_name;

[User] Only consider transactions that occurred within the last 90 days for this calculation.

[Assistant] SELECT c.first_name || ' ' || c.last_name AS customer_full_name, AVG(t.amount) AS average_transaction_amount FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id JOIN financial_services.transactions AS t ON a.account_id = t.account_id OR a.account_id = t.related_account_id WHERE t.transaction_date >= CURRENT_DATE - INTERVAL '90 day' GROUP BY c.customer_id, customer_full_name;

[User] Filter the results to only show customers where this average transaction amount is greater than 1000.

[Assistant] SELECT c.first_name || ' ' || c.last_name AS customer_full_name, AVG(t.amount) AS average_transaction_amount FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id JOIN financial_services.transactions AS t ON a.account_id = t.account_id OR a.account_id = t.related_account_id WHERE t.transaction_date >= CURRENT_DATE - INTERVAL '90 day' GROUP BY c.customer_id, customer_full_name HAVING AVG(t.amount) > 1000;

[User] Can you provide a breakdown of total and average account balance by account_type and currency for each account status?

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance
FROM financial_services.accounts
GROUP BY account_type, currency, status;

[User] Could you include the minimum and maximum interest rate for each group as well?

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance, MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type, currency, status;

[User] Only show groups where the total_accounts is greater than 20.

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance, MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type, currency, status
HAVING COUNT(*) > 20;

[User] Please sort the results by average_balance in descending order.

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance, MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type, currency, status
HAVING COUNT(*) > 20
ORDER BY average_balance DESC;

[User] List all pairs of employees who work in the same department but at different branches. For each pair, show the employee_id and branch_id for both members.

[Assistant]
SELECT a.employee_id AS employee_id_a, a.branch_id AS branch_id_a, b.employee_id AS employee_id_b, b.branch_id AS branch_id_b, a.department
FROM financial_services.employees a
JOIN financial_services.employees b ON a.department = b.department AND a.employee_id < b.employee_id AND a.branch_id <> b.branch_id;

[User] Can you also add their full names and filter so only Active employees are included for both members of the pair?

[Assistant]
SELECT a.employee_id AS employee_id_a, a.first_name || ' ' || a.last_name AS name_a, a.branch_id AS branch_id_a,
       b.employee_id AS employee_id_b, b.first_name || ' ' || b.last_name AS name_b, b.branch_id AS branch_id_b, a.department
FROM financial_services.employees a
JOIN financial_services.employees b ON a.department = b.department AND a.employee_id < b.employee_id AND a.branch_id <> b.branch_id
WHERE a.status = 'Active' AND b.status = 'Active';

[User] Please include the job titles for both employees and order the results by a.department ascending, then by name_a ascending.

[Assistant]
SELECT a.employee_id AS employee_id_a, a.first_name || ' ' || a.last_name AS name_a, a.job_title AS job_title_a, a.branch_id AS branch_id_a,
       b.employee_id AS employee_id_b, b.first_name || ' ' || b.last_name AS name_b, b.job_title AS job_title_b, b.branch_id AS branch_id_b, a.department
FROM financial_services.employees a
JOIN financial_services.employees b ON a.department = b.department AND a.employee_id < b.employee_id AND a.branch_id <> b.branch_id
WHERE a.status = 'Active' AND b.status = 'Active'
ORDER BY a.department ASC, name_a ASC;

[User] Show me the account details (account_id, account_number, balance) for all active (status = 'Open') checking accounts opened in the last 6 months, along with the customer_id.

[Assistant] SELECT a.account_id, a.account_number, a.balance, a.customer_id FROM financial_services.accounts a WHERE a.account_type = 'Checking' AND a.status = 'Open' AND a.opened_date >= CURRENT_DATE - INTERVAL '6 months';

[User] Now modify the query to only include accounts with a balance greater than $10,000 and sort them by balance in descending order.

[Assistant] SELECT a.account_id, a.account_number, a.balance, a.customer_id FROM financial_services.accounts a WHERE a.account_type = 'Checking' AND a.status = 'Open' AND a.opened_date >= CURRENT_DATE - INTERVAL '6 months' AND a.balance > 10000 ORDER BY a.balance DESC;