System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the first and last names of citizens along with the reference numbers of the applications they have submitted.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.reference_number FROM government_services.citizens AS T1 JOIN government_services.applications AS T2 ON T1.citizen_id  =  T2.citizen_id

[User] List the names of active services offered by agencies with at least one accessible service location in the state of 'New York'. Show the service name, category, agency name, and the location name.

[Assistant] SELECT T1.service_name, T1.category, T2.agency_name, T3.location_name FROM government_services.services AS T1 JOIN government_services.agencies AS T2 ON T1.agency_id = T2.agency_id JOIN government_services.service_locations AS T3 ON T2.agency_id = T3.agency_id WHERE T1.is_active IS TRUE AND T3.is_accessible IS TRUE AND T3.state = 'New York';

[User] How many employees are currently not terminated?

[Assistant] SELECT COUNT(*) FROM government_services.employees WHERE termination_date IS NULL;

[User] Retrieve each employee's first and last name along with the count of applications they've been assigned that are currently in the 'Under Review' status.

[Assistant]
SELECT e.first_name,
       e.last_name,
       COUNT(app.application_id) AS under_review_count
FROM government_services.employees e
LEFT JOIN government_services.applications app ON e.employee_id = app.assigned_employee_id
    AND app.status = 'Under Review'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] List the names of agencies and their established dates, but only for agencies that offer at least one service.

[Assistant] SELECT DISTINCT T1.agency_name ,  T1.established_date FROM government_services.agencies AS T1 JOIN government_services.services AS T2 ON T1.agency_id  =  T2.agency_id

[User] For each service location in Texas, provide the location name, city, and the number of appointments scheduled there by verified citizens.

[Assistant]
SELECT sl.location_name, sl.city, COUNT(a.appointment_id) AS appointment_count
FROM government_services.service_locations sl
JOIN government_services.appointments a ON sl.location_id = a.location_id
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id AND c.is_verified = TRUE
WHERE sl.state = 'Texas'
GROUP BY sl.location_id, sl.location_name, sl.city;

[User] List each employee's first and last name along with the count of active services offered by their agency.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Actually, only include employees whose service count is greater than 5.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(s.service_id) > 5;

[User] For each service category, find the total number of notifications sent related to applications of services in that category.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
GROUP BY s.category;

[User] Exclude notifications with status 'Failed' and 'Cancelled'.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE n.status NOT IN ('Failed', 'Cancelled')
GROUP BY s.category;

[User] Only include categories with at least 10 notifications.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE n.status NOT IN ('Failed', 'Cancelled')
GROUP BY s.category
HAVING COUNT(n.notification_id) >= 10;

[User] Also, order the results by notification_count descending and limit to the top 5 categories.

[Assistant]
SELECT s.category, COUNT(n.notification_id) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE n.status NOT IN ('Failed', 'Cancelled')
GROUP BY s.category
HAVING COUNT(n.notification_id) >= 10
ORDER BY notification_count DESC
LIMIT 5;

[User] For each agency offering more than 5 active services, list the agency_name, jurisdiction_level, and the count of active services. Order the results by the count in descending order.

[Assistant]
SELECT a.agency_name,
       a.jurisdiction_level,
       COUNT(s.service_id) AS active_service_count
FROM government_services.agencies a
JOIN government_services.services s
  ON a.agency_id = s.agency_id
WHERE s.is_active = TRUE
GROUP BY a.agency_name, a.jurisdiction_level
HAVING COUNT(s.service_id) > 5
ORDER BY active_service_count DESC;

[User] Retrieve the citizen_id, full name, and registration_date of all citizens born before 1980-01-01 who are not verified.

[Assistant]
SELECT citizen_id,
       first_name || ' ' || last_name AS full_name,
       registration_date
FROM government_services.citizens
WHERE date_of_birth < '1980-01-01'
  AND is_verified = FALSE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
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 )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] Show each passenger's name and the total number of trips they have booked.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS trip_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Can you show only those passengers who have booked more than two trips?

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS trip_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 2;

[User] Now, for these passengers, also display their email addresses.

[Assistant]
SELECT p.first_name, p.last_name, p.email, COUNT(b.booking_id) AS trip_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING COUNT(b.booking_id) > 2;

[User] Show me the trip_id, route_number, and scheduled_departure for all trips where the associated vehicle has a maintenance log indicating the next service is due before 2024-05-01.

[Assistant]
SELECT t.trip_id, r.route_number, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.maintenance_logs m ON t.vehicle_id = m.vehicle_id
WHERE m.next_service_due_date < '2024-05-01';

[User] For the above list, also include the mechanic_name from the maintenance log.

[Assistant]
SELECT t.trip_id, r.route_number, t.scheduled_departure, m.mechanic_name
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.maintenance_logs m ON t.vehicle_id = m.vehicle_id
WHERE m.next_service_due_date < '2024-05-01';

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

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

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

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

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

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

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

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

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

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

[User] Show me the driver_id and full name for all drivers.

[Assistant] SELECT driver_id, first_name, last_name FROM transportation.drivers;

[User] Only show drivers whose status is 'Inactive'.

[Assistant] SELECT driver_id, first_name, last_name FROM transportation.drivers WHERE status = 'Inactive';

[User] Can you also include their hire date and sort by hire date descending?

[Assistant] SELECT driver_id, first_name, last_name, hire_date FROM transportation.drivers WHERE status = 'Inactive' ORDER BY hire_date DESC;

[User] How many inactive drivers were hired before 2022?

[Assistant] SELECT COUNT(*) FROM transportation.drivers WHERE status = 'Inactive' AND hire_date < '2022-01-01';

[User] What is the average maintenance cost per service_type for maintenance performed in 2023?

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
WHERE service_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY service_type;

[User] Now include only those service types where the average cost exceeds 500 and sort by avg_cost desc.

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
WHERE service_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY service_type
HAVING AVG(cost) > 500
ORDER BY avg_cost DESC;

[User] List each vehicle's ID, make, and model along with the count of trips scheduled to depart in the next 7 days.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count
FROM transportation.vehicles v
JOIN transportation.trips t
  ON v.vehicle_id = t.vehicle_id
WHERE t.scheduled_departure BETWEEN NOW() AND NOW() + INTERVAL '7 days'
GROUP BY v.vehicle_id, v.make, v.model;

[User] Now filter to only include vehicles with more than 2 upcoming trips and order by trip_count descending.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count
FROM transportation.vehicles v
JOIN transportation.trips t
  ON v.vehicle_id = t.vehicle_id
WHERE t.scheduled_departure BETWEEN NOW() AND NOW() + INTERVAL '7 days'
GROUP BY v.vehicle_id, v.make, v.model
HAVING COUNT(t.trip_id) > 2
ORDER BY trip_count DESC;

[User] For each fueling event, show the fuel_log_id, vehicle_id, the full name of the assigned driver for the trip during that fueling event, and the log_timestamp.

