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.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] Find documents that have the same document_name but are associated with different cases. Show the document name and the two different case IDs.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id;

[User] Actually, only show pairs where at least one of the documents is of document_type 'Contract'.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract');

[User] Also, only include pairs where both documents were uploaded in the year 2024.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract') AND YEAR(d1.upload_timestamp) = 2024 AND YEAR(d2.upload_timestamp) = 2024;

[User] List document names, types, and upload timestamps for documents uploaded after '2024-01-01'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01'

[User] Filter the results to only include documents of type 'Contract'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract'

[User] Only show documents with version 3.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' AND version  =  3

[User] Remove the version filter, add the document description, and order by upload timestamp.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp ,  description FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' ORDER BY upload_timestamp

[User] List the document name, upload timestamp, and the full name of the lawyer who uploaded it, for all documents associated with case number 'CASE123'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123'

[User] Only include documents of type 'Pleading'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading'

[User] Also show the version and restrict results to documents with version greater than 1.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T1.version ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading' AND T1.version  >  1

[User] Find pairs of documents within the same case that were uploaded on the same day but by different lawyers. Show the case_id, upload_date, document_id and uploader_id for both documents in the pair.

[Assistant] SELECT d1.case_id, DATE(d1.upload_timestamp) AS upload_date, d1.document_id AS document1_id, d1.uploaded_by_lawyer_id AS lawyer1_id, d2.document_id AS document2_id, d2.uploaded_by_lawyer_id AS lawyer2_id FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.case_id = d2.case_id AND DATE(d1.upload_timestamp) = DATE(d2.upload_timestamp) AND d1.uploaded_by_lawyer_id <> d2.uploaded_by_lawyer_id WHERE d1.document_id < d2.document_id;

