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';


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;


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;


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;


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;


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;


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;


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;


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';


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;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )

[User] List all posts that have received at least one like and at least one comment, showing the post_id and the total number of likes and comments each has.

[Assistant]
SELECT p.post_id, COUNT(DISTINCT l.like_id) AS like_count, COUNT(DISTINCT c.comment_id) AS comment_count
FROM social_media.likes l
JOIN social_media.comments c ON l.post_id = c.post_id
JOIN (SELECT DISTINCT post_id FROM social_media.likes) p ON p.post_id = l.post_id
GROUP BY p.post_id;

[User] Also, show the usernames of the users who created each post.

[Assistant]
SELECT p.post_id, u.username, COUNT(DISTINCT l.like_id) AS like_count, COUNT(DISTINCT c.comment_id) AS comment_count
FROM social_media.likes l
JOIN social_media.comments c ON l.post_id = c.post_id
JOIN posts p ON p.post_id = l.post_id
JOIN social_media.users u ON p.user_id = u.user_id
GROUP BY p.post_id, u.username;

[User] Find all users who have set their bio to a non-empty value, showing their username and email.

[Assistant]
SELECT username, email
FROM social_media.users
WHERE bio IS NOT NULL AND TRIM(bio) != '';

[User] Show me the usernames and the count of comments they made on posts associated with the hashtag 'community'.

[Assistant]
SELECT u.username, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username;

[User] Only include users who have made more than 3 comments on such posts.

[Assistant]
SELECT u.username, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username
HAVING COUNT(c.comment_id) > 3;

[User] Also, show the user's full name and sort the result by comment_count descending.

[Assistant]
SELECT u.username, u.full_name, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username, u.full_name
HAVING COUNT(c.comment_id) > 3
ORDER BY comment_count DESC;

[User] Show only the top 10 users by comment_count.

[Assistant]
SELECT u.username, u.full_name, COUNT(c.comment_id) AS comment_count
FROM social_media.users u
JOIN social_media.comments c ON u.user_id = c.user_id
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'community'
GROUP BY u.username, u.full_name
HAVING COUNT(c.comment_id) > 3
ORDER BY comment_count DESC
LIMIT 10;

[User] List all users who commented on posts tagged with hashtag 'spring', showing user_id, comment_id, content, and tag_name.

[Assistant]
SELECT c.user_id, c.comment_id, c.content, h.tag_name
FROM social_media.comments c
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'spring';

[User] Actually, only include comments from the last 7 days.

[Assistant]
SELECT c.user_id, c.comment_id, c.content, h.tag_name
FROM social_media.comments c
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'spring'
  AND c.created_at >= CURRENT_TIMESTAMP - INTERVAL '7 days';

[User] Also only include users who have email notifications enabled.

[Assistant]
SELECT c.user_id, c.comment_id, c.content, h.tag_name
FROM social_media.comments c
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
JOIN social_media.user_settings us ON c.user_id = us.user_id
WHERE h.tag_name = 'spring'
  AND c.created_at >= CURRENT_TIMESTAMP - INTERVAL '7 days'
  AND us.email_notifications_enabled = TRUE;

[User] Order the results by comment created_at descending and limit to 50.

[Assistant]
SELECT c.user_id, c.comment_id, c.content, h.tag_name
FROM social_media.comments c
JOIN social_media.post_hashtags ph ON c.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
JOIN social_media.user_settings us ON c.user_id = us.user_id
WHERE h.tag_name = 'spring'
  AND c.created_at >= CURRENT_TIMESTAMP - INTERVAL '7 days'
  AND us.email_notifications_enabled = TRUE
ORDER BY c.created_at DESC
LIMIT 50;

[User] I need a list of conversation IDs and participant usernames for conversations that have media messages. Include conversation_id, username, and media_type.

[Assistant]
SELECT m.conversation_id, u.username, m.media_type
FROM social_media.messages m
JOIN social_media.conversation_participants cp ON m.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
WHERE m.media_url IS NOT NULL;

[User] Only include messages where media_type = 'image'.

[Assistant]
SELECT m.conversation_id, u.username, m.media_type
FROM social_media.messages m
JOIN social_media.conversation_participants cp ON m.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
WHERE m.media_url IS NOT NULL
  AND m.media_type = 'image';


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)