[Assistant]
SELECT fl.fuel_log_id, fl.vehicle_id, d.first_name || ' ' || d.last_name AS driver_full_name, fl.log_timestamp
FROM transportation.fuel_logs fl
JOIN transportation.trips t ON fl.trip_id = t.trip_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id;

[User] Show the name and city of all maintenance facility locations and include the total number of maintenance logs performed at each location.

[Assistant]
SELECT l.name, l.city, COUNT(m.log_id) AS maintenance_count
FROM transportation.locations l
LEFT JOIN transportation.maintenance_logs m ON l.location_id = m.vehicle_id
WHERE l.type = 'Maintenance Facility'
GROUP BY l.location_id, l.name, l.city;

[User] Only include maintenance facilities located in New York and order them by the number of maintenance logs in descending order.

[Assistant]
SELECT l.name, l.city, COUNT(m.log_id) AS maintenance_count
FROM transportation.locations l
LEFT JOIN transportation.maintenance_logs m ON l.location_id = m.vehicle_id
WHERE l.type = 'Maintenance Facility' AND l.state_province = 'NY'
GROUP BY l.location_id, l.name, l.city
ORDER BY maintenance_count DESC;

[User] Display the name and type of each location, as well as the earliest and latest maintenance service_date for vehicles assigned to that location (assuming vehicle_id matches location_id).

[Assistant]
SELECT l.name, l.type,
       MIN(m.service_date) AS earliest_service,
       MAX(m.service_date) AS latest_service
FROM transportation.locations l
LEFT JOIN transportation.maintenance_logs m ON l.location_id = m.vehicle_id
GROUP BY l.location_id, l.name, l.type;

[User] I got an error because some locations do not have any maintenance logs. Please only show locations that have at least one associated maintenance log.

[Assistant]
SELECT l.name, l.type,
       MIN(m.service_date) AS earliest_service,
       MAX(m.service_date) AS latest_service
FROM transportation.locations l
JOIN transportation.maintenance_logs m ON l.location_id = m.vehicle_id
GROUP BY l.location_id, l.name, l.type;

[User] Now, include the total cost of all maintenance performed for each location.

[Assistant]
SELECT l.name, l.type,
       MIN(m.service_date) AS earliest_service,
       MAX(m.service_date) AS latest_service,
       SUM(m.cost) AS total_maintenance_cost
FROM transportation.locations l
JOIN transportation.maintenance_logs m ON l.location_id = m.vehicle_id
GROUP BY l.location_id, l.name, l.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 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] List all time entries that do not have a description, including the entry ID, date worked, hours spent, and the first and last name of the lawyer who recorded the entry.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.description IS NULL OR te.description = '';

[User] Show me the total hours spent by each lawyer on a specific case, say with case_id = 'CASE001'.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' GROUP BY lawyer_id;

[User] Can you also include only the entries that are billable?

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' AND is_billable = TRUE GROUP BY lawyer_id;

[User] Now, show only those lawyers who have logged more than 5 billable hours on this case.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' AND is_billable = TRUE GROUP BY lawyer_id HAVING SUM(hours_spent) > 5;

[User] How many time entries were recorded on each date? List the date and the count of entries for that date, ordered by date.

[Assistant] SELECT date_worked, COUNT(*) AS entry_count FROM legal_services.time_entries GROUP BY date_worked ORDER BY date_worked;

[User] List each case_id along with the total hours worked and total billed amount for that case.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries GROUP BY case_id;

[User] Only include entries that have been billed.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE GROUP BY case_id;

[User] And restrict to cases worked on in February 2024 only.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND date_worked >= '2024-02-01' AND date_worked < '2024-03-01' GROUP BY case_id;

[User] Please order the results by total_billed_amount descending.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND date_worked >= '2024-02-01' AND date_worked < '2024-03-01' GROUP BY case_id ORDER BY total_billed_amount DESC;

[User] Show the invoice_id and total hours logged for each invoice.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id;

[User] Only include invoices with more than 10 total hours.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id HAVING SUM(hours_spent) > 10;

[User] Show me all time entries for case ID 'case_abc', including the entry ID, date worked, hours spent, and the first and last name of the lawyer.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc';

[User] Okay, now only show the entries that are marked as billable.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE;

[User] Also, include the description for these entries and sort them by date worked, oldest first.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name, te.description FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE ORDER BY te.date_worked ASC;

[User] List total billable hours and total amount per lawyer for July 2023.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id;

[User] Actually, only include lawyers who logged more than 40 billable hours that month.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id
HAVING SUM(hours_spent) > 40;

[User] Also show the average billing rate for each of those lawyers.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount,
       AVG(billing_rate) AS avg_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id
HAVING SUM(hours_spent) > 40;

[User] Finally, order the results by total_amount descending.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount,
       AVG(billing_rate) AS avg_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id
HAVING SUM(hours_spent) > 40
ORDER BY total_amount DESC;

[User] Can you list all billable and non-billable entry pairs for the same lawyer on the same date?

[Assistant]
SELECT b.lawyer_id,
       b.date_worked,
       b.entry_id AS billable_entry,
       n.entry_id AS non_billable_entry,
       b.description AS billable_desc,
       n.description AS non_billable_desc
FROM legal_services.time_entries b
JOIN legal_services.time_entries n
  ON b.lawyer_id = n.lawyer_id
  AND b.date_worked = n.date_worked
WHERE b.is_billable = TRUE
  AND n.is_billable = FALSE;

[User] Actually, only include pairs where the creation times differ by less than 6 hours.

[Assistant]
SELECT b.lawyer_id,
       b.date_worked,
       b.entry_id AS billable_entry,
       n.entry_id AS non_billable_entry,
       b.description AS billable_desc,
       n.description AS non_billable_desc
FROM legal_services.time_entries b
JOIN legal_services.time_entries n
  ON b.lawyer_id = n.lawyer_id
  AND b.date_worked = n.date_worked
  AND ABS(b.created_at - n.created_at) < INTERVAL '6 hours'
WHERE b.is_billable = TRUE
  AND n.is_billable = FALSE;

[User] How many billable hours has each lawyer logged in July 2024? Return the lawyer_id and the total billable hours, only including entries that have been billed, sorted by total hours descending.

[Assistant]
SELECT lawyer_id, SUM(hours_spent) AS total_billable_hours
FROM legal_services.time_entries
WHERE is_billable = true
  AND is_billed = true
  AND date_worked BETWEEN '2024-07-01' AND '2024-07-31'
GROUP BY lawyer_id
ORDER BY total_billable_hours DESC;

[User] Find pairs of time entries for the same invoice where one entry is billed and the other is not.

[Assistant]
SELECT a.invoice_id,
       a.entry_id AS billed_entry,
       b.entry_id AS unbilled_entry
FROM legal_services.time_entries a
JOIN legal_services.time_entries b
  ON a.invoice_id = b.invoice_id
 AND a.entry_id <> b.entry_id