[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Find pairs of documents in the same case where one document is of type 'Contract' and the other is of type 'Evidence'. Return the case_id, the contract document_name as contract_name, and the evidence document_name as evidence_name.

[Assistant]
SELECT c.case_id,
       c.document_name AS contract_name,
       e.document_name AS evidence_name
FROM legal_services.documents c
JOIN legal_services.documents e
  ON c.case_id = e.case_id
WHERE c.document_type = 'Contract'
  AND e.document_type = 'Evidence';

[User] How many documents are there for each document_type? Show document_type and count ordered by the count in descending order.

[Assistant]
SELECT document_type,
       COUNT(*) AS count
FROM legal_services.documents
GROUP BY document_type
ORDER BY count DESC;

[User] How many documents has each lawyer uploaded? Return uploaded_by_lawyer_id and the count, only include lawyers with at least 3 documents, sorted by count descending.

[Assistant]
SELECT uploaded_by_lawyer_id,
       COUNT(*) AS doc_count
FROM legal_services.documents
GROUP BY uploaded_by_lawyer_id
HAVING COUNT(*) >= 3
ORDER BY doc_count DESC;

[User] List all documents of type 'Pleading' uploaded between '2023-01-01' and '2023-12-31', including their name, case ID, and upload timestamp.

[Assistant] SELECT document_name, case_id, upload_timestamp FROM legal_services.documents WHERE document_type = 'Pleading' AND upload_timestamp BETWEEN '2023-01-01' AND '2023-12-31';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.passengers ( passenger_id.text, 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, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] For each passenger, compute the count of bookings and average fare for bookings made in February 2024.

[Assistant]
SELECT p.passenger_id, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.passenger_id;

[User] I need to see the passengers' first and last names instead of IDs and only include those with an average fare greater than 75.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75;

[User] Also, order the results by booking_count descending and limit the output to the top 5 passengers.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75
ORDER BY booking_count DESC
LIMIT 5;

[User] Retrieve the first and last names of passengers along with the total sum of fares they've paid for bookings with status 'Completed', ordered by the sum descending.

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

[User] Now, modify the query to include only those passengers who have made more than three completed bookings.

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

[User] List all bookings, including the passenger ID, booking ID, booking time, and the name of the origin and destination locations for the trip.

[Assistant] SELECT b.passenger_id, b.booking_id, b.booking_time, o.name AS origin_location_name, d.name AS destination_location_name FROM transportation.bookings b JOIN transportation.trips t ON b.trip_id = t.trip_id JOIN transportation.locations o ON t.origin_location_id = o.location_id JOIN transportation.locations d ON t.destination_location_id = d.location_id;

[User] List all drivers.

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

[User] Can you also include their hire date and status?

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

[User] Show only drivers hired after 2020-01-01.

[Assistant] SELECT driver_id, first_name, last_name, hire_date, status FROM transportation.drivers WHERE hire_date > '2020-01-01';

[User] Order them by hire date descending and limit to 10.

[Assistant] SELECT driver_id, first_name, last_name, hire_date, status FROM transportation.drivers WHERE hire_date > '2020-01-01' ORDER BY hire_date DESC LIMIT 10;

[User] List all trips including the name of the origin location and the name of the destination location.

[Assistant] SELECT t.trip_id, origin.name AS origin_location_name, destination.name AS destination_location_name FROM transportation.trips t JOIN transportation.locations origin ON t.origin_location_id = origin.location_id JOIN transportation.locations destination ON t.destination_location_id = destination.location_id;

[User] Show me all diesel vehicles with a capacity greater than 20, including their make, model, and year.

[Assistant] SELECT vehicle_id, make, model, year, capacity FROM transportation.vehicles WHERE fuel_type = 'diesel' AND capacity > 20;

[User] Now join this with the drivers table to show which drivers are assigned to these vehicles (assuming driver_id is stored in vehicles table).

[Assistant] SELECT v.vehicle_id, v.make, v.model, v.year, v.capacity, d.driver_id, d.first_name, d.last_name FROM transportation.vehicles v JOIN transportation.drivers d ON v.driver_id = d.driver_id WHERE v.fuel_type = 'diesel' AND v.capacity > 20;

[User] Actually, I need to see only active drivers and order the results by vehicle year in descending order.

[Assistant] SELECT v.vehicle_id, v.make, v.model, v.year, v.capacity, d.driver_id, d.first_name, d.last_name FROM transportation.vehicles v JOIN transportation.drivers d ON v.driver_id = d.driver_id WHERE v.fuel_type = 'diesel' AND v.capacity > 20 AND d.status = 'active' ORDER BY v.year DESC;

[User] List all maintenance logs for vehicles that are currently active, showing the vehicle ID and service type.

[Assistant] SELECT m.vehicle_id, m.service_type FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active';

[User] I also need to see the service date and cost for these logs, but only for services performed in the last 6 months.

[Assistant] SELECT m.vehicle_id, m.service_type, m.service_date, m.cost FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active' AND m.service_date >= CURRENT_DATE - INTERVAL '6 months';

[User] Can you filter this to only show 'Oil Change' services that cost more than $100?

[Assistant] SELECT m.vehicle_id, m.service_type, m.service_date, m.cost FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active' AND m.service_date >= CURRENT_DATE - INTERVAL '6 months' AND m.service_type = 'Oil Change' AND m.cost > 100;

[User] Actually, I need to see the vehicle make and model as well, and order the results by service date with the most recent first.

[Assistant] SELECT m.vehicle_id, v.make, v.model, m.service_type, m.service_date, m.cost FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active' AND m.service_date >= CURRENT_DATE - INTERVAL '6 months' AND m.service_type = 'Oil Change' AND m.cost > 100 ORDER BY m.service_date DESC;

[User] Show me all maintenance logs for vehicles of make 'Toyota' performed after January 1, 2024. Include the log ID, vehicle ID, service date, and service type.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.make = 'Toyota' AND ml.service_date > '2024-01-01';

[User] Can you add the maintenance cost and mechanic name to each entry and sort the results by service date descending?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.cost, ml.mechanic_name
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.make = 'Toyota' AND ml.service_date > '2024-01-01'
ORDER BY ml.service_date DESC;

[User] Actually, only show logs where the maintenance cost is greater than 1000.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.cost, ml.mechanic_name
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.make = 'Toyota' AND ml.service_date > '2024-01-01' AND ml.cost > 1000
ORDER BY ml.service_date DESC;

[User] For each booking, list the booking_id, fare, and the total quantity of fuel consumed on its associated trip.

[Assistant]
SELECT b.booking_id,
       b.fare,
       SUM(fl.quantity) AS total_fuel_quantity
FROM transportation.bookings b
JOIN transportation.fuel_logs fl
  ON b.trip_id = fl.trip_id
GROUP BY b.booking_id, b.fare;

[User] Only include bookings where the total_fuel_quantity > 100 and order the results by total_fuel_quantity DESC.

[Assistant]
SELECT b.booking_id,
       b.fare,
       SUM(fl.quantity) AS total_fuel_quantity
FROM transportation.bookings b
JOIN transportation.fuel_logs fl
  ON b.trip_id = fl.trip_id
GROUP BY b.booking_id, b.fare
HAVING SUM(fl.quantity) > 100
ORDER BY total_fuel_quantity DESC;

[User] For each vehicle, show vehicle_id, make, model, the earliest and latest fuel log IDs with their timestamps.

[Assistant]
WITH extremes AS (
  SELECT vehicle_id,
         MIN(log_timestamp) AS first_ts,
         MAX(log_timestamp) AS last_ts
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT v.vehicle_id,
       v.make,
       v.model,
       fl1.fuel_log_id   AS first_log_id,
       extremes.first_ts AS first_log_timestamp,
       fl2.fuel_log_id   AS last_log_id,
       extremes.last_ts  AS last_log_timestamp
FROM extremes
JOIN transportation.vehicles v
  ON v.vehicle_id = extremes.vehicle_id
JOIN transportation.fuel_logs fl1
  ON fl1.vehicle_id = extremes.vehicle_id
 AND fl1.log_timestamp = extremes.first_ts
JOIN transportation.fuel_logs fl2
  ON fl2.vehicle_id = extremes.vehicle_id
 AND fl2.log_timestamp = extremes.last_ts;

[User] Also include the cost difference between the latest and earliest total_cost as cost_diff.

[Assistant]
WITH extremes AS (
  SELECT vehicle_id,
         MIN(log_timestamp) AS first_ts,
         MAX(log_timestamp) AS last_ts
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT v.vehicle_id,
       v.make,
       v.model,
       fl1.fuel_log_id   AS first_log_id,
       extremes.first_ts AS first_log_timestamp,
       fl2.fuel_log_id   AS last_log_id,
       extremes.last_ts  AS last_log_timestamp,
       (fl2.total_cost - fl1.total_cost) AS cost_diff
FROM extremes
JOIN transportation.vehicles v
  ON v.vehicle_id = extremes.vehicle_id
JOIN transportation.fuel_logs fl1
  ON fl1.vehicle_id = extremes.vehicle_id
 AND fl1.log_timestamp = extremes.first_ts
JOIN transportation.fuel_logs fl2
  ON fl2.vehicle_id = extremes.vehicle_id
 AND fl2.log_timestamp = extremes.last_ts;

[User] Only include vehicles with at least two fuel log entries and cost_diff > 100, and order by cost_diff DESC.

[Assistant]
WITH extremes AS (
  SELECT vehicle_id,
         MIN(log_timestamp) AS first_ts,
         MAX(log_timestamp) AS last_ts,
         COUNT(*) AS log_count
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
  HAVING COUNT(*) >= 2
)
SELECT v.vehicle_id,
       v.make,
       v.model,
       fl1.fuel_log_id   AS first_log_id,
       extremes.first_ts AS first_log_timestamp,
       fl2.fuel_log_id   AS last_log_id,
       extremes.last_ts  AS last_log_timestamp,
       (fl2.total_cost - fl1.total_cost) AS cost_diff
FROM extremes
JOIN transportation.vehicles v
  ON v.vehicle_id = extremes.vehicle_id
JOIN transportation.fuel_logs fl1
  ON fl1.vehicle_id = extremes.vehicle_id
 AND fl1.log_timestamp = extremes.first_ts
JOIN transportation.fuel_logs fl2
  ON fl2.vehicle_id = extremes.vehicle_id
 AND fl2.log_timestamp = extremes.last_ts
WHERE (fl2.total_cost - fl1.total_cost) > 100
ORDER BY cost_diff 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 narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] List the top 5 exchanges with the highest total USD value of tokens held on the 'Ethereum' chain for the latest snapshot time.

[Assistant] SELECT exchange, SUM(usd_value) AS TotalUSDValue FROM cex_token_balance WHERE chain = 'Ethereum' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance WHERE chain = 'Ethereum') GROUP BY exchange ORDER BY TotalUSDValue DESC LIMIT 5

[User] Could you also show the number of distinct tokens held by each of these top exchanges?

[Assistant] SELECT exchange, SUM(usd_value) AS TotalUSDValue, COUNT(DISTINCT token_symbol) AS DistinctTokenCount FROM cex_token_balance WHERE chain = 'Ethereum' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance WHERE chain = 'Ethereum') GROUP BY exchange ORDER BY TotalUSDValue DESC LIMIT 5

[User] For narratives listed in `narrative_info`, find the total USD value held by CEXes for tokens that are among their top 3 listed coins. Show the narrative and the total CEX USD value.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative

[User] Could you also include the number of distinct tokens contributing to this value for each narrative?

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, COUNT(DISTINCT T1.token_symbol) AS DistinctTokenCount FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative

[User] Now, only show narratives where the total CEX USD value is greater than $100,000.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, COUNT(DISTINCT T1.token_symbol) AS DistinctTokenCount FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative HAVING SUM(T1.usd_value) > 100000