[User] Which customers have more than one active policy at the same time? Show the customer ID and the number of active policies.

[Assistant]
SELECT customer_id, COUNT(policy_id) AS active_policy_count
FROM insurance.policies
WHERE status = 'Active'
GROUP BY customer_id
HAVING COUNT(policy_id) > 1;

[User] Can you also list the policy numbers for each customer, separated by commas, in a column called policy_numbers?

[Assistant]
SELECT customer_id, COUNT(policy_id) AS active_policy_count, STRING_AGG(policy_number, ', ') AS policy_numbers
FROM insurance.policies
WHERE status = 'Active'
GROUP BY customer_id
HAVING COUNT(policy_id) > 1;

[User] For each insurance product type, retrieve the total premium_amount and average coverage_limit for policies under active products. Include product_type, total_premium, and avg_coverage_limit, sorted by total_premium descending.

[Assistant]
SELECT ip.product_type,
       SUM(p.premium_amount) AS total_premium,
       AVG(p.coverage_limit) AS avg_coverage_limit
FROM insurance.policies p
JOIN insurance.insurance_products ip
  ON p.product_id = ip.product_id
WHERE ip.is_active = TRUE
GROUP BY ip.product_type
ORDER BY total_premium DESC;

[User] Which agents have sold more than 10 insurance policies, and what are the average premium amounts of the policies they sold? Also, include the agent ID and their name.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policies_sold, AVG(p.premium_amount) AS avg_premium
FROM insurance.policies p
JOIN insurance.agents a ON p.agent_id = a.agent_id
GROUP BY a.agent_id, a.first_name, a.last_name
HAVING COUNT(p.policy_id) > 10;

[User] Actually, could you add the license_state of each agent as well?

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, a.license_state, COUNT(p.policy_id) AS policies_sold, AVG(p.premium_amount) AS avg_premium
FROM insurance.policies p
JOIN insurance.agents a ON p.agent_id = a.agent_id
GROUP BY a.agent_id, a.first_name, a.last_name, a.license_state
HAVING COUNT(p.policy_id) > 10;

[User] Please only include agents where the average premium amount is above $3000.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, a.license_state, COUNT(p.policy_id) AS policies_sold, AVG(p.premium_amount) AS avg_premium
FROM insurance.policies p
JOIN insurance.agents a ON p.agent_id = a.agent_id
GROUP BY a.agent_id, a.first_name, a.last_name, a.license_state
HAVING COUNT(p.policy_id) > 10 AND AVG(p.premium_amount) > 3000;

[User] Show me a list of all policy numbers that have a deductible exactly equal to 0.

[Assistant]
SELECT policy_number
FROM insurance.policies
WHERE deductible = 0;

[User] Identify agents who have sold overlapping policies. Return agent_id, policy_number1, policy_number2, and their coverage dates.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date;

[User] Actually, only consider policies that are currently Active for both entries.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'Active'
  AND p2.status = 'Active';

[User] Also, exclude entries where agent_id is null.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'Active'
  AND p2.status = 'Active'
  AND p1.agent_id IS NOT NULL;

[User] Finally, sort by agent_id ascending and limit to 5 results.

[Assistant]
SELECT p1.agent_id,
       p1.policy_number AS policy_number1,
       p2.policy_number AS policy_number2,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date)       AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.agent_id = p2.agent_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'Active'
  AND p2.status = 'Active'
  AND p1.agent_id IS NOT NULL
ORDER BY p1.agent_id ASC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )

[User] Show me all pairs of patients who share the same emergency contact phone, including both patient IDs, their names, and the shared emergency contact phone.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id;

[User] Only include those pairs where both emergency_contact_name values are not null.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id
WHERE p1.emergency_contact_name IS NOT NULL
  AND p2.emergency_contact_name IS NOT NULL;

[User] Also exclude any pairs where the shared emergency contact phone matches the patient's own phone_number.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id
WHERE p1.emergency_contact_name IS NOT NULL
  AND p2.emergency_contact_name IS NOT NULL
  AND p1.emergency_contact_phone <> p1.phone_number
  AND p2.emergency_contact_phone <> p2.phone_number;

[User] Finally, order the results by the shared emergency contact phone ascending and limit to the first 50 pairs.