WHERE a.is_billed = TRUE
  AND b.is_billed = FALSE;

[User] Also show the number of days between the billed and unbilled entry dates.

[Assistant]
SELECT a.invoice_id,
       a.entry_id AS billed_entry,
       b.entry_id AS unbilled_entry,
       ABS(DATE_PART('day', a.date_worked - b.date_worked)) AS days_between
FROM legal_services.time_entries a
JOIN legal_services.time_entries b
  ON a.invoice_id = b.invoice_id
 AND a.entry_id <> b.entry_id
WHERE a.is_billed = TRUE
  AND b.is_billed = FALSE;


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.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)

[User] Find pairs of documents in the same case where one document is version 1 and the other is the highest version for that document_name, showing case_id, document_name, version1, latest_version, version1_upload_timestamp, and latest_upload_timestamp.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version;

[User] Actually, I only want the pairs where the difference between latest_version and version1 is at least 2.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version
WHERE (d2.version - d1.version) >= 2;

[User] Also include the uploaded_by_lawyer_id for both the version1 and the latest version documents.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp,
       d1.uploaded_by_lawyer_id AS version1_uploaded_by,
       d2.uploaded_by_lawyer_id AS latest_uploaded_by
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version
WHERE (d2.version - d1.version) >= 2;

[User] List document names and versions for documents that share the same case_id, showing each pair of versions.

[Assistant] SELECT d1.case_id, d1.document_name AS doc_name_v1, d1.version AS version1, d2.document_name AS doc_name_v2, d2.version AS version2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.case_id = d2.case_id AND d1.version < d2.version;

[User] Actually, I only want to compare the highest version against the second highest version per case.

[Assistant] SELECT d_prev.case_id, d_prev.document_name AS prev_doc, d_prev.version AS prev_version, d_latest.document_name AS latest_doc, d_latest.version AS latest_version FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id);

[User] Also include the upload timestamps and restrict to cases with at least three versions.

[Assistant] SELECT d_latest.case_id, d_prev.document_name AS prev_doc, d_prev.upload_timestamp AS prev_upload, d_latest.document_name AS latest_doc, d_latest.upload_timestamp AS latest_upload FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id) AND (SELECT COUNT(*) FROM legal_services.documents d2 WHERE d2.case_id = d_latest.case_id) >= 3;

[User] List pairs of documents uploaded by the same lawyer, showing uploader ID and both document names.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id;

[User] Only include pairs where the upload timestamps are within 7 days of each other.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id AND ABS(EXTRACT(EPOCH FROM (d1.upload_timestamp - d2.upload_timestamp)))/86400 <= 7;

[User] Show me document names and upload timestamps for documents linked to cases that were opened after January 1, 2023.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01';

[User] Additionally, only include documents that have a version number greater than 1.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01' AND T1.version > 1;

[User] List the document name, type, version, and description for all documents.

[Assistant] SELECT document_name, document_type, version, description FROM documents;

[User] Only include documents where the description is not null.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL;

[User] Also, filter to only show documents with a version greater than 2.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2;

[User] Order the results by upload timestamp descending.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2 ORDER BY upload_timestamp DESC;

[User] List the names of law firms whose managing partner has uploaded at least one document, and show the managing partner ID along with the firm's phone number.

[Assistant] SELECT DISTINCT T1.firm_name, T1.managing_partner_id, T1.phone FROM legal_services.law_firms AS T1 JOIN legal_services.documents AS T2 ON T1.managing_partner_id = T2.uploaded_by_lawyer_id;

[User] List all cases that have an invoice issued in July 2024, showing the case name, case number, invoice number, and issue date.

[Assistant] SELECT T1.case_name, T1.case_number, T2.invoice_number, T2.issue_date FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id WHERE T2.issue_date BETWEEN '2024-07-01' AND '2024-07-31';


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.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)

[User] List all pairs of locations within the same state_province where the two locations are of different types. For each pair, show the first location's name, type, city, and the second location's name, type, city, and their shared state_province.

[Assistant]
SELECT l1.name AS name1, l1.type AS type1, l1.city AS city1, l2.name AS name2, l2.type AS type2, l2.city AS city2, l1.state_province
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.state_province = l2.state_province
 AND l1.location_id < l2.location_id
 AND l1.type <> l2.type;

[User] Now restrict the results to only include pairs where both locations are in the city of 'Houston'.

[Assistant]
SELECT l1.name AS name1, l1.type AS type1, l1.city AS city1, l2.name AS name2, l2.type AS type2, l2.city AS city2, l1.state_province
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.state_province = l2.state_province
 AND l1.city = 'Houston'
 AND l2.city = 'Houston'
 AND l1.location_id < l2.location_id
 AND l1.type <> l2.type;

[User] Which locations lack a postal code? For each, display the name, type, city, and state_province.

[Assistant]
SELECT name, type, city, state_province
FROM transportation.locations
WHERE postal_code IS NULL;

[User] Also show the country and order the results by city in ascending order.

[Assistant]
SELECT name, type, city, state_province, country
FROM transportation.locations
WHERE postal_code IS NULL
ORDER BY city ASC;

[User] List for each fuel_type and unit the average total_cost at each fueling location. Include fuel_type, unit, location name, city, and average_cost, and order the result by average_cost descending.

[Assistant]
SELECT
    f.fuel_type,
    f.unit,
    l.name AS location_name,
    l.city,
    AVG(f.total_cost) AS average_cost
FROM
    transportation.fuel_logs f
JOIN
    transportation.locations l
  ON f.location_id = l.location_id
GROUP BY
    f.fuel_type,
    f.unit,
    l.name,
    l.city
ORDER BY
    average_cost DESC;

[User] I need a report showing the number of maintenance services performed per vehicle, broken down by service_type.

[Assistant]
SELECT
    vehicle_id,
    service_type,
    COUNT(*) AS service_count
FROM
    transportation.maintenance_logs
GROUP BY
    vehicle_id,
    service_type;

[User] Actually, filter to include only vehicles that have at least 2 "Oil Change" services.

[Assistant]
SELECT
    vehicle_id,
    service_type,
    COUNT(*) AS service_count
FROM
    transportation.maintenance_logs
GROUP BY
    vehicle_id,
    service_type
HAVING
    service_type = 'Oil Change'
    AND COUNT(*) >= 2;

[User] Now also include only those vehicles whose average cost for "Engine Repair" exceeds 500.

[Assistant]
SELECT
    m.vehicle_id,
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') AS oil_change_count,
    AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') AS avg_engine_repair_cost
FROM
    transportation.maintenance_logs m
GROUP BY
    m.vehicle_id
HAVING
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') >= 2
    AND AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') > 500;

[User] Finally, sort by total services performed descending and limit to the top 5 vehicles.

[Assistant]
SELECT
    m.vehicle_id,
    COUNT(*) AS total_services,
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') AS oil_change_count,
    AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') AS avg_engine_repair_cost
FROM
    transportation.maintenance_logs m