[User] Order the results by total CEX USD value in descending order and show the top 5 narratives.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, COUNT(DISTINCT T1.token_symbol) AS DistinctTokenCount FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative HAVING SUM(T1.usd_value) > 100000 ORDER BY TotalCexUSDValue DESC LIMIT 5

[User] For the 'AI' and 'Gaming' narratives, what is the total USD value held by CEXes for tokens listed in their top 3 coins?

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') GROUP BY T2.narrative

[User] Also show the average price of these tokens in CEX holdings for each narrative.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, AVG(T1.price) AS AverageTokenPrice FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') GROUP BY T2.narrative

[User] Can you filter the results to only include tokens where the USD value in the CEX holding record is greater than $1000?

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, AVG(T1.price) AS AverageTokenPrice FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') AND T1.usd_value > 1000 GROUP BY T2.narrative

[User] Order the results by total USD value descending and show both narratives.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, AVG(T1.price) AS AverageTokenPrice FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') AND T1.usd_value > 1000 GROUP BY T2.narrative ORDER BY TotalCexUSDValue 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.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)

[User] Show me a list of all partners who were hired in 2021.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31';

[User] Include their professional email addresses as well.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       email,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31';

[User] Exclude any partners who haven't provided a phone number.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       email,
       phone,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31'
  AND phone IS NOT NULL;

[User] Finally, order the result by hire_date in descending order.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       email,
       phone,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31'
  AND phone IS NOT NULL
ORDER BY hire_date DESC;

[User] Show me the names of law firms founded after 2010, along with the full name of their managing partner.

[Assistant] SELECT f.firm_name, l.first_name, l.last_name FROM legal_services.law_firms AS f JOIN legal_services.lawyers AS l ON f.managing_partner_id = l.lawyer_id WHERE f.founded_date > '2010-12-31';

[User] List the first name, last name, email, and the name of the law firm for all lawyers.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T1.email ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id  =  T2.firm_id

[User] List the first name, last name, specialization, and the name of the law firm for all lawyers hired before January 1, 2020.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T1.specialization ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id  =  T2.firm_id WHERE T1.hire_date < '2020-01-01'

[User] List each lawyer's full name with the full name of the partner at the same firm.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true;

[User] Actually, I only want those lawyers whose specialization includes 'Corporate Law'. Could you update the query?

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%';

[User] Also only show those who were hired after 2020-01-01.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%'
  AND l.hire_date > '2020-01-01';

[User] List all partners who have provided a phone number, showing their full name and email.

[Assistant] SELECT first_name, last_name, email FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL;

[User] Okay, now only include those partners hired between 2020-01-01 and 2022-12-31.

[Assistant] SELECT first_name, last_name, email FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31';

[User] Can you also add their specialization to the output?

[Assistant] SELECT first_name, last_name, email, specialization FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31';

[User] Finally, order the results by specialization in ascending order, then by last name.

[Assistant] SELECT first_name, last_name, email, specialization FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31' ORDER BY specialization ASC, last_name ASC;

[User] How many lawyers who are partners were hired in each year? Show the hire year and the count.

[Assistant] SELECT strftime('%Y', hire_date) AS hire_year ,  count(lawyer_id) FROM legal_services.lawyers WHERE is_partner  =  true GROUP BY hire_year

[User] List the names of all open cases, the name of the client for each case, and the name of the lead lawyer, but only for cases where the lead lawyer specializes in 'Family Law'.

[Assistant] SELECT T1.case_name ,  T2.first_name ,  T2.last_name ,  T3.first_name ,  T3.last_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T3 ON T1.lead_lawyer_id  =  T3.lawyer_id WHERE T1.status  =  'Open' AND T3.specialization  =  'Family Law'

[User] Actually, could you change the specialization filter to 'Criminal Law' and include the case number? Also, please sort the results by the client's last name.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.first_name ,  T2.last_name ,  T3.first_name ,  T3.last_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T3 ON T1.lead_lawyer_id  =  T3.lawyer_id WHERE T1.status  =  'Open' AND T3.specialization  =  'Criminal Law' ORDER BY T2.last_name

[User] Okay, now just show the cases that were opened after '2023-07-01'.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.first_name ,  T2.last_name ,  T3.first_name ,  T3.last_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T3 ON T1.lead_lawyer_id  =  T3.lawyer_id WHERE T1.status  =  'Open' AND T3.specialization  =  'Criminal Law' AND T1.date_opened  >  '2023-07-01' ORDER BY T2.last_name

[User] List each case's number and name with the full name of its lead lawyer and the firm name they belong to.

[Assistant]
SELECT c.case_number, c.case_name, CONCAT(l.first_name, ' ', l.last_name) AS lead_lawyer, f.firm_name
FROM legal_services.cases c
JOIN legal_services.lawyers l ON c.lead_lawyer_id = l.lawyer_id
LEFT JOIN legal_services.law_firms f ON l.firm_id = f.firm_id;

[User] Actually, only include cases that are currently open and have been opened after January 1, 2023.

[Assistant]
SELECT c.case_number, c.case_name, CONCAT(l.first_name, ' ', l.last_name) AS lead_lawyer, f.firm_name
FROM legal_services.cases c
JOIN legal_services.lawyers l ON c.lead_lawyer_id = l.lawyer_id
LEFT JOIN legal_services.law_firms f ON l.firm_id = f.firm_id
WHERE c.status = 'Open'
  AND c.date_opened > '2023-01-01';

[User] Now order the results by date_opened descending and show only the first 20 rows.

[Assistant]
SELECT c.case_number, c.case_name, CONCAT(l.first_name, ' ', l.last_name) AS lead_lawyer, f.firm_name
FROM legal_services.cases c
JOIN legal_services.lawyers l ON c.lead_lawyer_id = l.lawyer_id
LEFT JOIN legal_services.law_firms f ON l.firm_id = f.firm_id
WHERE c.status = 'Open'
  AND c.date_opened > '2023-01-01'
ORDER BY c.date_opened DESC
LIMIT 20;

[User] Find all documents with version greater than 1 and include the case number, case name, and the full name of the lawyer who uploaded them.

[Assistant]
SELECT d.document_id,
       d.document_name,
       c.case_number,
       c.case_name,
       CONCAT(l.first_name, ' ', l.last_name) AS uploader_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE d.version > 1;

[User] Only include those uploaded after March 1, 2024 and order by upload_timestamp ascending.

[Assistant]
SELECT d.document_id,
       d.document_name,
       c.case_number,
       c.case_name,
       CONCAT(l.first_name, ' ', l.last_name) AS uploader_name,
       d.upload_timestamp
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE d.version > 1
  AND d.upload_timestamp > '2024-03-01'
ORDER BY d.upload_timestamp 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 healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )

[User] List the doctor ID, last name, and the date they were updated, for all doctors updated in the year 2024.

[Assistant] SELECT doctor_id, last_name, updated_at FROM healthcare.doctors WHERE updated_at >= '2024-01-01' AND updated_at < '2025-01-01';