[Assistant]
SELECT p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name,
       p1.emergency_contact_phone
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.emergency_contact_phone = p2.emergency_contact_phone
 AND p1.patient_id < p2.patient_id
WHERE p1.emergency_contact_name IS NOT NULL
  AND p2.emergency_contact_name IS NOT NULL
  AND p1.emergency_contact_phone <> p1.phone_number
  AND p2.emergency_contact_phone <> p2.phone_number
ORDER BY p1.emergency_contact_phone ASC
LIMIT 50;

[User] Show the patient ID, first name, last name, and email for all patients who have provided both an email address and a phone number.

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

[User] List all pairs of patients who have the same emergency contact name and phone number. Show the IDs and full names of both patients and the shared emergency contact details (name and phone).

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

[User] Only include pairs where the shared emergency contact name is not null.

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

[User] Count the number of patients whose address includes the word 'Street' and are male.

[Assistant] SELECT COUNT(*) FROM healthcare.patients WHERE address LIKE '%Street%' AND gender = 'Male';

[User] Find all patients who share the same home address with another patient; show the address and both patient IDs and names.

[Assistant]
SELECT p1.address,
       p1.patient_id,
       p1.first_name,
       p1.last_name,
       p2.patient_id AS other_patient_id,
       p2.first_name AS other_first_name,
       p2.last_name AS other_last_name
FROM healthcare.patients p1
JOIN healthcare.patients p2
  ON p1.address = p2.address
 AND p1.patient_id < p2.patient_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Get a list of all policies that have at least two beneficiaries with a percentage_share greater than 20%. Include policy_id, policy_number, and beneficiary_count.

[Assistant]
SELECT p.policy_id, p.policy_number, COUNT(pb.beneficiary_id) AS beneficiary_count
FROM insurance.policies p
JOIN insurance.policy_beneficiaries pb
  ON p.policy_id = pb.policy_id
WHERE pb.percentage_share > 20
GROUP BY p.policy_id, p.policy_number
HAVING COUNT(pb.beneficiary_id) >= 2;

[User] Also include the names of those beneficiaries concatenated as a comma-separated string labeled beneficiaries.

[Assistant]
SELECT p.policy_id, p.policy_number,
       COUNT(pb.beneficiary_id) AS beneficiary_count,
       STRING_AGG(pb.first_name || ' ' || pb.last_name, ', ') AS beneficiaries
FROM insurance.policies p
JOIN insurance.policy_beneficiaries pb
  ON p.policy_id = pb.policy_id
WHERE pb.percentage_share > 20
GROUP BY p.policy_id, p.policy_number
HAVING COUNT(pb.beneficiary_id) >= 2;

[User] I want to retrieve all agents along with the number of active policies they've sold and the average premium amount of those active policies. Please include agent_id, first_name, last_name, policy_count, avg_premium. Sort the results by policy_count in descending order.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium
FROM insurance.agents a
LEFT JOIN insurance.policies p
  ON a.agent_id = p.agent_id AND p.status = 'Active'
GROUP BY a.agent_id, a.first_name, a.last_name
ORDER BY policy_count DESC;

[User] Actually, only consider policies where the coverage_limit is above 500000, and include only agents with more than 5 such policies.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium
FROM insurance.agents a
JOIN insurance.policies p
  ON a.agent_id = p.agent_id
WHERE p.status = 'Active'
  AND p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name
HAVING COUNT(p.policy_id) > 5
ORDER BY policy_count DESC;

[User] Add the agent's agency_name and contact_email to the results.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, a.agency_name, a.contact_email,
       COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium
FROM insurance.agents a
JOIN insurance.policies p
  ON a.agent_id = p.agent_id
WHERE p.status = 'Active'
  AND p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name, a.agency_name, a.contact_email
HAVING COUNT(p.policy_id) > 5
ORDER BY policy_count DESC;

[User] List the five most recent claims with their claim_id, incident_date, customer's full name, and estimated_loss, sorted by reported_date descending.

[Assistant]
SELECT c.claim_id, c.incident_date,
       cu.first_name || ' ' || cu.last_name AS full_name,
       c.estimated_loss
FROM insurance.claims c
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
ORDER BY c.reported_date DESC
LIMIT 5;

[User] I need a list of customers who have filed at least one claim, along with the count of their claims and the total estimated loss per customer.