GROUP BY
    m.vehicle_id
HAVING
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') >= 2
    AND AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') > 500
ORDER BY
    total_services DESC
LIMIT 5;

[User] For each passenger, show their full name and the total amount they have spent on completed bookings.

[Assistant]
SELECT p.first_name, p.last_name, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Can you also include the number of completed bookings for each passenger?

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS completed_bookings, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Only include passengers who have spent more than 300 in total.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS completed_bookings, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING SUM(b.fare) > 300;

[User] I got an error about missing the email, please add their email to the output.

[Assistant]
SELECT p.first_name, p.last_name, p.email, COUNT(b.booking_id) AS completed_bookings, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING SUM(b.fare) > 300;

[User] Get all pairs of locations in the same city, showing both location IDs, names, and the shared city.

[Assistant]
SELECT l1.location_id AS location1_id, l1.name AS location1_name,
       l2.location_id AS location2_id, l2.name AS location2_name,
       l1.city
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.city = l2.city
 AND l1.location_id < l2.location_id;

[User] Show all locations in 'Texas' with their name, city, and type.

[Assistant]
SELECT location_id, name, city, type
FROM transportation.locations
WHERE state_province = 'Texas';

[User] Actually, only include locations in 'Houston' city.

[Assistant]
SELECT location_id, name, city, type
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston';

[User] I want to also see their postal codes.

[Assistant]
SELECT location_id, name, city, type, postal_code
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston';

[User] Please order the results by name in ascending order.

[Assistant]
SELECT location_id, name, city, type, postal_code
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston'
ORDER BY name ASC;


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 trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )

[User] List all asset types in the platform along with the count of assets for each type.

[Assistant] SELECT type, COUNT(*) as asset_count FROM trading_platform.assets GROUP BY type;

[User] Now show only asset types that have more than 10 assets.

[Assistant] SELECT type, COUNT(*) as asset_count FROM trading_platform.assets GROUP BY type HAVING COUNT(*) > 10;

[User] Can you modify the query to order the results by asset_count descending?

[Assistant] SELECT type, COUNT(*) as asset_count FROM trading_platform.assets GROUP BY type HAVING COUNT(*) > 10 ORDER BY asset_count DESC;

[User] Show me all assets whose symbol starts with 'BTC' or 'ETH', along with their full names and types.

[Assistant] SELECT asset_id, name, symbol, type FROM trading_platform.assets WHERE symbol LIKE 'BTC%' OR symbol LIKE 'ETH%';

[User] List all asset symbols where the asset type is 'token'.

[Assistant] SELECT symbol FROM trading_platform.assets WHERE type = 'token';

[User] Show the names and types of all assets whose symbol is exactly 3 characters long.

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3;

[User] Also, I want to order the results alphabetically by asset name.

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 ORDER BY name ASC;

[User] Actually, can you only show assets of type 'token' in the result?

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 AND type = 'token' ORDER BY name ASC;

[User] Now, just return the asset name and symbol for these tokens, sorted by symbol descending.

[Assistant] SELECT name, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 AND type = 'token' ORDER BY symbol DESC;

[User] List all addresses from the utxos table that have at least one spent UTXO and at least one unspent UTXO.

[Assistant] SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1;

[User] For the addresses identified in the previous step, show the address and the total amount of their unspent UTXOs.