[User] Sort this list by their update date, with the most recently updated doctors appearing first.

[Assistant] SELECT doctor_id, last_name, updated_at FROM healthcare.doctors WHERE updated_at >= '2024-01-01' AND updated_at < '2025-01-01' ORDER BY updated_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)

[User] Find all properties in California (state_province = 'California') that have a phone number and email address listed.

[Assistant] SELECT property_name, city, phone_number, email_address FROM hospitality_technology.properties WHERE state_province = 'California' AND phone_number IS NOT NULL AND email_address IS NOT NULL;

[User] Now, join this with another query to show only properties that are also Hotels and have a star rating between 3.5 and 4.5.

[Assistant] SELECT p.property_name, p.city, p.phone_number, p.email_address, p.star_rating FROM hospitality_technology.properties p WHERE p.state_province = 'California' AND p.phone_number IS NOT NULL AND p.email_address IS NOT NULL AND p.property_type = 'Hotel' AND p.star_rating BETWEEN 3.5 AND 4.5;

[User] The query is missing the postal code. Can you include that as well?

[Assistant] SELECT p.property_name, p.city, p.postal_code, p.phone_number, p.email_address, p.star_rating FROM hospitality_technology.properties p WHERE p.state_province = 'California' AND p.phone_number IS NOT NULL AND p.email_address IS NOT NULL AND p.property_type = 'Hotel' AND p.star_rating BETWEEN 3.5 AND 4.5;

[User] Perfect! Now, order the results by city name in alphabetical order.

[Assistant] SELECT p.property_name, p.city, p.postal_code, p.phone_number, p.email_address, p.star_rating FROM hospitality_technology.properties p WHERE p.state_province = 'California' AND p.phone_number IS NOT NULL AND p.email_address IS NOT NULL AND p.property_type = 'Hotel' AND p.star_rating BETWEEN 3.5 AND 4.5 ORDER BY p.city ASC;

[User] Retrieve the total revenue and order count for each department for services in July 2023. Show department, revenue, and order_count.

[Assistant]
SELECT s.department,
       SUM(o.total_price) AS revenue,
       COUNT(o.order_id) AS order_count
FROM hospitality_technology.services s
JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
WHERE o.order_timestamp >= '2023-07-01'
  AND o.order_timestamp < '2023-08-01'
GROUP BY s.department;

[User] Actually, I want to see only departments with revenue over 5000, and sort the results by revenue descending.

[Assistant]
SELECT s.department,
       SUM(o.total_price) AS revenue,
       COUNT(o.order_id) AS order_count
FROM hospitality_technology.services s
JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
WHERE o.order_timestamp >= '2023-07-01'
  AND o.order_timestamp < '2023-08-01'
GROUP BY s.department
HAVING SUM(o.total_price) > 5000
ORDER BY revenue DESC;

[User] Also include the name of the highest priced service in each of these departments and alias it as top_service.

[Assistant]
SELECT dept_stats.department,
       dept_stats.revenue,
       dept_stats.order_count,
       (
         SELECT s2.service_name
         FROM hospitality_technology.services s2
         WHERE s2.department = dept_stats.department
         ORDER BY s2.price DESC
         LIMIT 1
       ) AS top_service
FROM (
  SELECT s.department,
         SUM(o.total_price) AS revenue,
         COUNT(o.order_id) AS order_count
  FROM hospitality_technology.services s
  JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
  WHERE o.order_timestamp >= '2023-07-01'
    AND o.order_timestamp < '2023-08-01'
  GROUP BY s.department
  HAVING SUM(o.total_price) > 5000
) AS dept_stats
ORDER BY dept_stats.revenue DESC;

[User] Show me each room type with its property name and the number of rooms of that type which are currently 'Occupied'.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS occupied_room_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
JOIN hospitality_technology.rooms r ON r.room_type_id = rt.room_type_id
WHERE r.status = 'Occupied'
GROUP BY rt.type_name, p.property_name;

[User] Only return room types where at least 2 rooms are 'Occupied'.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS occupied_room_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
JOIN hospitality_technology.rooms r ON r.room_type_id = rt.room_type_id
WHERE r.status = 'Occupied'
GROUP BY rt.type_name, p.property_name
HAVING COUNT(r.room_id) >= 2;

[User] Also, sort the results by occupied_room_count in descending order and only include room types at properties in the USA.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS occupied_room_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
JOIN hospitality_technology.rooms r ON r.room_type_id = rt.room_type_id
WHERE r.status = 'Occupied' AND p.country_code = 'USA'
GROUP BY rt.type_name, p.property_name
HAVING COUNT(r.room_id) >= 2
ORDER BY occupied_room_count DESC;

[User] For each reservation, can you show the guest's full name, the property name, and the room number?

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, rm.room_number
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.rooms rm ON r.room_id = rm.room_id;

[User] Also include the check-in and check-out dates for each reservation, and sort the results by check-in date.

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, rm.room_number, r.check_in_date, r.check_out_date
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.rooms rm ON r.room_id = rm.room_id
ORDER BY r.check_in_date;

[User] List all public reviews from the past 30 days with the property name and overall rating.

[Assistant]
SELECT r.review_id, p.property_name, r.rating_overall, r.review_date
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.properties AS p
  ON r.property_id = p.property_id
WHERE r.is_public = TRUE
  AND r.review_date >= CURRENT_DATE - INTERVAL '30 days';

[User] For each reservation, show the reservation ID and the total number of payments made for that reservation.

[Assistant]
SELECT
  r.reservation_id,
  COUNT(p.payment_id) AS payment_count
FROM hospitality_technology.reservations AS r
JOIN hospitality_technology.payments AS p
  ON r.reservation_id = p.reservation_id
GROUP BY
  r.reservation_id;

[User] Only include reservations that have at least 2 payments and show the total amount paid across all payments for each.

[Assistant]
SELECT
  r.reservation_id,
  COUNT(p.payment_id) AS payment_count,
  SUM(p.amount) AS total_amount_paid
FROM hospitality_technology.reservations AS r
JOIN hospitality_technology.payments AS p
  ON r.reservation_id = p.reservation_id
GROUP BY
  r.reservation_id
HAVING
  COUNT(p.payment_id) >= 2;

[User] Actually, show me the reservation ID, property ID, and check-in date for all reservations that have not received any payments.

[Assistant]
SELECT
  r.reservation_id,
  r.property_id,
  r.check_in_date
FROM hospitality_technology.reservations AS r
LEFT JOIN hospitality_technology.payments AS p
  ON r.reservation_id = p.reservation_id
WHERE
  p.payment_id IS NULL;

[User] Provide a list of properties and the total number of reservations made at each property.

[Assistant] SELECT p.property_name, COUNT(r.reservation_id) AS total_reservations FROM hospitality_technology.properties p JOIN hospitality_technology.reservations r ON p.property_id = r.property_id GROUP BY p.property_name;