[Assistant]
SELECT c.customer_id,
       COUNT(cl.claim_id) AS claim_count,
       SUM(cl.estimated_loss) AS total_estimated_loss
FROM insurance.customers c
JOIN insurance.claims cl ON c.customer_id = cl.customer_id
GROUP BY c.customer_id;

[User] Actually, only include customers whose total estimated loss exceeds 20000.

[Assistant]
SELECT c.customer_id,
       COUNT(cl.claim_id) AS claim_count,
       SUM(cl.estimated_loss) AS total_estimated_loss
FROM insurance.customers c
JOIN insurance.claims cl ON c.customer_id = cl.customer_id
GROUP BY c.customer_id
HAVING SUM(cl.estimated_loss) > 20000;

[User] Also include their email and phone number in the result.

[Assistant]
SELECT c.customer_id,
       c.first_name,
       c.last_name,
       c.email,
       c.phone_number,
       COUNT(cl.claim_id) AS claim_count,
       SUM(cl.estimated_loss) AS total_estimated_loss
FROM insurance.customers c
JOIN insurance.claims cl ON c.customer_id = cl.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.phone_number
HAVING SUM(cl.estimated_loss) > 20000;

[User] List all policies sold by agents licensed in Texas. Include the policy number, policy start date, and the agent's first and last name.

[Assistant] SELECT T1.policy_number, T1.start_date, T2.first_name, T2.last_name FROM insurance.policies AS T1 JOIN insurance.agents AS T2 ON T1.agent_id = T2.agent_id WHERE T2.license_state = 'TX'

[User] Can you also include the policy status and only show policies that are 'Cancelled'?

[Assistant] SELECT T1.policy_number, T1.start_date, T2.first_name, T2.last_name, T1.status FROM insurance.policies AS T1 JOIN insurance.agents AS T2 ON T1.agent_id = T2.agent_id WHERE T2.license_state = 'TX' AND T1.status = 'Cancelled'

[User] For those cancelled policies, please add the customer's full name.

[Assistant] SELECT T1.policy_number, T1.start_date, T2.first_name AS agent_first_name, T2.last_name AS agent_last_name, T1.status, T3.first_name AS customer_first_name, T3.last_name AS customer_last_name FROM insurance.policies AS T1 JOIN insurance.agents AS T2 ON T1.agent_id = T2.agent_id JOIN insurance.customers AS T3 ON T1.customer_id = T3.customer_id WHERE T2.license_state = 'TX' AND T1.status = 'Cancelled'


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 erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id.text, status.text, coin_type.text, balance.text, owner.text )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE token_prices (
    uuid varchar(36) NOT NULL, -- uuid fields for the functionType  in contract
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] Show me the wallet addresses that hold more than 1000 of any ERC20 token, along with the token symbol and amount, from the erc20_balances table.

[Assistant] SELECT e.wallet_address, t.symbol, e.amount FROM erc20_balances e JOIN token_prices_latest t ON e.contract_address = t.address WHERE CAST(e.amount AS decimal) > 1000;

[User] Can you also include the current price of each token from the token_prices_latest table and sort the results by amount in descending order?

[Assistant] SELECT e.wallet_address, t.symbol, e.amount, t.price FROM erc20_balances e JOIN token_prices_latest t ON e.contract_address = t.address WHERE CAST(e.amount AS decimal) > 1000 ORDER BY CAST(e.amount AS decimal) DESC;

[User] For each Sui NFT with status 'exists', show its object ID, collection type, and owner.

[Assistant] SELECT object_id, collection_type, owner FROM sui_nfts WHERE status = 'exists';

[User] Only show NFTs whose collection_type contains 'Art'.

[Assistant] SELECT object_id, collection_type, owner FROM sui_nfts WHERE status = 'exists' AND collection_type LIKE '%Art%';

[User] Add the name and display metadata for each NFT in the result.

[Assistant] SELECT object_id, collection_type, owner, name, display FROM sui_nfts WHERE status = 'exists' AND collection_type LIKE '%Art%';

[User] Order the results by name in ascending order and limit to the first 10 entries.

[Assistant] SELECT object_id, collection_type, owner, name, display FROM sui_nfts WHERE status = 'exists' AND collection_type LIKE '%Art%' ORDER BY name ASC LIMIT 10;