[Assistant] SELECT address, SUM(CASE WHEN spent = false THEN amount ELSE 0 END) AS total_unspent_amount FROM trading_platform.utxos WHERE address IN ( SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY address;

[User] Filter the previous result to show only addresses where the total unspent amount is greater than 1000.

[Assistant] SELECT address, SUM(CASE WHEN spent = false THEN amount ELSE 0 END) AS total_unspent_amount FROM trading_platform.utxos WHERE address IN ( SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY address HAVING SUM(CASE WHEN spent = false THEN amount ELSE 0 END) > 1000;

[User] For the addresses with a total unspent amount greater than 1000 (from the previous step), also include the total amount of their spent UTXOs, and order the results by the total unspent amount descending.

[Assistant] SELECT address, SUM(CASE WHEN spent = false THEN amount ELSE 0 END) AS total_unspent_amount, SUM(CASE WHEN spent = true THEN amount ELSE 0 END) AS total_spent_amount FROM trading_platform.utxos WHERE address IN ( SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY address HAVING SUM(CASE WHEN spent = false THEN amount ELSE 0 END) > 1000 ORDER BY total_unspent_amount DESC;

[User] Find transaction IDs in the utxos table that have both spent and unspent UTXOs associated with them. List these transaction IDs.

[Assistant] SELECT transaction_id FROM trading_platform.utxos GROUP BY transaction_id HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1;

[User] Okay, for those transaction IDs, show the total count of spent UTXOs and the total count of unspent UTXOs.

[Assistant] SELECT transaction_id, SUM(CASE WHEN spent = true THEN 1 ELSE 0 END) AS spent_count, SUM(CASE WHEN spent = false THEN 1 ELSE 0 END) AS unspent_count FROM trading_platform.utxos WHERE transaction_id IN ( SELECT transaction_id FROM trading_platform.utxos GROUP BY transaction_id HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY transaction_id;

[User] List all UTXO IDs, addresses, and amounts for unspent UTXOs with an amount between 200 and 800.

[Assistant] SELECT utxo_id, address, amount FROM trading_platform.utxos WHERE spent = false AND amount BETWEEN 200 AND 800;

[User] I need to retrieve asset IDs along with their category and website metadata values for assets that have both entries.

[Assistant]
SELECT m_cat.asset_id,
       m_cat.value AS category,
       m_web.value AS website_url
FROM trading_platform.metadata m_cat
JOIN trading_platform.metadata m_web
  ON m_cat.asset_id = m_web.asset_id
WHERE m_cat.key = 'category'
  AND m_web.key = 'website';

[User] Actually, filter to include only those assets where the category value is 'defi'.

[Assistant]
SELECT m_cat.asset_id,
       m_cat.value AS category,
       m_web.value AS website_url
FROM trading_platform.metadata m_cat
JOIN trading_platform.metadata m_web
  ON m_cat.asset_id = m_web.asset_id
WHERE m_cat.key = 'category'
  AND m_web.key = 'website'
  AND m_cat.value = 'defi';

[User] List asset_id, issuer and launch_date metadata values for each asset that has both 'issuer' and 'launch_date' keys.

[Assistant]
SELECT m_iss.asset_id,
       m_iss.value AS issuer,
       m_ld.value AS launch_date
FROM trading_platform.metadata m_iss
JOIN trading_platform.metadata m_ld
  ON m_iss.asset_id = m_ld.asset_id
WHERE m_iss.key = 'issuer'
  AND m_ld.key = 'launch_date';

[User] That misses assets without a launch_date. I still want to list all issuers with NULL for missing launch_date.

[Assistant]
SELECT m_iss.asset_id,
       m_iss.value AS issuer,
       m_ld.value AS launch_date
FROM trading_platform.metadata m_iss
LEFT JOIN trading_platform.metadata m_ld
  ON m_iss.asset_id = m_ld.asset_id
  AND m_ld.key = 'launch_date'
WHERE m_iss.key = 'issuer';

[User] Also include the metadata_id for the issuer entry as issuer_metadata_id.

[Assistant]
SELECT m_iss.asset_id,
       m_iss.metadata_id AS issuer_metadata_id,
       m_iss.value AS issuer,
       m_ld.value AS launch_date
FROM trading_platform.metadata m_iss
LEFT JOIN trading_platform.metadata m_ld
  ON m_iss.asset_id = m_ld.asset_id
  AND m_ld.key = 'launch_date'
WHERE m_iss.key = 'issuer';

[User] Finally, sort the results by asset_id ascending.

[Assistant]
SELECT m_iss.asset_id,
       m_iss.metadata_id AS issuer_metadata_id,
       m_iss.value AS issuer,
       m_ld.value AS launch_date
FROM trading_platform.metadata m_iss
LEFT JOIN trading_platform.metadata m_ld
  ON m_iss.asset_id = m_ld.asset_id
  AND m_ld.key = 'launch_date'
WHERE m_iss.key = 'issuer'
ORDER BY m_iss.asset_id ASC;


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.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)

[User] I want to see all time entries where the description contains the word 'draft' and that have not been billed yet.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false;

[User] Only include entries that were logged in June 2024.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30';

[User] Now only show entries that are billable and where hours_spent is greater than 2.

[Assistant]
SELECT *
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND is_billable = true
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30'
  AND hours_spent > 2;

[User] Please only include the entry_id, lawyer_id, date_worked, and hours_spent in the output.

[Assistant]
SELECT entry_id, lawyer_id, date_worked, hours_spent
FROM legal_services.time_entries
WHERE description ILIKE '%draft%'
  AND is_billed = false
  AND is_billable = true
  AND date_worked BETWEEN '2024-06-01' AND '2024-06-30'
  AND hours_spent > 2;

[User] Get me all unbilled billable time entries with their entry_id, case_id, lawyer_id, hours_spent, and billing_rate.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE;

[User] Actually, I only want entries for lawyer 'lawyer_123'.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND lawyer_id = 'lawyer_123';

[User] Also, sort the results by hours_spent in descending order.

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND lawyer_id = 'lawyer_123'
ORDER BY hours_spent DESC;

[User] Show me all pairs of time entries made by the same lawyer on the same date. Include both entry IDs, lawyer_id, and date_worked.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id;

[User] Actually, only include pairs where both entries are billable.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id
  AND t1.is_billable = true
  AND t2.is_billable = true;

[User] Also, ensure that the two entries have different hours_spent values.

[Assistant]
SELECT t1.lawyer_id, t1.date_worked, t1.entry_id AS entry_id_1, t2.entry_id AS entry_id_2
FROM legal_services.time_entries t1
JOIN legal_services.time_entries t2
  ON t1.lawyer_id = t2.lawyer_id
  AND t1.date_worked = t2.date_worked
WHERE t1.entry_id < t2.entry_id
  AND t1.is_billable = true
  AND t2.is_billable = true
  AND t1.hours_spent <> t2.hours_spent;

[User] Show me all time entries from the last 90 days, including the entry description, hours spent, the name of the case, and the name of the client.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name, T3.first_name, T3.last_name FROM legal_services.time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN clients AS T3 ON T2.client_id = T3.client_id WHERE T1.date_worked >= CURRENT_DATE - INTERVAL '90 days';

[User] Calculate the total billable hours spent by each lawyer for entries in March 2024.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2024-03-01' AND '2024-03-31'
GROUP BY lawyer_id;

[User] Show me the total hours spent by each lawyer on billable time entries in 2024.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id;

[User] Actually, only include entries that have not yet been billed.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id;

[User] And restrict this to entries recorded after June 30, 2024.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND date_worked > '2024-06-30'
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id;

[User] Finally, order the results by total_hours descending.

[Assistant]
SELECT
  lawyer_id,
  SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND date_worked > '2024-06-30'
  AND EXTRACT(YEAR FROM date_worked) = 2024
GROUP BY lawyer_id
ORDER BY total_hours DESC;

[User] List all time entries where the description includes the word 'email', showing the entry ID, date worked, hours spent, and description.

[Assistant] SELECT entry_id, date_worked, hours_spent, description FROM legal_services.time_entries WHERE description ILIKE '%email%';

[User] Show me the total hours and total billed amount for each lawyer and each case, including the lawyer_id and case_id.

[Assistant]
SELECT lawyer_id, case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount
FROM legal_services.time_entries
WHERE is_billable = true AND is_billed = true
GROUP BY lawyer_id, case_id;

[User] Could you only include entries worked in 2023?

[Assistant]
SELECT lawyer_id, case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount
FROM legal_services.time_entries
WHERE is_billable = true AND is_billed = true
  AND date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY lawyer_id, case_id;

[User] Now, show only those lawyers who have logged more than 20 billable and billed hours in total in 2023, across all cases.

[Assistant]
SELECT lawyer_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount
FROM legal_services.time_entries
WHERE is_billable = true AND is_billed = true
  AND date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY lawyer_id
HAVING SUM(hours_spent) > 20;

[User] Show me the total number of time entries for each case.

[Assistant]
SELECT case_id, COUNT(*) AS entry_count
FROM legal_services.time_entries
GROUP BY case_id;

[User] Only include cases where the total is greater than 10.

[Assistant]
SELECT case_id, COUNT(*) AS entry_count
FROM legal_services.time_entries
GROUP BY case_id
HAVING COUNT(*) > 10;

[User] List the full name of each lawyer along with the location and status of their appointments.

[Assistant] SELECT T1.first_name, T1.last_name, T2.location, T2.status FROM legal_services.lawyers AS T1 JOIN legal_services.appointments AS T2 ON T1.lawyer_id = T2.lawyer_id

[User] Please only show appointments with a status of 'completed' or 'cancelled', and sort by lawyer's last name.

[Assistant] SELECT T1.first_name, T1.last_name, T2.location, T2.status FROM legal_services.lawyers AS T1 JOIN legal_services.appointments AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.status IN ('completed', 'cancelled') ORDER BY T1.last_name


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )

[User] Count the number of events for each hour of the day based on the emitted_at timestamp.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour ORDER BY event_hour;

[User] Actually, only show hours with more than 100 events.

[Assistant] SELECT EXTRACT(HOUR FROM emitted_at) AS event_hour, COUNT(*) AS event_count FROM web3.events GROUP BY event_hour HAVING COUNT(*) > 100 ORDER BY event_hour;

[User] For each contract, can you show the number of different types of events it has emitted along with the contract ID?

[Assistant] SELECT contract_id, COUNT(DISTINCT event_name) AS distinct_event_types FROM web3.events GROUP BY contract_id;

[User] For each event, display its event_id, the event_id of the previous event in the same transaction (if any), and the log_index of both events.

[Assistant]
SELECT curr.event_id   AS current_event_id,
       prev.event_id   AS previous_event_id,
       curr.log_index  AS current_log_index,
       prev.log_index  AS previous_log_index,
       curr.transaction_id
FROM web3.events curr
LEFT JOIN web3.events prev
  ON curr.transaction_id = prev.transaction_id
 AND curr.log_index = prev.log_index + 1;

[User] List the transaction IDs which have had more than one unique event emitted inside them.

[Assistant] SELECT transaction_id FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Actually, can you also list the names of these unique events for each transaction ID?

[Assistant] SELECT transaction_id, STRING_AGG(DISTINCT event_name, ', ') AS unique_event_names FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Can you find the contract that has emitted the most events, and show its contract ID along with the total number of events emitted?

[Assistant] SELECT contract_id, COUNT(*) AS total_events FROM web3.events GROUP BY contract_id ORDER BY total_events DESC LIMIT 1;

[User] Find all pairs of events that occurred in the same transaction but at different log indices, showing both event_ids, their event_names, the transaction_id, and each log_index.

[Assistant]
SELECT a.event_id AS event_id1,
       a.event_name AS event_name1,
       b.event_id AS event_id2,
       b.event_name AS event_name2,
       a.transaction_id,
       a.log_index AS log_index1,
       b.log_index AS log_index2
FROM web3.events a
JOIN web3.events b
  ON a.transaction_id = b.transaction_id
 AND a.log_index < b.log_index;

[User] Show the event_id, transaction_id, and emitted_at timestamp for all events with event_name 'Approval' and contract_id '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef'.

[Assistant] SELECT event_id, transaction_id, emitted_at FROM web3.events WHERE event_name = 'Approval' AND contract_id = '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef';

[User] How many events were emitted on each date? List the date and the count of events.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at);

[User] Actually, only include dates where more than 10 events were emitted.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at)
HAVING COUNT(*) > 10;