[User] Now, filter this list to only include properties with a star rating of 4 or higher.

[Assistant] SELECT p.property_name, COUNT(r.reservation_id) AS total_reservations FROM hospitality_technology.properties p JOIN hospitality_technology.reservations r ON p.property_id = r.property_id WHERE p.star_rating >= 4 GROUP BY p.property_name;

[User] Only show those properties that have more than 100 reservations and order them by the number of reservations in descending order.

[Assistant] SELECT p.property_name, COUNT(r.reservation_id) AS total_reservations FROM hospitality_technology.properties p JOIN hospitality_technology.reservations r ON p.property_id = r.property_id WHERE p.star_rating >= 4 GROUP BY p.property_name HAVING COUNT(r.reservation_id) > 100 ORDER BY total_reservations DESC;

[User] List all staff members who have responded to at least one review in the last 6 months, including their first and last names and the count of responses.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, COUNT(r.review_id) AS response_count
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Actually, only include responses to public reviews.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, COUNT(r.review_id) AS response_count
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
  AND r.is_public = TRUE
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Also include the average response time in days for each staff member.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name,
       COUNT(r.review_id) AS response_count,
       AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 86400) AS avg_response_days
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
  AND r.is_public = TRUE
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Show the number of staff members for each property, along with the property name.

[Assistant]
SELECT p.property_name, COUNT(s.staff_id) AS staff_count
FROM hospitality_technology.properties p
JOIN hospitality_technology.staff s ON p.property_id = s.property_id
GROUP BY p.property_name;

[User] Only include properties with more than 20 staff members, and order the result by staff count descending.

[Assistant]
SELECT p.property_name, COUNT(s.staff_id) AS staff_count
FROM hospitality_technology.properties p
JOIN hospitality_technology.staff s ON p.property_id = s.property_id
GROUP BY p.property_name
HAVING COUNT(s.staff_id) > 20
ORDER BY staff_count DESC;

[User] List all properties that have at least one room with 'Ocean View' in its features, showing the property name and the total count of such rooms.

[Assistant] SELECT T1.property_name, COUNT(T2.room_id) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.rooms AS T2 ON T1.property_id = T2.property_id WHERE T2.features LIKE '%Ocean View%' GROUP BY T1.property_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 legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] List pairs of invoices for the same case where one invoice's total_amount is lower than another's; show lower_invoice_number, higher_invoice_number, and case_id.

[Assistant]
SELECT a.invoice_number AS lower_invoice_number,
       b.invoice_number AS higher_invoice_number,
       a.case_id
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.case_id = b.case_id
   AND a.total_amount < b.total_amount;

[User] Please only include cases that have at least two invoices and sort by case_id and lower_invoice_number.

[Assistant]
SELECT a.invoice_number AS lower_invoice_number,
       b.invoice_number AS higher_invoice_number,
       a.case_id
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.case_id = b.case_id
   AND a.total_amount < b.total_amount
 ORDER BY a.case_id, a.invoice_number;

[User] For each client, show the earliest and latest invoice issue_date, along with the total amount invoiced. Include client_id, earliest_issue_date, latest_issue_date, and total_amount.

[Assistant]
SELECT client_id, MIN(issue_date) AS earliest_issue_date, MAX(issue_date) AS latest_issue_date, SUM(total_amount) AS total_amount
FROM legal_services.invoices
GROUP BY client_id;

[User] Show me pairs of invoice numbers for the same case.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id ORDER BY T1.case_id, T1.invoice_number, T2.invoice_number

[User] Only include pairs where the total amount of one invoice is greater than the other.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount ORDER BY T1.case_id, invoice1_amount DESC

[User] Exclude pairs where the issue dates are more than 90 days apart.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount, ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) AS days_apart FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount AND ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) <= 90 ORDER BY T1.case_id, days_apart ASC

[User] Show me all invoice numbers and due dates where the amount paid is exactly zero.

[Assistant] SELECT invoice_number, due_date FROM legal_services.invoices WHERE amount_paid = 0;

[User] Show the count of invoices for each case ID.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id ORDER BY invoice_count DESC

[User] Only include case IDs with more than 2 invoices.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY invoice_count DESC

[User] For these cases, what is the average total amount across all invoices?

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount DESC

[User] Order the results by average total amount ascending.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount ASC

[User] Show me each invoice and the invoice_number of the next invoice for the same client, along with how many days apart their issue_dates are.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date;

[User] Please restrict to pairs where the days_between is greater than 30.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30;

[User] And only include pairs where both invoices have status 'Overdue'.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30
   AND a.status = 'Overdue'
   AND b.status = 'Overdue';

[User] Compute the total invoiced amount and average payment delay (in days) by status for invoices issued between 2024-01-01 and 2024-06-30.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status;

[User] Also show the count of invoices per status.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status;

[User] Exclude statuses where total_invoiced is less than 10000.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status
HAVING SUM(total_amount) >= 10000;

[User] Finally, order the results by avg_payment_delay_days ascending.

[Assistant]
SELECT status,
       SUM(total_amount) AS total_invoiced,
       AVG(EXTRACT(day FROM (payment_date::date - issue_date))) AS avg_payment_delay_days,
       COUNT(*) AS invoice_count
  FROM legal_services.invoices
 WHERE issue_date BETWEEN '2024-01-01' AND '2024-06-30'
 GROUP BY status
HAVING SUM(total_amount) >= 10000
 ORDER BY avg_payment_delay_days ASC;

[User] List all invoice numbers and their total amount for invoices that are overdue. Show the client ID and the due date as well.

[Assistant] SELECT invoice_number, total_amount, client_id, due_date FROM legal_services.invoices WHERE due_date < CURRENT_DATE AND amount_paid < total_amount;

[User] Please also include the number of days each invoice is overdue.

[Assistant] SELECT invoice_number, total_amount, client_id, due_date, (CURRENT_DATE - due_date) AS days_overdue FROM legal_services.invoices WHERE due_date < CURRENT_DATE AND amount_paid < total_amount;

[User] Now, show only those invoices that are overdue by more than 15 days.

[Assistant] SELECT invoice_number, total_amount, client_id, due_date, (CURRENT_DATE - due_date) AS days_overdue FROM legal_services.invoices WHERE due_date < CURRENT_DATE AND amount_paid < total_amount AND (CURRENT_DATE - due_date) > 15;

[User] Add the invoice status to the output and order by days_overdue descending.

[Assistant] SELECT invoice_number, total_amount, client_id, due_date, status, (CURRENT_DATE - due_date) AS days_overdue FROM legal_services.invoices WHERE due_date < CURRENT_DATE AND amount_paid < total_amount AND (CURRENT_DATE - due_date) > 15 ORDER BY days_overdue DESC;

[User] Show me all invoices for case_id 'case_777', including the invoice number, total amount, and status.

[Assistant] SELECT invoice_number, total_amount, status FROM legal_services.invoices WHERE case_id = 'case_777';