[User] Which ERC1155 NFT contracts have received approval-for-all events, and for each contract, how many total approval events were recorded?

[Assistant] SELECT contract_address, COUNT(*) AS approval_count FROM erc1155_approval_for_all GROUP BY contract_address;

[User] Can you also show how many unique wallet addresses currently hold NFTs from each of these contracts?

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT nh.wallet_address) AS holder_count FROM erc1155_approval_for_all ea LEFT JOIN nft_holders nh ON ea.contract_address = nh.contract_address GROUP BY ea.contract_address;

[User] Only include contracts where the holder count is greater than 10, sorted by approval_count descending.

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT nh.wallet_address) AS holder_count FROM erc1155_approval_for_all ea LEFT JOIN nft_holders nh ON ea.contract_address = nh.contract_address GROUP BY ea.contract_address HAVING COUNT(DISTINCT nh.wallet_address) > 10 ORDER BY approval_count DESC;

[User] Add a limit to return only the top 10 contracts.

[Assistant] SELECT ea.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT nh.wallet_address) AS holder_count FROM erc1155_approval_for_all ea LEFT JOIN nft_holders nh ON ea.contract_address = nh.contract_address GROUP BY ea.contract_address HAVING COUNT(DISTINCT nh.wallet_address) > 10 ORDER BY approval_count DESC LIMIT 10;

[User] Which wallets have sent more than 5 BTC in the past 7 days? Show wallet_address and total_sent_amount.

[Assistant]
SELECT ta.from_address AS wallet_address, SUM(ta.amt) AS total_sent
FROM token_activities ta
WHERE ta.tick = 'BTC'
  AND ta.block_timestamp >= now() - INTERVAL '7 days'
GROUP BY ta.from_address
HAVING SUM(ta.amt) > 5;

[User] Also include their most recent BTC balance from token_balances_bitcoin.

[Assistant]
SELECT t.wallet_address, t.total_sent,
       (SELECT tb2.amount
        FROM token_balances_bitcoin tb2
        WHERE tb2.wallet_address = t.wallet_address
          AND tb2.tick = 'BTC'
        ORDER BY tb2.block_number DESC
        LIMIT 1) AS current_balance
FROM (
  SELECT ta.from_address AS wallet_address, SUM(ta.amt) AS total_sent
  FROM token_activities ta
  WHERE ta.tick = 'BTC'
    AND ta.block_timestamp >= now() - INTERVAL '7 days'
  GROUP BY ta.from_address
  HAVING SUM(ta.amt) > 5
) t;

[User] Limit to top 5 wallets by total_sent in descending order.

[Assistant]
SELECT t.wallet_address, t.total_sent,
       (SELECT tb2.amount
        FROM token_balances_bitcoin tb2
        WHERE tb2.wallet_address = t.wallet_address
          AND tb2.tick = 'BTC'
        ORDER BY tb2.block_number DESC
        LIMIT 1) AS current_balance
FROM (
  SELECT ta.from_address AS wallet_address, SUM(ta.amt) AS total_sent
  FROM token_activities ta
  WHERE ta.tick = 'BTC'
    AND ta.block_timestamp >= now() - INTERVAL '7 days'
  GROUP BY ta.from_address
  HAVING SUM(ta.amt) > 5
) t
ORDER BY t.total_sent DESC
LIMIT 5;

[User] For each Bitcoin token tick, show me the creator address from the token_info_bitcoin table and the number of unique wallets currently holding that token.

[Assistant] SELECT ti.tick, ti.creator, COUNT(DISTINCT tb.wallet_address) AS unique_wallets FROM token_info_bitcoin ti JOIN token_balances_bitcoin tb ON ti.tick = tb.tick GROUP BY ti.tick, ti.creator;

[User] Now, only include ticks where there are more than 5 unique wallets, and order the result by the number of unique wallets descending.

[Assistant] SELECT ti.tick, ti.creator, COUNT(DISTINCT tb.wallet_address) AS unique_wallets FROM token_info_bitcoin ti JOIN token_balances_bitcoin tb ON ti.tick = tb.tick GROUP BY ti.tick, ti.creator HAVING COUNT(DISTINCT tb.wallet_address) > 5 ORDER BY unique_wallets DESC;