[User] Find all events where the data field contains 'amount' and show the event name, contract ID, and transaction ID, along with the log index, sorted by log index in ascending order.

[Assistant] SELECT event_name, contract_id, transaction_id, log_index FROM web3.events WHERE data LIKE '%amount%' ORDER BY log_index ASC;

[User] List events from contract '0xContractA...' that occurred between '2023-01-01' and '2023-01-31'. Show the event ID, event name, and emitted timestamp.

[Assistant] SELECT event_id, event_name, emitted_at FROM web3.events WHERE contract_id = '0xContractA...' AND emitted_at >= '2023-01-01' AND emitted_at < '2023-02-01';

[User] Okay, and only show me the first 10 results, ordered by emitted time descending.

[Assistant] SELECT event_id, event_name, emitted_at FROM web3.events WHERE contract_id = '0xContractA...' AND emitted_at >= '2023-01-01' AND emitted_at < '2023-02-01' ORDER BY emitted_at DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)

[User] Retrieve the most recent log entry for each user, including action and logged_at.

[Assistant]
SELECT l1.user_id,
       l1.action,
       l1.logged_at
FROM trading_platform.logs l1
WHERE l1.logged_at = (
  SELECT MAX(l2.logged_at)
  FROM trading_platform.logs l2
  WHERE l2.user_id = l1.user_id
);

[User] For each user, list their username and the total number of filled orders they have placed.

[Assistant]
SELECT u.username, COUNT(o.order_id) AS filled_order_count
FROM trading_platform.users u
JOIN trading_platform.orders o ON u.user_id = o.user_id
WHERE o.status = 'filled'
GROUP BY u.username;

[User] Now only include users who have placed more than 10 filled orders.

[Assistant]
SELECT u.username, COUNT(o.order_id) AS filled_order_count
FROM trading_platform.users u
JOIN trading_platform.orders o ON u.user_id = o.user_id
WHERE o.status = 'filled'
GROUP BY u.username
HAVING COUNT(o.order_id) > 10;

[User] For each asset, I want to know how many orders have the status 'filled', showing the asset symbol.

[Assistant]
SELECT m.value AS asset_symbol,
       COUNT(*) AS filled_order_count
FROM trading_platform.orders o
JOIN trading_platform.metadata m
  ON o.asset_id = m.asset_id
 AND m.key = 'symbol'
WHERE o.status = 'filled'
GROUP BY m.value;

[User] Include assets that have zero filled orders, showing filled_order_count as 0.

[Assistant]
WITH asset_symbols AS (
  SELECT DISTINCT asset_id,
         value AS asset_symbol
  FROM trading_platform.metadata
  WHERE key = 'symbol'
)
SELECT a.asset_symbol,
       COALESCE(f.filled_order_count, 0) AS filled_order_count
FROM asset_symbols a
LEFT JOIN (
  SELECT asset_id,
         COUNT(*) AS filled_order_count
  FROM trading_platform.orders
  WHERE status = 'filled'
  GROUP BY asset_id
) f
  ON a.asset_id = f.asset_id;

[User] Show for every asset the usernames of users who have both bought and sold that asset, along with the asset name.

[Assistant]
SELECT DISTINCT a.asset_id, a.name AS asset_name, u.username
FROM trading_platform.assets a
JOIN trading_platform.trades t_buyer ON t_buyer.asset_id = a.asset_id
JOIN trading_platform.users u ON u.user_id = t_buyer.buyer_id
WHERE EXISTS (
    SELECT 1 FROM trading_platform.trades t_seller
    WHERE t_seller.asset_id = a.asset_id AND t_seller.seller_id = t_buyer.buyer_id
);

[User] Only include assets where at least 2 different users have both bought and sold them, and list the number of such users.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, COUNT(DISTINCT u.user_id) AS user_count
FROM trading_platform.assets a
JOIN trading_platform.trades t_buyer ON t_buyer.asset_id = a.asset_id
JOIN trading_platform.users u ON u.user_id = t_buyer.buyer_id
WHERE EXISTS (
    SELECT 1 FROM trading_platform.trades t_seller
    WHERE t_seller.asset_id = a.asset_id AND t_seller.seller_id = t_buyer.buyer_id
)
GROUP BY a.asset_id, a.name
HAVING COUNT(DISTINCT u.user_id) >= 2;

[User] Show the name, symbol, and total quantity traded for each asset.

[Assistant]
SELECT a.name, a.symbol, COALESCE(SUM(t.quantity), 0) AS total_quantity_traded
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON t.asset_id = a.asset_id
GROUP BY a.asset_id, a.name, a.symbol;

[User] Only show assets with a total traded quantity less than 50 and order them by total_quantity_traded ascending.

[Assistant]
SELECT a.name, a.symbol, COALESCE(SUM(t.quantity), 0) AS total_quantity_traded
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON t.asset_id = a.asset_id
GROUP BY a.asset_id, a.name, a.symbol
HAVING COALESCE(SUM(t.quantity), 0) < 50
ORDER BY total_quantity_traded ASC;