[User] I need only those invoices that are unpaid. Can you filter for invoices where the amount_paid is less than the total_amount?

[Assistant] SELECT invoice_number, total_amount, status FROM legal_services.invoices WHERE case_id = 'case_777' AND (amount_paid IS NULL OR amount_paid < total_amount);

[User] Actually, add the due_date and sort the results by due_date ascending.

[Assistant] SELECT invoice_number, total_amount, status, due_date FROM legal_services.invoices WHERE case_id = 'case_777' AND (amount_paid IS NULL OR amount_paid < total_amount) ORDER BY due_date ASC;

[User] Calculate the average total amount for invoices issued in each calendar year.

[Assistant] SELECT EXTRACT(YEAR FROM issue_date) AS issue_year, AVG(total_amount) AS average_total_amount FROM legal_services.invoices GROUP BY EXTRACT(YEAR FROM issue_date) ORDER BY issue_year


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.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
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, 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.integer, cargo_manifest_id.text )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.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, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] Retrieve the passenger_id, first_name, last_name, and total number of bookings each passenger has made in 2023, including only those with at least one booking.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2023-01-01' AND b.booking_time < '2024-01-01'
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 0;

[User] Also, include the sum of fares paid by each passenger and order by total_fares descending.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fares
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2023-01-01' AND b.booking_time < '2024-01-01'
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 0
ORDER BY total_fares DESC;

[User] Show all trips along with the vehicle's make and model, the driver full name, and the route distance in kilometers.

[Assistant]
SELECT t.trip_id, v.make, v.model, d.first_name || ' ' || d.last_name AS driver_full_name, r.distance_km
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.routes r ON t.route_id = r.route_id;

[User] List every maintenance log for each vehicle, including the vehicle's license plate and the mechanic's name.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id;

[User] I want to see only the maintenance logs where the service cost exceeds 500.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500;

[User] Add the odometer reading and sort the results by service date descending.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost, ml.odometer_reading
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500
ORDER BY ml.service_date DESC;

[User] Sorry, actually, I also want to see the recommended next_service_due_date in the output.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost, ml.odometer_reading, ml.next_service_due_date
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500
ORDER BY ml.service_date DESC;

[User] List all fuel refueling events with the refueled vehicle's make and model, the fuel type used, and the fueling location ID.

[Assistant]
SELECT fl.fuel_log_id, fl.log_timestamp, v.make, v.model, fl.fuel_type, fl.quantity, fl.unit, fl.total_cost, fl.location_id
FROM transportation.fuel_logs fl
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_id;

[User] Show the total fare collected from bookings, grouped by the state/province of the destination location of the trip, for bookings made in May 2024.

[Assistant]
SELECT
  l.state_province,
  SUM(b.fare) AS total_fare_collected
FROM transportation.bookings AS b
JOIN transportation.trips AS t
  ON b.trip_id = t.trip_id
JOIN transportation.locations AS l
  ON t.destination_location_id = l.location_id
WHERE
  b.booking_time >= '2024-05-01 00:00:00' AND b.booking_time < '2024-06-01 00:00:00'
GROUP BY
  l.state_province;

[User] Filter this list to only include states/provinces where the total fare collected is greater than 10000 and also include the count of bookings for each of these states. Order the results by total fare descending.

[Assistant]
SELECT
  l.state_province,
  SUM(b.fare) AS total_fare_collected,
  COUNT(b.booking_id) AS booking_count
FROM transportation.bookings AS b
JOIN transportation.trips AS t
  ON b.trip_id = t.trip_id
JOIN transportation.locations AS l
  ON t.destination_location_id = l.location_id
WHERE
  b.booking_time >= '2024-05-01 00:00:00' AND b.booking_time < '2024-06-01 00:00:00'
GROUP BY
  l.state_province
HAVING
  SUM(b.fare) > 10000
ORDER BY
  total_fare_collected DESC;

[User] Retrieve the vehicle_id, make, model, and the next_service_due_date for each vehicle based on the most recent maintenance log.

[Assistant] SELECT DISTINCT ON (ml.vehicle_id) v.vehicle_id, v.make, v.model, ml.next_service_due_date FROM transportation.maintenance_logs ml JOIN transportation.vehicles v ON v.vehicle_id = ml.vehicle_id ORDER BY ml.vehicle_id, ml.service_date DESC;

[User] Now, only include vehicles with status 'Active' and whose next_service_due_date is within the next 30 days, ordering by next_service_due_date ascending.

[Assistant] SELECT v.vehicle_id, v.make, v.model, ml.next_service_due_date FROM transportation.vehicles v JOIN (SELECT DISTINCT ON (vehicle_id) vehicle_id, next_service_due_date FROM transportation.maintenance_logs ORDER BY vehicle_id, service_date DESC) ml ON v.vehicle_id = ml.vehicle_id WHERE v.status = 'Active' AND ml.next_service_due_date BETWEEN current_date AND current_date + INTERVAL '30 days' ORDER BY ml.next_service_due_date ASC;

[User] For each route that originates from a location of type 'Port', list the route number, the name of the origin location, and the total distance accumulated from all completed trips on this route.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name;

[User] Now, only include routes where the accumulated distance is greater than 5000 kilometers and order the results by accumulated distance descending.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000
ORDER BY
  total_accumulated_distance DESC;

[User] Also include the number of completed trips for each of these routes and filter further to only show routes that have had more than 5 completed trips.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance,
  COUNT(t.trip_id) AS completed_trip_count
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000 AND COUNT(t.trip_id) > 5
ORDER BY
  total_accumulated_distance DESC;

[User] For each route, show the route number and the total number of trips associated with it.

[Assistant] SELECT T2.route_number, count(T1.trip_id) FROM transportation.trips AS T1 JOIN transportation.routes AS T2 ON T1.route_id = T2.route_id GROUP BY T2.route_number

[User] Provide each trip's ID, vehicle license plate, driver's full name, origin city, and destination city.

[Assistant]
SELECT t.trip_id,
       v.license_plate,
       CONCAT(d.first_name, ' ', d.last_name) AS driver_name,
       lo.city AS origin_city,
       ld.city AS destination_city
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.locations lo ON t.origin_location_id = lo.location_id
JOIN transportation.locations ld ON t.destination_location_id = ld.location_id;

[User] List maintenance logs including vehicle make, model, service_date, cost, and next_service_due_date for vehicles that are currently 'Active'.

[Assistant]
SELECT ml.log_id,
       v.make,
       v.model,
       ml.service_date,
       ml.cost,
       ml.next_service_due_date
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, 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.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description 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] Find the total number of unique document types stored in the claim_documents table.

[Assistant] SELECT COUNT(DISTINCT document_type) FROM insurance.claim_documents;

[User] For each claim, show the claim ID, incident date, the customer's first and last name, and the policy number under which it was filed.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id;

[User] Filter these results to only include claims reported in the year 2024.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01';