[User] Some assets have never been traded and do not appear in the result. Please include those assets as well, with total_quantity_traded as 0.

[Assistant]
SELECT a.name, a.symbol, COALESCE(SUM(t.quantity), 0) AS total_quantity_traded
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON t.asset_id = a.asset_id
GROUP BY a.asset_id, a.name, a.symbol
HAVING COALESCE(SUM(t.quantity), 0) < 50 OR SUM(t.quantity) IS NULL
ORDER BY total_quantity_traded ASC;

[User] I noticed that assets with no trades still appear, but the column name is inconsistent when there are no trades. Can you make sure total_quantity_traded always appears as 0 for such assets and is labeled consistently?

[Assistant]
SELECT a.name, a.symbol, COALESCE(SUM(t.quantity), 0) AS total_quantity_traded
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON t.asset_id = a.asset_id
GROUP BY a.asset_id, a.name, a.symbol
HAVING COALESCE(SUM(t.quantity), 0) < 50
ORDER BY total_quantity_traded ASC;

[User] Find the username, email, and total number of orders placed by each user.

[Assistant]
SELECT u.username, u.email, COUNT(o.order_id) AS order_count
FROM trading_platform.users u
LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id
LEFT JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
GROUP BY u.user_id, u.username, u.email;

[User] The query failed because there is no orders table. I want instead the username, email, and total number of trades each user has been involved in, either as a buyer or a seller.

[Assistant]
SELECT u.username, u.email, COUNT(t.trade_id) AS trade_count
FROM trading_platform.users u
LEFT JOIN trading_platform.trades t ON u.user_id = t.buyer_id OR u.user_id = t.seller_id
GROUP BY u.user_id, u.username, u.email;

[User] Please only show users who have participated in more than 2 trades.

[Assistant]
SELECT u.username, u.email, COUNT(t.trade_id) AS trade_count
FROM trading_platform.users u
LEFT JOIN trading_platform.trades t ON u.user_id = t.buyer_id OR u.user_id = t.seller_id
GROUP BY u.user_id, u.username, u.email
HAVING COUNT(t.trade_id) > 2;

[User] Also, show the total trade quantity that each user has bought (as buyer) and the quantity they have sold (as seller).

[Assistant]
SELECT u.username, u.email,
       COUNT(t.trade_id) AS trade_count,
       COALESCE(SUM(CASE WHEN t.buyer_id = u.user_id THEN t.quantity END), 0) AS total_bought,
       COALESCE(SUM(CASE WHEN t.seller_id = u.user_id THEN t.quantity END), 0) AS total_sold
FROM trading_platform.users u
LEFT JOIN trading_platform.trades t ON u.user_id = t.buyer_id OR u.user_id = t.seller_id
GROUP BY u.user_id, u.username, u.email
HAVING COUNT(t.trade_id) > 2;

[User] Show all wallet addresses that have ever received a UTXO.

[Assistant]
SELECT DISTINCT address
FROM trading_platform.utxos;

[User] List all users whose usernames start with the letter 'B'.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username LIKE 'B%';

[User] Can you make it case-insensitive, so usernames starting with either upper or lower case 'b' are included?

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username ILIKE 'b%';

[User] Instead of showing all details, just display the usernames in alphabetical order.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC;

[User] Limit the result to only the first 3 usernames.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC LIMIT 3;

[User] How many users registered in 2024?

[Assistant] SELECT COUNT(*) FROM trading_platform.users WHERE DATE_PART('year', created_at) = 2024;

[User] Show me all users whose email address contains the word 'test', along with their user IDs and the date they registered.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%';

[User] Actually, only include users who registered after January 1, 2024, and sort them by newest registration date first.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%' AND created_at > '2024-01-01' ORDER BY created_at 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 legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )

[User] Please list the full name and status of clients who have not provided a company name.

[Assistant]
SELECT first_name, last_name, status
FROM legal_services.clients
WHERE company_name IS NULL;

[User] Can you show me the company name, email, and phone of all clients who share the same status?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id;

[User] What if I only want to see those clients who registered before January 1st, 2023?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01';

[User] Please add each client's first and last name, and sort the results by company_name.

[Assistant]
SELECT a.first_name, a.last_name, a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01'
ORDER BY a.company_name;

[User] I need a list of unique company names and the number of clients in each company.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name;

[User] Only include companies where there are at least 2 clients.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name
HAVING COUNT(*) >= 2;

[User] Also, show the email addresses of the clients in those companies.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] Only show companies whose name contains the word 'Group'.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL AND company_name ILIKE '%Group%'
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] List all pairs of clients who registered in the same year. Show each client's first_name, last_name, and the registration year.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id;

[User] Actually, only include clients with status = 'active'.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active';

[User] Also, sort the results by registration_year descending and then by the first client's last_name ascending.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active' ORDER BY registration_year DESC, last_name_1 ASC;

[User] List the first_name, last_name, and email of all clients whose email domain is 'gmail.com'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE SUBSTRING(email FROM POSITION('@' IN email) + 1) = 'gmail.com';

[User] List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;

[User] List each client along with another client who shares the same status.

[Assistant] SELECT c1.client_id AS client1_id, c1.first_name AS client1_first_name, c1.last_name AS client1_last_name, c2.client_id AS client2_id, c2.first_name AS client2_first_name, c2.last_name AS client2_last_name, c1.status FROM legal_services.clients c1 JOIN legal_services.clients c2 ON c1.status = c2.status AND c1.client_id <> c2.client_id;

[User] Actually, I only want pairs where the status is 'prospect'.

[Assistant] SELECT c1.client_id AS client1_id, c1.first_name AS client1_first_name, c1.last_name AS client1_last_name, c2.client_id AS client2_id, c2.first_name AS client2_first_name, c2.last_name AS client2_last_name, c1.status FROM legal_services.clients c1 JOIN legal_services.clients c2 ON c1.status = c2.status AND c1.client_id <> c2.client_id WHERE c1.status = 'prospect';

[User] And only include pairs where both clients have provided a phone number.

[Assistant] SELECT c1.client_id AS client1_id, c1.first_name AS client1_first_name, c1.last_name AS client1_last_name, c2.client_id AS client2_id, c2.first_name AS client2_first_name, c2.last_name AS client2_last_name, c1.status FROM legal_services.clients c1 JOIN legal_services.clients c2 ON c1.status = c2.status AND c1.client_id <> c2.client_id WHERE c1.status = 'prospect' AND c1.phone IS NOT NULL AND c2.phone IS NOT NULL;

[User] Show me all clients whose company name contains 'Tech' and display their email and date of registration.

[Assistant] SELECT first_name, last_name, company_name, email, date_registered FROM legal_services.clients WHERE company_name ILIKE '%Tech%';

[User] Show me all clients along with their email addresses who registered in the year 2023.

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

[User] Could you also show their current status and sort the list by the registration date in ascending order?

[Assistant] SELECT first_name, last_name, email, status FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 ORDER BY date_registered ASC;

[User] Additionally, only include those with a company name specified, and display the company name as well.

[Assistant] SELECT first_name, last_name, email, status, company_name FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND company_name IS NOT NULL ORDER BY date_registered ASC;

[User] Give me the count of clients who registered in each month of 2023.

[Assistant] SELECT TO_CHAR(date_registered, 'YYYY-MM') AS reg_month, COUNT(*) AS client_count FROM legal_services.clients WHERE date_registered BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY TO_CHAR(date_registered, 'YYYY-MM') ORDER BY reg_month;

[User] Filter to show only months with more than five registrations.

[Assistant] SELECT TO_CHAR(date_registered, 'YYYY-MM') AS reg_month, COUNT(*) AS client_count FROM legal_services.clients WHERE date_registered BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY TO_CHAR(date_registered, 'YYYY-MM') HAVING COUNT(*) > 5 ORDER BY reg_month;

[User] Can you include the average days since registration for those clients up to today?

[Assistant] SELECT TO_CHAR(date_registered, 'YYYY-MM') AS reg_month, COUNT(*) AS client_count, ROUND(AVG((CURRENT_DATE - date_registered)::INT), 2) AS avg_days_since_registration FROM legal_services.clients WHERE date_registered BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY TO_CHAR(date_registered, 'YYYY-MM') HAVING COUNT(*) > 5;

[User] Now order the results by avg_days_since_registration descending.

[Assistant] SELECT TO_CHAR(date_registered, 'YYYY-MM') AS reg_month, COUNT(*) AS client_count, ROUND(AVG((CURRENT_DATE - date_registered)::INT), 2) AS avg_days_since_registration FROM legal_services.clients WHERE date_registered BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY TO_CHAR(date_registered, 'YYYY-MM') HAVING COUNT(*) > 5 ORDER BY avg_days_since_registration 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 gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )

[User] For each player, can you find the username and registration_date of the player who registered immediately before them in the same country?

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
LEFT JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    );

[User] Actually, I'd like to exclude players who don't have a previous registrant, so only show rows where prev_username is not null.

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    );

[User] I'd like the final result ordered by country_code and then by the player's registration_date.

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    )
ORDER BY p.country_code, p.registration_date;

[User] Can you give me a count of players for each player status?

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players GROUP BY status;

[User] Now, only show me the statuses that have fewer than 100 players.

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players GROUP BY status HAVING COUNT(player_id) < 100;

[User] Show me the username and registration date for players who do not have a last login recorded.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE last_login IS NULL;

[User] Also include their country code in the output.

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL;

[User] Filter this list to only include players from the United Kingdom ('GB').

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'GB';

[User] Order the results by their registration date, from oldest to newest.

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'GB' ORDER BY registration_date ASC;

[User] Show me the usernames and registration dates for players who registered between '2023-01-01' and '2023-12-31'.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE registration_date >= '2023-01-01' AND registration_date < '2024-01-01';

[User] I'd like to see, for each month, the total number of players who registered and how many of them are active versus inactive.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count
FROM gaming_technology.players
GROUP BY month;

[User] Actually, limit this to registrations from January 1, 2022 onwards.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count
FROM gaming_technology.players
WHERE registration_date >= '2022-01-01'
GROUP BY month;

[User] Also, I'd like to calculate the active percentage per month as active_count * 100.0 / total_registrations.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count,
       ROUND(
         COUNT(*) FILTER (WHERE status = 'active') * 100.0 /
         NULLIF(COUNT(*),0), 2
       ) AS active_percentage
FROM gaming_technology.players
WHERE registration_date >= '2022-01-01'
GROUP BY month;

[User] Finally, please sort the output by month in ascending order.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count,
       ROUND(
         COUNT(*) FILTER (WHERE status = 'active') * 100.0 /
         NULLIF(COUNT(*),0), 2
       ) AS active_percentage
FROM gaming_technology.players
WHERE registration_date >= '2022-01-01'
GROUP BY month
ORDER BY month ASC;

[User] List the usernames and registration dates for all players from Germany ('DE') who are currently 'online'.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE country_code = 'DE' AND status = 'online';

[User] Now, for players in Germany ('DE'), show me the count of players for each different status recorded in the table.

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players WHERE country_code = 'DE' GROUP BY status;

[User] Show me all players who do not have a last_login recorded. List their player_id, username, and registration_date.

[Assistant] SELECT player_id, username, registration_date FROM gaming_technology.players WHERE last_login IS NULL;

[User] Additionally, include their email and country_code.

[Assistant] SELECT player_id, username, registration_date, email, country_code FROM gaming_technology.players WHERE last_login IS NULL;

[User] I only want players from the United States. Can you filter the list for country_code = 'US'?

[Assistant] SELECT player_id, username, registration_date, email, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'US';

[User] Please sort the list by registration_date in ascending order.

[Assistant] SELECT player_id, username, registration_date, email, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'US' ORDER BY registration_date ASC;

[User] Find pairs of players from the same country who have different last login dates. Show their usernames, country code, and last login dates. Exclude pairs where either last login date is null.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login;

[User] Filter the results to only include pairs where the last login date difference is more than 30 days.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400;

[User] Exclude pairs where the country code is NULL.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400 AND p1.country_code IS NOT NULL;

[User] Order the results by the country code and then by the larger of the two last login dates in descending order. Limit to the top 10 results.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400 AND p1.country_code IS NOT NULL ORDER BY p1.country_code, GREATEST(p1.last_login, p2.last_login) DESC LIMIT 10;

[User] How many players are registered for each country? Return the country_code and the player count.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY country_code;

[User] I only want to see countries where there are at least 3 players. Please also order the result by player_count descending.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] Remove countries where the country_code is NULL.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players WHERE country_code IS NOT NULL GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] Please also include the earliest registration_date for each country.

[Assistant] SELECT country_code, COUNT(*) AS player_count, MIN(registration_date) AS earliest_registration FROM gaming_technology.players WHERE country_code IS NOT NULL GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] List the usernames and status of all players who have 'de' as their country_code.

[Assistant] SELECT username, status FROM gaming_technology.players WHERE country_code = 'DE';

[User] Can you also add their registration_date and last_login fields?

[Assistant] SELECT username, status, registration_date, last_login FROM gaming_technology.players WHERE country_code = 'DE';

[User] Now, only include players whose status is 'inactive'.

[Assistant] SELECT username, status, registration_date, last_login FROM gaming_technology.players WHERE country_code = 'DE' AND status = 'inactive';

[User] Sort the results by last_login descending, showing players who logged in most recently first.

[Assistant] SELECT username, status, registration_date, last_login FROM gaming_technology.players WHERE country_code = 'DE' AND status = 'inactive' ORDER BY last_login DESC;