[User] Now, only show claims where the status is 'Settled' or 'Approved', and include the settlement amount.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number, cl.settlement_amount FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved');

[User] For *these* settled or approved claims reported in 2024, find the count of associated claim documents and the total size of those documents. Show the claim ID, customer full name, and the document count and total size.

[Assistant] SELECT cl.claim_id, c.first_name AS customer_first_name, c.last_name AS customer_last_name, COUNT(cd.document_id) AS document_count, SUM(cd.file_size_bytes) AS total_document_size_bytes FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id LEFT JOIN insurance.claim_documents AS cd ON cl.claim_id = cd.claim_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved') GROUP BY cl.claim_id, c.first_name, c.last_name ORDER BY cl.claim_id;

[User] What is the minimum, maximum, and average commission rate among all agents?

[Assistant] SELECT MIN(commission_rate) AS min_commission_rate, MAX(commission_rate) AS max_commission_rate, AVG(commission_rate) AS average_commission_rate FROM insurance.agents;

[User] List policies issued by active agents to customers in the 'CA' state, including policy number, customer's first and last name, agent's first and last name, and the agent's license state.

[Assistant] SELECT p.policy_number, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name, a.license_state FROM insurance.policies AS p JOIN insurance.agents AS a ON p.agent_id = a.agent_id JOIN insurance.customers AS c ON p.customer_id = c.customer_id WHERE a.status = 'Active' AND c.state = 'CA';

[User] Show me the policy number, start date, end date, product name, and product type for all policies.

[Assistant] SELECT T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id

[User] Okay, now only show policies that started after '2023-01-01'.

[Assistant] SELECT T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.start_date > '2023-01-01'

[User] Also include the customer's first and last name in the results.

[Assistant] SELECT T3.first_name, T3.last_name, T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id JOIN insurance.customers AS T3 ON T1.customer_id = T3.customer_id WHERE T1.start_date > '2023-01-01'

[User] Sort the results by policy start date descending and limit to the top 10.

[Assistant] SELECT T3.first_name, T3.last_name, T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id JOIN insurance.customers AS T3 ON T1.customer_id = T3.customer_id WHERE T1.start_date > '2023-01-01' ORDER BY T1.start_date DESC LIMIT 10

[User] Which customers have policies that expired in the last month? Please show the customer ID, policy number, and expiration date.

[Assistant]
SELECT c.customer_id, p.policy_number, p.end_date
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.end_date >= (CURRENT_DATE - INTERVAL '1 month') AND p.end_date < CURRENT_DATE;

[User] Add the customer's email to the results.

[Assistant]
SELECT c.customer_id, c.email, p.policy_number, p.end_date
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.end_date >= (CURRENT_DATE - INTERVAL '1 month') AND p.end_date < CURRENT_DATE;

[User] Show me policies that have at least one overdue premium payment, including policy_number, customer full name, agent_id, due_date, and days overdue.

[Assistant]
SELECT p.policy_number,
       c.first_name || ' ' || c.last_name AS customer_name,
       p.agent_id,
       pp.due_date,
       EXTRACT(day FROM CURRENT_DATE - pp.due_date) AS days_overdue
FROM insurance.policies p
JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id
JOIN insurance.customers c ON p.customer_id = c.customer_id
WHERE pp.status = 'overdue';

[User] Actually, only consider overdue payments by more than 7 days and only active policies.

[Assistant]
SELECT p.policy_number,
       c.first_name || ' ' || c.last_name AS customer_name,
       p.agent_id,
       pp.due_date,
       EXTRACT(day FROM CURRENT_DATE - pp.due_date) AS days_overdue
FROM insurance.policies p
JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id
JOIN insurance.customers c ON p.customer_id = c.customer_id
WHERE pp.status = 'overdue'
  AND p.status = 'active'
  AND EXTRACT(day FROM CURRENT_DATE - pp.due_date) > 7;

[User] Also include the payment_method and label the overdue days column as overdue_days.

[Assistant]
SELECT p.policy_number,
       c.first_name || ' ' || c.last_name AS customer_name,
       p.agent_id,
       pp.payment_method,
       pp.due_date,
       EXTRACT(day FROM CURRENT_DATE - pp.due_date) AS overdue_days
FROM insurance.policies p
JOIN insurance.premium_payments pp ON p.policy_id = pp.policy_id
JOIN insurance.customers c ON p.customer_id = c.customer_id
WHERE pp.status = 'overdue'
  AND p.status = 'active'
  AND EXTRACT(day FROM CURRENT_DATE - pp.due_date) > 7;

[User] Show me claim IDs, incident dates, and file names for all 'Accident Report' claim documents.

[Assistant]
SELECT cd.claim_id, cl.incident_date, cd.file_name
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type = 'Accident Report';

[User] Include both 'Accident Report' and 'Theft Report' document types.

[Assistant]
SELECT cd.claim_id, cl.incident_date, cd.file_name
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type IN ('Accident Report','Theft Report');

[User] Instead of listing each file, show the number of these documents per claim.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type IN ('Accident Report','Theft Report')
GROUP BY cd.claim_id;

[User] Also restrict to claims reported in 2024 and order by document_count descending.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type IN ('Accident Report','Theft Report')
  AND EXTRACT(YEAR FROM cl.reported_date) = 2024
GROUP BY cd.claim_id
ORDER BY document_count DESC;

[User] Show me the first and last names of customers who have purchased a policy for an insurance product of type 'travel', along with the policy number and product name.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, ip.product_name
FROM insurance.policies p
JOIN insurance.customers c ON p.customer_id = c.customer_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE ip.product_type = 'travel';

[User] Add the premium_amount of the policy and the product's base_premium to the result, and only include policies with status 'active'.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, ip.product_name, p.premium_amount, ip.base_premium
FROM insurance.policies p
JOIN insurance.customers c ON p.customer_id = c.customer_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE ip.product_type = 'travel' AND p.status = 'active';

[User] Can you also show only the records where the premium_amount of the policy is greater than the product's base_premium?

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, ip.product_name, p.premium_amount, ip.base_premium
FROM insurance.policies p
JOIN insurance.customers c ON p.customer_id = c.customer_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE ip.product_type = 'travel' AND p.status = 'active' AND p.premium_amount > ip.base_premium;

[User] List all policies where the premium_amount exceeds the base_premium of its insurance product. Display the policy_number, premium_amount, product_name, and base_premium. Sort the results by premium_amount descending.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
ORDER BY p.premium_amount DESC;

[User] Actually, I only want policies that are active and whose insurance products are also active.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
ORDER BY p.premium_amount DESC;

[User] Also, limit the output to policies with a coverage_limit greater than 1000000.

[Assistant]
SELECT p.policy_number, p.premium_amount, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.status = 'active'
  AND ip.is_active = TRUE
  AND p.coverage_limit > 1000000
ORDER BY p.premium_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 gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )

[User] Show the maximum and minimum current_players for each server status.

[Assistant] SELECT status, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status;

[User] Please also provide the total number of servers for each status.

[Assistant] SELECT status, COUNT(*) AS total_servers, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status;

[User] Could you sort the results by total_servers in descending order?

[Assistant] SELECT status, COUNT(*) AS total_servers, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status ORDER BY total_servers DESC;

[User] Can you show me the number of servers in each region, as well as the total max_players for each region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players FROM gaming_technology.servers GROUP BY region;

[User] Actually, can you also include the average number of current players per region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players, AVG(current_players) AS avg_current_players FROM gaming_technology.servers GROUP BY region;

[User] Show me all servers where current_players is 0, and include their server_id, server_name, and region.

[Assistant] SELECT server_id, server_name, region FROM gaming_technology.servers WHERE current_players = 0;

[User] Add the max_players and status columns.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0;

[User] Only show servers where status is not 'offline'.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline';

[User] Now sort the results by region ascending and max_players descending.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline' ORDER BY region ASC, max_players DESC;

[User] List all pairs of servers in the same region that are both 'online', showing server1_name, server2_name, and the absolute difference in current_players.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
WHERE s1.server_id <> s2.server_id
  AND s1.status = 'online'
  AND s2.status = 'online';

[User] Actually, only include each pair once (server1_id < server2_id) and where player_diff is less than 20.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
    AND s1.server_id < s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 20;

[User] Now, only include pairs where both servers have max_players greater than 100.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
    AND s1.server_id < s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 20
  AND s1.max_players > 100
  AND s2.max_players > 100;

[User] Show me all pairs of servers that are located in the same region, listing both server names and their region.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id;

[User] Filter this list to only include pairs where both servers are currently 'online'.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] For these pairs, also show the current_players for both servers.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] Order the results by region ascending, then by the current players of the first server in the pair ascending.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online' ORDER BY s1.region ASC, s1.current_players ASC;

[User] List all server names and their statuses.

[Assistant] SELECT server_name, status FROM gaming_technology.servers;

[User] Can you also include the region and current_players for each server?

[Assistant] SELECT server_name, status, region, current_players FROM gaming_technology.servers;

[User] List all servers that are currently marked with a 'offline' status.

[Assistant] SELECT server_id, server_name, region FROM gaming_technology.servers WHERE status = 'offline';

[User] For those offline servers, please include the server name, region, and calculate how many minutes have passed since their last reported heartbeat.

[Assistant] SELECT server_name, region, EXTRACT(EPOCH FROM (NOW() - last_heartbeat))/60 AS minutes_since_heartbeat FROM gaming_technology.servers WHERE status = 'offline';

[User] Refine the list further to only show offline servers where the last heartbeat was received more than 90 minutes ago.

[Assistant] SELECT server_name, region, EXTRACT(EPOCH FROM (NOW() - last_heartbeat))/60 AS minutes_since_heartbeat FROM gaming_technology.servers WHERE status = 'offline' AND last_heartbeat < NOW() - INTERVAL '90 minutes';

[User] Finally, order these results by how long ago the heartbeat was received, from the oldest heartbeat to the most recent among this filtered group.

[Assistant] SELECT server_name, region, EXTRACT(EPOCH FROM (NOW() - last_heartbeat))/60 AS minutes_since_heartbeat FROM gaming_technology.servers WHERE status = 'offline' AND last_heartbeat < NOW() - INTERVAL '90 minutes' ORDER BY last_heartbeat ASC;

[User] For each game_id and region, show me the server that currently has the highest current_players and the server that has the highest max_players. Return game_id, region, top_current_server_id, top_current_players, top_capacity_server_id, and top_capacity.

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s2
    WHERE s2.game_id = s1.game_id
      AND s2.region = s1.region
      AND s2.current_players > s1.current_players
  )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s4
    WHERE s4.game_id = s3.game_id
      AND s4.region = s3.region
      AND s4.max_players > s3.max_players
  )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region;

[User] Actually, can you also calculate the difference between top_capacity and top_current_players as free_slots_diff?

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s2
    WHERE s2.game_id = s1.game_id
      AND s2.region = s1.region
      AND s2.current_players > s1.current_players
  )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s4
    WHERE s4.game_id = s3.game_id
      AND s4.region = s3.region
      AND s4.max_players > s3.max_players
  )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity,
  (cp.top_capacity - tc.top_current_players) AS free_slots_diff
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region;

[User] Now only include combinations where free_slots_diff is less than 10.

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s2
    WHERE s2.game_id = s1.game_id
      AND s2.region = s1.region
      AND s2.current_players > s1.current_players
  )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s4
    WHERE s4.game_id = s3.game_id
      AND s4.region = s3.region
      AND s4.max_players > s3.max_players
  )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity,
  (cp.top_capacity - tc.top_current_players) AS free_slots_diff
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region
WHERE (cp.top_capacity - tc.top_current_players) < 10;

[User] Also, filter to only include servers with status = 'online'.

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE s1.status = 'online'
    AND NOT EXISTS (
      SELECT 1
      FROM gaming_technology.servers s2
      WHERE s2.game_id = s1.game_id
        AND s2.region = s1.region
        AND s2.current_players > s1.current_players
    )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE s3.status = 'online'
    AND NOT EXISTS (
      SELECT 1
      FROM gaming_technology.servers s4
      WHERE s4.game_id = s3.game_id
        AND s4.region = s3.region
        AND s4.max_players > s3.max_players
    )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity,
  (cp.top_capacity - tc.top_current_players) AS free_slots_diff
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region
WHERE (cp.top_capacity - tc.top_current_players) < 10;

[User] Find pairs of servers that are currently 'online' and share the same game_id, listing their server names and the shared game_id.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] For these pairs, show the sum of their current_players and the sum of their max_players.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id, (s1.current_players + s2.current_players) AS combined_current_players, (s1.max_players + s2.max_players) AS combined_max_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] Order the results by game_id and then by the combined current players in descending order.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id, (s1.current_players + s2.current_players) AS combined_current_players, (s1.max_players + s2.max_players) AS combined_max_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online' ORDER BY s1.game_id, combined_current_players DESC;

[User] Show me pairs of servers in the same region hosting different games where one has at least 100 more current players than the other.

[Assistant]
SELECT s1.server_id AS server1_id,
       s1.server_name AS server1_name,
       s1.region,
       s2.server_id AS server2_id,
       s2.server_name AS server2_name
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
WHERE s1.game_id <> s2.game_id
  AND s1.current_players >= s2.current_players + 100;

[User] Also include the difference in current players between the two servers as player_diff.

[Assistant]
SELECT s1.server_id AS server1_id,
       s1.server_name AS server1_name,
       s1.region,
       s2.server_id AS server2_id,
       s2.server_name AS server2_name,
       (s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
WHERE s1.game_id <> s2.game_id
  AND (s1.current_players - s2.current_players) >= 100;