System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)

[User] Find all pairs of transactions where both transactions have the same nonce and from_address, but different transaction_id. Show both transaction IDs, the shared from_address, shared nonce, and their block numbers.

[Assistant]
SELECT t1.transaction_id AS transaction_id_1, t2.transaction_id AS transaction_id_2, t1.from_address, t1.nonce, t1.block_number AS block_number_1, t2.block_number AS block_number_2
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
 AND t1.nonce = t2.nonce
 AND t1.transaction_id < t2.transaction_id;

[User] Show me all failed transactions where the gas_used is greater than 100,000, including the transaction_id and timestamp.

[Assistant] SELECT transaction_id, timestamp FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000;

[User] Actually, I also need to see the from_address and the value of these transactions.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000;

[User] There's a typo in your SQL, it should be '100000' not '100,000'. Also, sort the results by timestamp in descending order.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 ORDER BY timestamp DESC;

[User] Now filter to only show transactions from the last 30 days.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 AND timestamp >= NOW() - INTERVAL '30 days' ORDER BY timestamp DESC;

[User] Find the top 5 transactions with the highest gas prices, including the from_address, to_address, and block_number, sorted by gas_price in descending order.

[Assistant] SELECT transaction_id, from_address, to_address, block_number, gas_price FROM web3.transactions ORDER BY gas_price DESC LIMIT 5;

[User] Show the average gas_price for each transaction status.

[Assistant]
SELECT status, AVG(gas_price) AS avg_gas_price
FROM web3.transactions
GROUP BY status;

[User] Actually, can you also include the total number of transactions for each status in the result?

[Assistant]
SELECT status, AVG(gas_price) AS avg_gas_price, COUNT(*) AS transaction_count
FROM web3.transactions
GROUP BY status;

[User] List all transactions where the recipient address is not specified (i.e., to_address is NULL), showing transaction_id, from_address, value, and block_number.

[Assistant]
SELECT transaction_id, from_address, value, block_number
FROM web3.transactions
WHERE to_address IS NULL;

[User] In addition, please also include the status of these transactions and sort the results by block_number descending.

[Assistant]
SELECT transaction_id, from_address, value, block_number, status
FROM web3.transactions
WHERE to_address IS NULL
ORDER BY block_number 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.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)

[User] For each property, show the property name, average price of available services, and the maximum price of available services.

[Assistant]
SELECT p.property_name,
       AVG(s.price) AS avg_price,
       MAX(s.price) AS max_price
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_available = true
GROUP BY p.property_name;

[User] Actually, I also need the service_name of the highest priced available service per property.

[Assistant]
SELECT t.property_name,
       t.avg_price,
       s_high.service_name AS highest_priced_service,
       t.max_price
FROM (
    SELECT s.property_id,
           p.property_name,
           AVG(s.price) AS avg_price,
           MAX(s.price) AS max_price
    FROM hospitality_technology.services s
    JOIN hospitality_technology.properties p ON s.property_id = p.property_id
    WHERE s.is_available = true
    GROUP BY s.property_id, p.property_name
) t
JOIN hospitality_technology.services s_high
  ON s_high.property_id = t.property_id
 AND s_high.price = t.max_price
 AND s_high.is_available = true;

[User] Now, only include properties where the average price is above 75 and sort the results by avg_price descending.

[Assistant]
SELECT t.property_name,
       t.avg_price,
       s_high.service_name AS highest_priced_service,
       t.max_price
FROM (
    SELECT s.property_id,
           p.property_name,
           AVG(s.price) AS avg_price,
           MAX(s.price) AS max_price
    FROM hospitality_technology.services s
    JOIN hospitality_technology.properties p ON s.property_id = p.property_id
    WHERE s.is_available = true
    GROUP BY s.property_id, p.property_name
    HAVING AVG(s.price) > 75
) t
JOIN hospitality_technology.services s_high
  ON s_high.property_id = t.property_id
 AND s_high.price = t.max_price
 AND s_high.is_available = true
ORDER BY t.avg_price DESC;

[User] List payment records in USD including guest names and processing staff names.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD';

[User] Only include payments with status 'Succeeded' made within the last 30 days.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD'
  AND p.status = 'Succeeded'
  AND p.payment_timestamp >= NOW() - INTERVAL '30 days';

[User] Sort by payment timestamp descending and limit to 50 records.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD'
  AND p.status = 'Succeeded'
  AND p.payment_timestamp >= NOW() - INTERVAL '30 days'
ORDER BY p.payment_timestamp DESC
LIMIT 50;

[User] List all food and beverage services (category = 'Food & Beverage') with their names, prices, and units, where the price is less than $20.

[Assistant] SELECT service_name, price, unit FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20;

[User] Now, filter these results to only include services that are priced per item (unit = 'Per Item').

[Assistant] SELECT service_name, price, unit FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item';

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

[Assistant] SELECT service_name, price, unit, department FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item';

[User] Actually, I only need services from the 'F&B' department, and order them by price in ascending order.

[Assistant] SELECT service_name, price, unit, department FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item' AND department = 'F&B' ORDER BY price ASC;

[User] Retrieve service_id, service_name, price, and unit for all services in the 'Wellness' category priced between 30 and 100.

[Assistant]
SELECT service_id,
       service_name,
       price,
       unit
FROM hospitality_technology.services
WHERE category = 'Wellness'
  AND price BETWEEN 30 AND 100;

[User] Also only include services that are currently available and order by price ascending.

[Assistant]
SELECT service_id,
       service_name,
       price,
       unit
FROM hospitality_technology.services
WHERE category = 'Wellness'
  AND price BETWEEN 30 AND 100
  AND is_available = true
ORDER BY price ASC;

[User] Show me all available services with a unit of 'Per Hour'.

[Assistant] SELECT service_name ,  description ,  price FROM hospitality_technology.services WHERE is_available  =  true AND unit  =  'Per Hour'

[User] Also include the department and filter the results to only show services priced above 100.

[Assistant] SELECT service_name ,  description ,  price ,  department FROM hospitality_technology.services WHERE is_available  =  true AND unit  =  'Per Hour' AND price  >  100


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )

[User] Can you show the total amount paid and number of payments per citizen in 2024?

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' GROUP BY citizen_id;

[User] Add a filter to only include payments with the status 'Succeeded'.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id;

[User] Now, only show those citizens who have paid more than 1000 in total.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id HAVING SUM(amount) > 1000;

[User] Show the result ordered by total_paid descending and limit to top 10 citizens.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id HAVING SUM(amount) > 1000 ORDER BY total_paid DESC LIMIT 10;

[User] Show me the total payment amount and number of payments for each service.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id;

[User] Only include services where more than 3 payments have been made.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id HAVING COUNT(*) > 3;

[User] For each payment method, show the total number of completed payments and the total amount paid.

[Assistant] SELECT payment_method, COUNT(*) AS completed_count, SUM(amount) AS total_paid FROM government_services.payments WHERE status = 'Completed' GROUP BY payment_method;

[User] Can you show me the total amount paid by each citizen for each service? Please display the citizen_id, service_id, and the total amount.

[Assistant]
SELECT citizen_id, service_id, SUM(amount) AS total_amount
FROM government_services.payments
GROUP BY citizen_id, service_id;

[User] Actually, I only want to see results for payments with status 'Succeeded'.

[Assistant]
SELECT citizen_id, service_id, SUM(amount) AS total_amount
FROM government_services.payments
WHERE status = 'Succeeded'
GROUP BY citizen_id, service_id;

[User] Show me all failed payments along with the application ID, citizen ID, and payment timestamp.

[Assistant]
SELECT payment_id, application_id, citizen_id, payment_timestamp
FROM government_services.payments
WHERE status = 'Failed';


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
Use Hashes. Key pattern: 'inv:<inventory_record_id>'. Example: HSET inv:INVREC500 component_id "component:WINGBOLT" quantity 5000 location_warehouse "WH3" batch_number "BCH778899" ... Consider Sorted Set by expiry date: ZADD component_expiry:<component_id> <expiry_timestamp> <inventory_record_id>.

[User] Can you help me fetch the inventory records for components stored in a specific warehouse, along with their expiry dates?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter this to show only records for a specific component ID?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] What if I want to exclude records with quantities below a certain threshold, like 100?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES
# Note: Filtering by quantity would require additional scripting or client-side processing as Redis does not support direct filtering on hash field values.

[User] Can you also sort the results by expiry date in descending order?

[Assistant]
HGETALL inv:<inventory_record_id>
ZREVRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you help me retrieve the inventory details for a specific component ID, including the quantity and warehouse location?

[Assistant] HGETALL inv:<inventory_record_id>

[User] Can you also include the batch number for that inventory record?

[Assistant] HGETALL inv:<inventory_record_id>

[User] If I want to check the expiry date for this component, how can I retrieve that information?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter the results to show only inventory records with an expiry date after a specific timestamp?

[Assistant] ZRANGEBYSCORE component_expiry:<component_id> <specific_timestamp> +inf WITHSCORES

[User] I need to get the inventory quantity and location for a specific batch number. Can you help with that?

[Assistant] HGETALL inv:<inventory_record_id>

[User] Can you also show me the component ID associated with this batch?

[Assistant] HGETALL inv:<inventory_record_id>

[User] If I want to retrieve multiple inventory records for the same component ID, how can I do that?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1

[User] Can you sort those records by expiry date in ascending order?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] What is the purchase price of the components in a specific batch with batch_number 'BATCH123'?

[Assistant] I'm sorry, but I can't provide information on the purchase price of components as this data is not stored in the component_inventory table. If you have other questions or need assistance with data available in the table, such as quantity or location, I'm happy to help.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )

[User] How many lawyers are there per specialization?

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

[User] Please exclude specializations where lawyer_count is less than 3.

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

[User] Add the average tenure in years (from hire_date to current date) for each specialization.

[Assistant]
SELECT
  specialization,
  COUNT(*) AS lawyer_count,
  AVG(
    EXTRACT(EPOCH FROM (CURRENT_DATE - hire_date)) / (365 * 24 * 3600)
  ) AS avg_tenure_years
FROM legal_services.lawyers
GROUP BY specialization
HAVING COUNT(*) >= 3;

[User] Finally, sort the result by avg_tenure_years descending.

[Assistant]
SELECT
  specialization,
  COUNT(*) AS lawyer_count,
  AVG(
    EXTRACT(EPOCH FROM (CURRENT_DATE - hire_date)) / (365 * 24 * 3600)
  ) AS avg_tenure_years
FROM legal_services.lawyers
GROUP BY specialization
HAVING COUNT(*) >= 3
ORDER BY avg_tenure_years DESC;

[User] List the full name and bar number of all lawyers who were hired before 2015.

[Assistant]
SELECT first_name || ' ' || last_name AS lawyer_full_name, bar_number
FROM legal_services.lawyers
WHERE hire_date < '2015-01-01';

[User] List all clients with the count of cases they have opened.

[Assistant]
SELECT
  c.client_id,
  c.first_name,
  c.last_name,
  COUNT(cs.case_id) AS case_count
FROM legal_services.clients c
LEFT JOIN legal_services.cases cs ON c.client_id = cs.client_id
GROUP BY c.client_id, c.first_name, c.last_name;

[User] Only include clients with at least two cases and show their email too.

[Assistant]
SELECT
  c.client_id,
  c.first_name,
  c.last_name,
  c.email,
  COUNT(cs.case_id) AS case_count
FROM legal_services.clients c
JOIN legal_services.cases cs ON c.client_id = cs.client_id
GROUP BY c.client_id, c.first_name, c.last_name, c.email
HAVING COUNT(cs.case_id) >= 2;

[User] Show me the first and last names of clients along with the first and last names of their lead lawyers for all open cases.

[Assistant]
SELECT c.first_name AS client_first, c.last_name AS client_last, l.first_name AS lawyer_first, l.last_name AS lawyer_last
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE cs.status = 'Open';

[User] Actually, only include cases in the 'Civil Court' jurisdiction.

[Assistant]
SELECT c.first_name AS client_first, c.last_name AS client_last, l.first_name AS lawyer_first, l.last_name AS lawyer_last
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE cs.status = 'Open'
  AND cs.court_jurisdiction = 'Civil Court';

[User] And order the results by client_last ascending.

[Assistant]
SELECT c.first_name AS client_first, c.last_name AS client_last, l.first_name AS lawyer_first, l.last_name AS lawyer_last
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE cs.status = 'Open'
  AND cs.court_jurisdiction = 'Civil Court'
ORDER BY c.last_name ASC;

[User] Which clients have had at least one case led by a lawyer who is a partner? Show the client name, the case name, and the name of the lead lawyer.

[Assistant]
SELECT cl.first_name || ' ' || cl.last_name AS client_name, ca.case_name, l.first_name || ' ' || l.last_name AS lead_lawyer_name
FROM legal_services.cases ca
JOIN legal_services.clients cl ON ca.client_id = cl.client_id
JOIN legal_services.lawyers l ON ca.lead_lawyer_id = l.lawyer_id
WHERE l.is_partner = TRUE;

[User] Actually, can you only show results for cases where the client's status is 'active'?

[Assistant]
SELECT cl.first_name || ' ' || cl.last_name AS client_name, ca.case_name, l.first_name || ' ' || l.last_name AS lead_lawyer_name
FROM legal_services.cases ca
JOIN legal_services.clients cl ON ca.client_id = cl.client_id
JOIN legal_services.lawyers l ON ca.lead_lawyer_id = l.lawyer_id
WHERE l.is_partner = TRUE AND cl.status = 'active';

[User] Add the case_number to the output and sort the results by the client's last name.

[Assistant]
SELECT cl.first_name || ' ' || cl.last_name AS client_name, ca.case_name, ca.case_number, l.first_name || ' ' || l.last_name AS lead_lawyer_name
FROM legal_services.cases ca
JOIN legal_services.clients cl ON ca.client_id = cl.client_id
JOIN legal_services.lawyers l ON ca.lead_lawyer_id = l.lawyer_id
WHERE l.is_partner = TRUE AND cl.status = 'active'
ORDER BY cl.last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )

[User] Show me the names, founding dates, and websites of all law firms whose name contains the word 'Legal' and were founded after the year 2005. Sort the results by their founding date.

[Assistant] SELECT firm_name, founded_date, website FROM legal_services.law_firms WHERE firm_name LIKE '%Legal%' AND founded_date > '2005-12-31' ORDER BY founded_date ASC;

[User] List pairs of law firms that are located at the same address. Display the names of both firms and the shared address, ensuring the address is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL;

[User] Only show pairs where both firms were founded before 2020.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL AND EXTRACT(YEAR FROM t1.founded_date) < 2020 AND EXTRACT(YEAR FROM t2.founded_date) < 2020;

[User] Show me the name and founding date of every law firm.

[Assistant]
SELECT firm_name, founded_date
FROM law_firms;

[User] Also include the firm's phone number.

[Assistant]
SELECT firm_name, phone, founded_date
FROM law_firms;

[User] Exclude any firms that don't have a website specified.

[Assistant]
SELECT firm_name, phone, founded_date
FROM law_firms
WHERE website IS NOT NULL;

[User] Finally, order the list by firm_name in descending order.

[Assistant]
SELECT firm_name, phone, founded_date
FROM law_firms
WHERE website IS NOT NULL
ORDER BY firm_name DESC;

[User] Show the number of law firms founded each year, with the founding year and the count of firms, ordered by year in descending order.

[Assistant] SELECT EXTRACT(YEAR FROM founded_date) AS founding_year, COUNT(*) AS firm_count FROM legal_services.law_firms GROUP BY founding_year ORDER BY founding_year DESC;

[User] Can you provide a list of all law firms, including their address and phone number?

[Assistant] SELECT firm_id, firm_name, address, phone FROM legal_services.law_firms;

[User] I would like to see only those firms founded before 2010.

[Assistant] SELECT firm_id, firm_name, address, phone FROM legal_services.law_firms WHERE founded_date < '2010-01-01';

[User] Filter the list further to include only firms that have a phone number specified.

[Assistant] SELECT firm_id, firm_name, address, phone FROM legal_services.law_firms WHERE founded_date < '2010-01-01' AND phone IS NOT NULL;

[User] Please display the results ordered by firm name alphabetically.

[Assistant] SELECT firm_id, firm_name, address, phone FROM legal_services.law_firms WHERE founded_date < '2010-01-01' AND phone IS NOT NULL ORDER BY firm_name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )

[User] Show me pairs of trip IDs that used the same vehicle.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id;

[User] Now, filter this list to only include pairs where both trips have a 'Completed' status.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id
WHERE
  t1.status = 'Completed' AND t2.status = 'Completed';

[User] Show me the total number of passengers transported by each vehicle in the last week, along with the vehicle ID.

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id;

[User] Can you include the average passenger count per trip for each vehicle as well?

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers, AVG(passenger_count) AS avg_passengers_per_trip FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id;

[User] Now filter to only show vehicles that transported more than 100 passengers total.

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers, AVG(passenger_count) AS avg_passengers_per_trip FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id HAVING SUM(passenger_count) > 100;

[User] What is the count of trips for each status?

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

[User] Only include statuses with more than 5 trips.

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

[User] For each vehicle, list the vehicle_id and the total number of trips it has performed.

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

[User] Can you limit this to only vehicles that have more than 10 trips?

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

[User] In addition, for these vehicles, can you show the driver_id who has driven the highest number of trips for each vehicle?

[Assistant] SELECT vehicle_id, driver_id, trip_driver_count FROM (SELECT vehicle_id, driver_id, COUNT(*) AS trip_driver_count, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY COUNT(*) DESC) as rn FROM transportation.trips GROUP BY vehicle_id, driver_id) t WHERE rn = 1 AND vehicle_id IN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 10);

[User] Find consecutive pairs of trips for each vehicle based on the scheduled departure time.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn;

[User] From these consecutive pairs, only show those where the destination of the first trip matches the origin of the second trip.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn
WHERE
  t1.destination_location_id = t2.origin_location_id;

[User] Also, only include pairs where the time difference between the scheduled departures is less than 24 hours.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn
WHERE
  t1.destination_location_id = t2.origin_location_id
  AND t2.scheduled_departure < t1.scheduled_departure + INTERVAL '24 hour';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] For each user, show their username and the number of unique IP addresses from the peers table where the port is less than 2000.

[Assistant]
SELECT u.username, COUNT(DISTINCT p.ip_address) AS unique_ip_count
FROM trading_platform.users u
JOIN trading_platform.peers p ON u.user_id = p.peer_id
WHERE p.port < 2000
GROUP BY u.username;

[User] This query isn't working because peer_id and user_id don't always match. Could you just show the total number of unique IPs with port < 2000 in the peers table, excluding user data?

[Assistant]
SELECT COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000;

[User] Now, for each port number below 2000, show the count of unique IP addresses using that port.

[Assistant]
SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000
GROUP BY port;

[User] Actually, only show ports where more than one unique IP address exists.

[Assistant]
SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000
GROUP BY port
HAVING COUNT(DISTINCT ip_address) > 1;

[User] List all DApps along with the number of metadata entries linked to each, even if the DApp has no linked metadata.

[Assistant]
SELECT d.name, d.url, COUNT(m.metadata_id) AS metadata_count
FROM trading_platform.dapps d
LEFT JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id
GROUP BY d.dapp_id, d.name, d.url;

[User] For each user, show their username and the total number of completed orders they have placed, along with the name of the asset for each order.

[Assistant]
SELECT u.username, a.name AS asset_name, COUNT(o.order_id) AS completed_order_count
FROM trading_platform.users u
JOIN trading_platform.orders o ON u.user_id = o.user_id
JOIN trading_platform.assets a ON o.asset_id = a.asset_id
WHERE o.status = 'completed'
GROUP BY u.username, a.name;

[User] Actually, only show users who have completed orders for more than one different asset. Please also include their email in the results.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT o.asset_id) AS asset_count
FROM trading_platform.users u
JOIN trading_platform.orders o ON u.user_id = o.user_id
WHERE o.status = 'completed'
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT o.asset_id) > 1;

[User] Show each user's username along with their KYC status and the date of their latest KYC review.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
);

[User] Also filter to only include those whose latest status is 'approved'.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
)
  AND ka.status = 'approved';

[User] For each user, list their user_id, username, the count of log entries in the last 30 days, and the count of unread notifications.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) FILTER (WHERE l.logged_at >= NOW() - INTERVAL '30 days') AS recent_logs,
       COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.logs l ON u.user_id = l.user_id
INNER JOIN trading_platform.notifications n ON u.user_id = n.user_id
GROUP BY u.user_id, u.username;

[User] Filter to only include users who have more than 5 unread notifications.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) FILTER (WHERE l.logged_at >= NOW() - INTERVAL '30 days') AS recent_logs,
       COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.logs l ON u.user_id = l.user_id
INNER JOIN trading_platform.notifications n ON u.user_id = n.user_id
GROUP BY u.user_id, u.username
HAVING COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) > 5;

[User] The query is excluding users with no notifications. Ensure all users are included, showing zero for unread_notifications when none exist.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) FILTER (WHERE l.logged_at >= NOW() - INTERVAL '30 days') AS recent_logs,
       COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.logs l ON u.user_id = l.user_id
LEFT JOIN trading_platform.notifications n ON u.user_id = n.user_id
GROUP BY u.user_id, u.username
HAVING COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) > 5;

[User] Additionally, sort the results by unread_notifications descending and then recent_logs descending.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) FILTER (WHERE l.logged_at >= NOW() - INTERVAL '30 days') AS recent_logs,
       COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.logs l ON u.user_id = l.user_id
LEFT JOIN trading_platform.notifications n ON u.user_id = n.user_id
GROUP BY u.user_id, u.username
HAVING COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) > 5
ORDER BY unread_notifications DESC, recent_logs 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 blockchain.blocks ( block_id text PRIMARY KEY, previous_block_id text, timestamp timestamp, nonce int, merkle_root text, difficulty int )
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )

[User] Show me all smart contracts created by addresses with a balance greater than 1000, along with the contract creation timestamp and the creator's public key.

[Assistant] SELECT sc.contract_id, sc.timestamp, a.public_key FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id WHERE a.balance > 1000;

[User] Now filter these results to only show contracts created in the last 6 months and order them by timestamp in descending order.

[Assistant] SELECT sc.contract_id, sc.timestamp, a.public_key FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id WHERE a.balance > 1000 AND sc.timestamp > NOW() - INTERVAL '6 months' ORDER BY sc.timestamp DESC;

[User] Show me all addresses that have created smart contracts, along with their balance and the count of contracts they've created.

[Assistant] SELECT a.address_id, a.balance, COUNT(sc.contract_id) AS contract_count FROM blockchain.addresses a JOIN blockchain.smart_contracts sc ON a.address_id = sc.creator_address GROUP BY a.address_id, a.balance;

[User] Now filter these results to only show addresses that have created more than 3 contracts and have a balance greater than 500.

[Assistant] SELECT a.address_id, a.balance, COUNT(sc.contract_id) AS contract_count FROM blockchain.addresses a JOIN blockchain.smart_contracts sc ON a.address_id = sc.creator_address WHERE a.balance > 500 GROUP BY a.address_id, a.balance HAVING COUNT(sc.contract_id) > 3;

[User] Can you also include the timestamp of their earliest created contract?

[Assistant] SELECT a.address_id, a.balance, COUNT(sc.contract_id) AS contract_count, MIN(sc.timestamp) AS earliest_contract FROM blockchain.addresses a JOIN blockchain.smart_contracts sc ON a.address_id = sc.creator_address WHERE a.balance > 500 GROUP BY a.address_id, a.balance HAVING COUNT(sc.contract_id) > 3;

[User] Show me the block with the earliest timestamp and its corresponding previous block's difficulty level.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 1;

[User] Now show me the same information but for the 5 earliest blocks instead of just one.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 5;

[User] Find all pairs of distinct block IDs that were mined at the exact same timestamp. Show both block IDs and the shared timestamp.

[Assistant] SELECT t1.block_id AS block_id_1, t2.block_id AS block_id_2, t1.timestamp FROM blockchain.blocks AS t1 JOIN blockchain.blocks AS t2 ON t1.timestamp = t2.timestamp WHERE t1.block_id < t2.block_id;

[User] Show me the earliest created smart contract for each creator address.

[Assistant] SELECT DISTINCT ON (creator_address) contract_id, creator_address, code, timestamp FROM blockchain.smart_contracts ORDER BY creator_address, timestamp ASC;

[User] Now include the total number of contracts each creator has made alongside this information.

[Assistant] WITH earliest_contracts AS (SELECT DISTINCT ON (creator_address) contract_id, creator_address, code, timestamp FROM blockchain.smart_contracts ORDER BY creator_address, timestamp ASC) SELECT ec.*, (SELECT COUNT(*) FROM blockchain.smart_contracts sc WHERE sc.creator_address = ec.creator_address) AS total_contracts FROM earliest_contracts ec;

[User] Filter this to only show creators who have made at least 10 contracts.

[Assistant] WITH earliest_contracts AS (SELECT DISTINCT ON (creator_address) contract_id, creator_address, code, timestamp FROM blockchain.smart_contracts ORDER BY creator_address, timestamp ASC) SELECT ec.*, (SELECT COUNT(*) FROM blockchain.smart_contracts sc WHERE sc.creator_address = ec.creator_address) AS total_contracts FROM earliest_contracts ec WHERE (SELECT COUNT(*) FROM blockchain.smart_contracts sc WHERE sc.creator_address = ec.creator_address) >= 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] For each claim, retrieve the document_id, file_name, and uploaded_at of the earliest and the latest uploaded document.

[Assistant]
SELECT
    c1.claim_id,
    c1.document_id AS earliest_document_id,
    c1.file_name AS earliest_file_name,
    c1.uploaded_at AS earliest_uploaded_at,
    c2.document_id AS latest_document_id,
    c2.file_name AS latest_file_name,
    c2.uploaded_at AS latest_uploaded_at
FROM insurance.claim_documents c1
JOIN insurance.claim_documents c2
  ON c1.claim_id = c2.claim_id
  AND c1.uploaded_at = (
    SELECT MIN(cd.uploaded_at)
    FROM insurance.claim_documents cd
    WHERE cd.claim_id = c1.claim_id
  )
  AND c2.uploaded_at = (
    SELECT MAX(cd.uploaded_at)
    FROM insurance.claim_documents cd
    WHERE cd.claim_id = c2.claim_id
  );

[User] Show me all claim documents that are police reports and were uploaded in the last 30 days, along with their file sizes.

[Assistant] SELECT document_id, claim_id, file_name, file_size_bytes, uploaded_at FROM insurance.claim_documents WHERE document_type = 'police_report' AND uploaded_at >= CURRENT_DATE - INTERVAL '30 days';

[User] Now include only documents that are larger than 1MB and sort them by file size in descending order.

[Assistant] SELECT document_id, claim_id, file_name, file_size_bytes, uploaded_at FROM insurance.claim_documents WHERE document_type = 'police_report' AND uploaded_at >= CURRENT_DATE - INTERVAL '30 days' AND file_size_bytes > 1000000 ORDER BY file_size_bytes DESC;

[User] I also want to see the count of police report documents per claim for these large files.

[Assistant] SELECT claim_id, COUNT(*) AS police_report_count FROM insurance.claim_documents WHERE document_type = 'police_report' AND uploaded_at >= CURRENT_DATE - INTERVAL '30 days' AND file_size_bytes > 1000000 GROUP BY claim_id;

[User] Finally, show me the average file size of these police reports by document type.

[Assistant] SELECT document_type, AVG(file_size_bytes) AS avg_file_size FROM insurance.claim_documents WHERE document_type = 'police_report' AND uploaded_at >= CURRENT_DATE - INTERVAL '30 days' AND file_size_bytes > 1000000 GROUP BY document_type;

[User] I want to find all claim IDs that have both an 'Accident Report' and a 'Police Report' document.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report';

[User] Now, only include those pairs if both documents were uploaded after '2024-06-01'.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01';

[User] Additionally, ensure that both files are larger than 500 KB.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01'
  AND a.file_size_bytes > 512000
  AND b.file_size_bytes > 512000;

[User] Finally, show me the file_name and uploaded_by for both document types in the results.

[Assistant]
SELECT
    a.claim_id,
    a.file_name       AS accident_file_name,
    a.uploaded_by     AS accident_uploaded_by,
    b.file_name       AS police_file_name,
    b.uploaded_by     AS police_uploaded_by
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01'
  AND a.file_size_bytes > 512000
  AND b.file_size_bytes > 512000;

[User] List pairs of documents uploaded by the same user for the same claim. Return uploaded_by, claim_id, document_id AS doc1_id, and the paired document_id AS doc2_id.

[Assistant]
SELECT cd1.uploaded_by,
       cd1.claim_id,
       cd1.document_id AS doc1_id,
       cd2.document_id AS doc2_id
FROM insurance.claim_documents cd1
JOIN insurance.claim_documents cd2
  ON cd1.claim_id = cd2.claim_id
 AND cd1.uploaded_by = cd2.uploaded_by
 AND cd1.document_id < cd2.document_id;

[User] Filter to only include pairs where the two documents have different mime_types.

[Assistant]
SELECT cd1.uploaded_by,
       cd1.claim_id,
       cd1.document_id AS doc1_id,
       cd2.document_id AS doc2_id
FROM insurance.claim_documents cd1
JOIN insurance.claim_documents cd2
  ON cd1.claim_id = cd2.claim_id
 AND cd1.uploaded_by = cd2.uploaded_by
 AND cd1.document_id < cd2.document_id
WHERE cd1.mime_type <> cd2.mime_type;

[User] List all unique document types available in the system.

[Assistant] SELECT DISTINCT document_type FROM insurance.claim_documents;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
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) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Which patients have a primary insurance policy and are subscribed to a plan provided by 'Cigna'? List patient ID, full name, policy number, plan ID, and insurance provider.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pi.policy_number, pi.plan_id, ip.insurance_provider
FROM healthcare.patient_insurance pi
JOIN healthcare.patients p ON pi.patient_id = p.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE pi.is_primary = true AND ip.insurance_provider = 'Cigna';

[User] Additionally, only show results where the policy has not expired yet.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pi.policy_number, pi.plan_id, ip.insurance_provider
FROM healthcare.patient_insurance pi
JOIN healthcare.patients p ON pi.patient_id = p.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE pi.is_primary = true AND ip.insurance_provider = 'Cigna' AND (pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_DATE);

[User] List all prescriptions with the corresponding patient's emergency contact name and phone number. Show prescription ID, patient full name, emergency contact name, and emergency contact phone.

[Assistant]
SELECT pr.prescription_id, p.first_name, p.last_name, p.emergency_contact_name, p.emergency_contact_phone
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id;

[User] Only include prescriptions where the emergency contact phone is not null and sort the results by the patient's last name.

[Assistant]
SELECT pr.prescription_id, p.first_name, p.last_name, p.emergency_contact_name, p.emergency_contact_phone
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
WHERE p.emergency_contact_phone IS NOT NULL
ORDER BY p.last_name ASC;

[User] Show me a list of all patients and the doctors who have made diagnoses for them. For each, include patient ID, patient full name, doctor ID, and doctor full name.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, d.doctor_id, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.doctors d ON diag.doctor_id = d.doctor_id;

[User] Can you narrow this down to only include diagnoses with the code type 'ICD-10'?

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, d.doctor_id, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.doctors d ON diag.doctor_id = d.doctor_id
WHERE diag.code_type = 'ICD-10';

[User] Also, sort the results by doctor last name, then patient first name.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, d.doctor_id, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.doctors d ON diag.doctor_id = d.doctor_id
WHERE diag.code_type = 'ICD-10'
ORDER BY d.last_name ASC, p.first_name ASC;

[User] List all diagnoses made in the last month including diagnosis_date, patient full name, doctor's full name, and description.

[Assistant]
SELECT d.diagnosis_date,
       p.first_name || ' ' || p.last_name AS patient_name,
       doc.first_name || ' ' || doc.last_name AS doctor_name,
       d.description
FROM healthcare.diagnoses AS d
JOIN healthcare.patients AS p
  ON d.patient_id = p.patient_id
JOIN healthcare.doctors AS doc
  ON d.doctor_id = doc.doctor_id
WHERE d.diagnosis_date >= CURRENT_DATE - INTERVAL '1 month';

[User] List patient ID, first name, last name, policy number, and plan name for all patient insurance policies that are not primary and expire after the year 2025.

[Assistant] SELECT p.patient_id, p.first_name, p.last_name, pi.policy_number, ip.plan_name FROM healthcare.patients p JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND pi.expiration_date > '2025-12-31';

[User] Sort the results by expiration date ascending.

[Assistant] SELECT p.patient_id, p.first_name, p.last_name, pi.policy_number, ip.plan_name FROM healthcare.patients p JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE pi.is_primary = false AND pi.expiration_date > '2025-12-31' ORDER BY pi.expiration_date 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
// PUT /schedules
{
  "mappings": {
    "properties": {
      "schedule_id": { "type": "keyword" },
      "train_id": { "type": "keyword" }, // References trains index
      "route_id": { "type": "keyword" }, // References routes index
      "departure_datetime": { "type": "date" }, // ISO 8601 format recommended
      "arrival_datetime": { "type": "date" },
      "status": { "type": "keyword" },
      "notes": { "type": "text" }
    }
  }
}
// PUT /passengers
{
  "mappings": {
    "properties": {
      "passenger_id": { "type": "keyword" },
      "first_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
      },
      "last_name": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 100 } }
       },
      "email": { "type": "keyword" }, // Often used for exact matches
      "phone_number": { "type": "keyword" },
      "date_of_birth": { "type": "date", "format": "yyyy-MM-dd" },
      "loyalty_program_id": { "type": "keyword" },
      "created_at": { "type": "date" }
    }
  }
}

[User] 能否帮我查询特定列车行程(schedule_id 为 'sched_001')的详细信息，包括列车出发和到达时间，以及该行程所属路线的ID和相关乘客信息？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001';

[User] 能否将结果限制在状态为‘Scheduled’的行程上，并且只显示乘客的姓名和电子邮件？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled';

[User] 能否再加入行程的备注信息，并按出发时间降序排列？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, s.notes, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled'
ORDER BY s.departure_datetime DESC;

[User] 如果没有关联的乘客信息，能否只显示行程信息？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, s.notes, p.passenger_id, p.first_name, p.last_name, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.schedule_id = 'sched_001' AND s.status = 'Scheduled'
ORDER BY s.departure_datetime DESC;

[User] 能否帮我查询特定路线(route_id 为 'RT001')的所有行程信息，并关联到乘客的联系方式？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001';

[User] 能否只显示状态为‘On Time’的行程，并按出发时间升序排列？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001' AND s.status = 'On Time'
ORDER BY s.departure_datetime ASC;

[User] 如果乘客信息为空，能否仍然显示行程信息，并限制结果前10条？

[Assistant]
SELECT s.schedule_id, s.train_id, s.route_id, s.departure_datetime, s.arrival_datetime, s.status, p.passenger_id, p.first_name, p.last_name, p.phone_number, p.email
FROM schedules s
LEFT JOIN passengers p ON s.schedule_id = (SELECT schedule_id FROM bookings WHERE passenger_id = p.passenger_id)
WHERE s.route_id = 'RT001' AND s.status = 'On Time'
ORDER BY s.departure_datetime ASC
LIMIT 10;

[User] 能否帮我统计数据库中所有乘客的数量，按忠诚计划ID分组？

[Assistant]
SELECT loyalty_program_id, COUNT(*) as passenger_count
FROM passengers
GROUP BY loyalty_program_id;

[User] Can you help me find all schedules for a specific route with route_id 'RT789' that includes the train details and the departure times?

[Assistant]
SELECT s.schedule_id, s.departure_datetime, s.arrival_datetime, s.status, t.train_id
FROM schedules s
JOIN train_cars t ON s.train_id = t.train_id
WHERE s.route_id = 'RT789';

[User] Can you filter the results to show only schedules with a status of 'Delayed'?

[Assistant]
SELECT s.schedule_id, s.departure_datetime, s.arrival_datetime, s.status, t.train_id
FROM schedules s
JOIN train_cars t ON s.train_id = t.train_id
WHERE s.route_id = 'RT789' AND s.status = 'Delayed';

[User] Can you also include the origin and destination station names for the route in the results?

[Assistant]
SELECT s.schedule_id, s.departure_datetime, s.arrival_datetime, s.status, t.train_id,
       os.station_name AS origin_station, ds.station_name AS destination_station
FROM schedules s
JOIN train_cars t ON s.train_id = t.train_id
JOIN routes r ON s.route_id = r.route_id
JOIN stations os ON r.origin_station_id = os.station_id
JOIN stations ds ON r.destination_station_id = ds.station_id
WHERE s.route_id = 'RT789' AND s.status = 'Delayed';

[User] Can you provide the total capacity of all train cars for a specific train with train_id 'TR789'?

[Assistant]
SELECT SUM(capacity) AS total_capacity
FROM train_cars
WHERE train_id = 'TR789';


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.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id, next_appointment_id, and the waiting time in minutes between them.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   );

[User] Now include only the pairs where the waiting time is less than 30 minutes.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   )
WHERE EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 < 30;

[User] Can you give me the total number of appointments grouped by status?

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

[User] Filter the result to show only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS total_appointments
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;

[User] I need to identify overlapping appointments for each doctor. Return doctor_id, the first appointment_id, the overlapping appointment_id, and the overlap start time.

[Assistant]
SELECT A.doctor_id,
       A.appointment_id AS a1,
       B.appointment_id AS a2,
       GREATEST(A.appointment_time, B.appointment_time) AS overlap_start
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.doctor_id = B.doctor_id
 AND A.appointment_id < B.appointment_id
 AND A.appointment_time < B.appointment_time + B.duration_minutes * INTERVAL '1 minute'
 AND B.appointment_time < A.appointment_time + A.duration_minutes * INTERVAL '1 minute';

[User] Actually, I only care about overlaps that last more than 15 minutes.

[Assistant]
SELECT A.doctor_id,
       A.appointment_id AS a1,
       B.appointment_id AS a2,
       GREATEST(A.appointment_time, B.appointment_time) AS overlap_start
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.doctor_id = B.doctor_id
 AND A.appointment_id < B.appointment_id
 AND A.appointment_time < B.appointment_time + B.duration_minutes * INTERVAL '1 minute'
 AND B.appointment_time < A.appointment_time + A.duration_minutes * INTERVAL '1 minute'
 AND (LEAST(A.appointment_time + A.duration_minutes * INTERVAL '1 minute',
            B.appointment_time + B.duration_minutes * INTERVAL '1 minute')
      - GREATEST(A.appointment_time, B.appointment_time)) > INTERVAL '15 minutes';

[User] Also, exclude any appointments that have a status of 'Cancelled'.

[Assistant]
SELECT A.doctor_id,
       A.appointment_id AS a1,
       B.appointment_id AS a2,
       GREATEST(A.appointment_time, B.appointment_time) AS overlap_start
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.doctor_id = B.doctor_id
 AND A.appointment_id < B.appointment_id
 AND A.appointment_time < B.appointment_time + B.duration_minutes * INTERVAL '1 minute'
 AND B.appointment_time < A.appointment_time + A.duration_minutes * INTERVAL '1 minute'
 AND (LEAST(A.appointment_time + A.duration_minutes * INTERVAL '1 minute',
            B.appointment_time + B.duration_minutes * INTERVAL '1 minute')
      - GREATEST(A.appointment_time, B.appointment_time)) > INTERVAL '15 minutes'
WHERE A.status <> 'Cancelled'
  AND B.status <> 'Cancelled';

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id AS current_appointment, next_appointment_id, and waiting_time in minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 ) ;

[User] Only include waiting times less than 30 minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 )
WHERE EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 < 30;

[User] Get the total number of appointments grouped by status.

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

[User] Now filter to include only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )

[User] Show me the total quantity traded and total amount for each security, identified by its ticker symbol, for trades in the last month.

[Assistant] SELECT T2.ticker_symbol, SUM(T1.quantity), SUM(T1.total_amount) FROM financial_services.trades AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.trade_timestamp >= DATE('now', '-1 month') GROUP BY 1

[User] Can you also show the average price per unit and filter to only include securities where the total quantity traded is greater than 5000?

[Assistant] SELECT T2.ticker_symbol, SUM(T1.quantity), SUM(T1.total_amount), AVG(T1.price_per_unit) FROM financial_services.trades AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.trade_timestamp >= DATE('now', '-1 month') GROUP BY 1 HAVING SUM(T1.quantity) > 5000

[User] List each account number and the total quantity of shares traded through it.

[Assistant] SELECT T2.account_number, SUM(T1.quantity) FROM financial_services.trades AS T1 JOIN financial_services.accounts AS T2 ON T1.account_id = T2.account_id GROUP BY 1

[User] Only include accounts with total quantity traded greater than 1000, and order the results by total quantity descending.

[Assistant] SELECT T2.account_number, SUM(T1.quantity) AS total_traded_quantity FROM financial_services.trades AS T1 JOIN financial_services.accounts AS T2 ON T1.account_id = T2.account_id GROUP BY 1 HAVING SUM(T1.quantity) > 1000 ORDER BY total_traded_quantity DESC

[User] What is the total commission earned from all trades executed in the 'NYSE' venue by employees in the 'Investment' department?

[Assistant] SELECT SUM(t.commission) AS total_commission FROM financial_services.trades t JOIN financial_services.employees e ON t.account_id = e.employee_id WHERE t.execution_venue = 'NYSE' AND e.department = 'Investment';

[User] Show the average current_principal_balance for each loan_type, and include the number of active loans per type.

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

[User] Exclude loan_types where the average balance is below 50,000.

[Assistant]
SELECT loan_type,
       COUNT(*) AS active_loan_count,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING AVG(current_principal_balance) >= 50000;

[User] Also include the account_number and interest_rate for individual loans that are above this threshold.

[Assistant]
SELECT l.loan_id,
       a.account_number,
       l.current_principal_balance,
       l.interest_rate
FROM financial_services.loans l
JOIN financial_services.accounts a
  ON l.account_id = a.account_id
WHERE l.status = 'Active'
  AND l.current_principal_balance >= 50000;

[User] Find pairs of BUY and SELL trades from the trades table for the same account that occurred on the same settlement_date and had matching quantities.

[Assistant]
SELECT
  a.trade_id AS buy_trade_id,
  b.trade_id AS sell_trade_id,
  a.account_id,
  a.settlement_date,
  a.quantity
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.account_id = b.account_id
  AND a.settlement_date = b.settlement_date
  AND a.quantity = b.quantity
WHERE a.trade_type = 'BUY'
  AND b.trade_type = 'SELL';

[User] Only include pairs where the execution_venue is different between the two trades.

[Assistant]
SELECT
  a.trade_id AS buy_trade_id,
  b.trade_id AS sell_trade_id,
  a.account_id,
  a.settlement_date,
  a.quantity
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.account_id = b.account_id
  AND a.settlement_date = b.settlement_date
  AND a.quantity = b.quantity
WHERE a.trade_type = 'BUY'
  AND b.trade_type = 'SELL'
  AND a.execution_venue <> b.execution_venue;

[User] Sort the results by account_id ascending and settlement_date descending.

[Assistant]
SELECT
  a.trade_id AS buy_trade_id,
  b.trade_id AS sell_trade_id,
  a.account_id,
  a.settlement_date,
  a.quantity
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.account_id = b.account_id
  AND a.settlement_date = b.settlement_date
  AND a.quantity = b.quantity
WHERE a.trade_type = 'BUY'
  AND b.trade_type = 'SELL'
  AND a.execution_venue <> b.execution_venue
ORDER BY a.account_id ASC, a.settlement_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)

[User] Show me all securities (security_id, ticker_symbol, security_name) that are traded on the NASDAQ exchange and belong to the 'Technology' sector, along with the employees (employee_id, first_name, last_name) who work in the 'Investment' department and were hired in the last 3 years.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, e.employee_id, e.first_name, e.last_name FROM financial_services.securities s CROSS JOIN financial_services.employees e WHERE s.exchange = 'NASDAQ' AND s.sector = 'Technology' AND e.department = 'Investment' AND e.hire_date >= CURRENT_DATE - INTERVAL '3 years' AND e.status = 'Active';

[User] Now modify the query to only include securities with a ticker_symbol starting with 'A' and sort the results by security_name in ascending order.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, e.employee_id, e.first_name, e.last_name FROM financial_services.securities s CROSS JOIN financial_services.employees e WHERE s.exchange = 'NASDAQ' AND s.sector = 'Technology' AND s.ticker_symbol LIKE 'A%' AND e.department = 'Investment' AND e.hire_date >= CURRENT_DATE - INTERVAL '3 years' AND e.status = 'Active' ORDER BY s.security_name ASC;

[User] List the ticker_symbol and average close price for all securities of type 'ETF'.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol;

[User] Sort the result by average close price descending.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol
ORDER BY avg_close_price DESC;

[User] List pairs of securities that trade on different exchanges but belong to the same sector, showing ticker_symbol of both as symbol_a and symbol_b, their exchanges, and the sector.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.ticker_symbol < b.ticker_symbol;

[User] Actually, exclude any pairs where the sector is NULL and ensure uniqueness by requiring symbol_a < symbol_b.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.ticker_symbol < b.ticker_symbol;

[User] Now also order the results by sector ascending and symbol_a ascending.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.ticker_symbol < b.ticker_symbol
ORDER BY a.sector ASC, a.ticker_symbol ASC;

[User] Finally, only include pairs where both securities are denominated in USD.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.currency = 'USD'
  AND b.currency = 'USD'
  AND a.ticker_symbol < b.ticker_symbol
ORDER BY a.sector ASC, a.ticker_symbol ASC;

[User] For each sector, retrieve the ticker symbol and last_updated timestamp of the earliest and latest updated securities, labeling them as earliest_ticker, earliest_updated, latest_ticker, and latest_updated.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated;

[User] Actually, only include sectors where the time span between latest_updated and earliest_updated exceeds 30 days.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
  HAVING MAX(last_updated) - MIN(last_updated) > INTERVAL '30 days'
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated;

[User] Now order the results by the time span descending.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
  HAVING MAX(last_updated) - MIN(last_updated) > INTERVAL '30 days'
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated,
  ss.latest_updated - ss.earliest_updated AS time_span
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated
ORDER BY time_span DESC;

[User] Show me all securities listed on the 'NYSE' exchange with their ticker symbol and most recent close price.

[Assistant]
SELECT s.security_name, s.ticker_symbol, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE' AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
);

[User] Only include securities where the close price is below 30.

[Assistant]
SELECT s.security_name, s.ticker_symbol, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE'
  AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
  )
  AND md.close_price < 30;

[User] Please add the sector information to the result as well.

[Assistant]
SELECT s.security_name, s.ticker_symbol, s.sector, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE'
  AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
  )
  AND md.close_price < 30;


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.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )

[User] Can you list the number of items for each rarity in the system?

[Assistant]
SELECT rarity, COUNT(*) AS item_count
FROM gaming_technology.in_game_items
GROUP BY rarity;

[User] Please only show rarities with at least 3 items.

[Assistant]
SELECT rarity, COUNT(*) AS item_count
FROM gaming_technology.in_game_items
GROUP BY rarity
HAVING COUNT(*) >= 3;

[User] Can you also display the minimum, maximum, and average cost amount for each rarity?

[Assistant]
SELECT rarity, COUNT(*) AS item_count, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost
FROM gaming_technology.in_game_items
GROUP BY rarity
HAVING COUNT(*) >= 3;

[User] Can you show me the total number of items and the average cost amount for each item type and rarity combination?

[Assistant]
SELECT item_type, rarity, COUNT(*) AS total_items, AVG(cost_amount) AS avg_cost_amount
FROM gaming_technology.in_game_items
GROUP BY item_type, rarity;

[User] Could you filter the results to only include item_type and rarity groups where there are more than 2 items?

[Assistant]
SELECT item_type, rarity, COUNT(*) AS total_items, AVG(cost_amount) AS avg_cost_amount
FROM gaming_technology.in_game_items
GROUP BY item_type, rarity
HAVING COUNT(*) > 2;

[User] Now only show results where the average cost amount is greater than 100.

[Assistant]
SELECT item_type, rarity, COUNT(*) AS total_items, AVG(cost_amount) AS avg_cost_amount
FROM gaming_technology.in_game_items
GROUP BY item_type, rarity
HAVING COUNT(*) > 2 AND AVG(cost_amount) > 100;

[User] Can you order the results by avg_cost_amount descending?

[Assistant]
SELECT item_type, rarity, COUNT(*) AS total_items, AVG(cost_amount) AS avg_cost_amount
FROM gaming_technology.in_game_items
GROUP BY item_type, rarity
HAVING COUNT(*) > 2 AND AVG(cost_amount) > 100
ORDER BY avg_cost_amount DESC;

[User] List each item_type along with the average cost_amount.

[Assistant]
SELECT item_type, AVG(cost_amount) AS avg_cost
FROM gaming_technology.in_game_items
GROUP BY item_type;

[User] Now only include types where the average cost_amount is greater than 1000.

[Assistant]
SELECT item_type, AVG(cost_amount) AS avg_cost
FROM gaming_technology.in_game_items
GROUP BY item_type
HAVING AVG(cost_amount) > 1000;

[User] Also sort the results by avg_cost in ascending order.

[Assistant]
SELECT item_type, AVG(cost_amount) AS avg_cost
FROM gaming_technology.in_game_items
GROUP BY item_type
HAVING AVG(cost_amount) > 1000
ORDER BY avg_cost ASC;

[User] Finally, limit the output to the top 3 item_types.

[Assistant]
SELECT item_type, AVG(cost_amount) AS avg_cost
FROM gaming_technology.in_game_items
GROUP BY item_type
HAVING AVG(cost_amount) > 1000
ORDER BY avg_cost ASC
LIMIT 3;

[User] I need pairs of items within the same game where one item_type is 'Weapon' and the other is 'Consumable'. Show game_id, weapon_name, and consumable_name.

[Assistant]
SELECT i1.game_id, i1.item_name AS weapon_name, i2.item_name AS consumable_name
FROM gaming_technology.in_game_items i1
JOIN gaming_technology.in_game_items i2 ON i1.game_id = i2.game_id AND i1.item_type = 'Weapon' AND i2.item_type = 'Consumable';

[User] Actually, I only want pairs where both items are of 'Epic' rarity.

[Assistant]
SELECT i1.game_id, i1.item_name AS weapon_name, i2.item_name AS consumable_name
FROM gaming_technology.in_game_items i1
JOIN gaming_technology.in_game_items i2 ON i1.game_id = i2.game_id
  AND i1.item_type = 'Weapon' AND i2.item_type = 'Consumable'
  AND i1.rarity = 'Epic' AND i2.rarity = 'Epic';

[User] Can you show me the number of unique item types and the average cost amount for each game?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS unique_item_types, AVG(cost_amount) AS avg_cost_amount FROM gaming_technology.in_game_items GROUP BY game_id;

[User] Actually, can you also include the item rarity with the highest average cost for each game?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS unique_item_types, AVG(cost_amount) AS avg_cost_amount, (SELECT rarity FROM gaming_technology.in_game_items i2 WHERE i2.game_id = i1.game_id GROUP BY rarity ORDER BY AVG(cost_amount) DESC LIMIT 1) AS highest_avg_cost_rarity FROM gaming_technology.in_game_items i1 GROUP BY game_id;

[User] Limit the results to games that have at least 3 different item types.

[Assistant] SELECT game_id, unique_item_types, avg_cost_amount, highest_avg_cost_rarity FROM (SELECT game_id, COUNT(DISTINCT item_type) AS unique_item_types, AVG(cost_amount) AS avg_cost_amount, (SELECT rarity FROM gaming_technology.in_game_items i2 WHERE i2.game_id = i1.game_id GROUP BY rarity ORDER BY AVG(cost_amount) DESC LIMIT 1) AS highest_avg_cost_rarity FROM gaming_technology.in_game_items i1 GROUP BY game_id) sub WHERE unique_item_types >= 3;

[User] Order the results by average cost amount in descending order.

[Assistant] SELECT game_id, unique_item_types, avg_cost_amount, highest_avg_cost_rarity FROM (SELECT game_id, COUNT(DISTINCT item_type) AS unique_item_types, AVG(cost_amount) AS avg_cost_amount, (SELECT rarity FROM gaming_technology.in_game_items i2 WHERE i2.game_id = i1.game_id GROUP BY rarity ORDER BY AVG(cost_amount) DESC LIMIT 1) AS highest_avg_cost_rarity FROM gaming_technology.in_game_items i1 GROUP BY game_id) sub WHERE unique_item_types >= 3 ORDER BY avg_cost_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 social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] List usernames and email addresses of users who have enabled both email and push notifications.

[Assistant] SELECT T1.username, T1.email FROM social_media.users AS T1 INNER JOIN social_media.user_settings AS T2 ON T1.user_id = T2.user_id WHERE T2.email_notifications_enabled = TRUE AND T2.push_notifications_enabled = TRUE;

[User] List all hashtags and for each, show how many different users have created posts using that hashtag.

[Assistant]
SELECT ph.hashtag_id, COUNT(DISTINCT p.user_id) AS unique_user_count
FROM social_media.post_hashtags ph
JOIN social_media.posts p ON ph.post_id = p.post_id
GROUP BY ph.hashtag_id;

[User] Only include hashtags used by at least 3 users.

[Assistant]
SELECT ph.hashtag_id, COUNT(DISTINCT p.user_id) AS unique_user_count
FROM social_media.post_hashtags ph
JOIN social_media.posts p ON ph.post_id = p.post_id
GROUP BY ph.hashtag_id
HAVING COUNT(DISTINCT p.user_id) >= 3;

[User] Show the number of followers for each user who is following others, listing their user_id and follower count.

[Assistant]
SELECT following_user_id AS user_id, COUNT(follower_user_id) AS follower_count
FROM social_media.follows
GROUP BY following_user_id;

[User] List the five earliest hashtags created in 2024 along with their names.

[Assistant]
SELECT hashtag_id, tag_name, created_at
FROM social_media.hashtags
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
ORDER BY created_at ASC
LIMIT 5;

[User] For all posts created between '2024-03-01' and '2024-03-31', show the post_id, content, and the author's full_name.

[Assistant]
SELECT p.post_id, p.content, u.full_name
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
WHERE p.created_at >= '2024-03-01' AND p.created_at < '2024-04-01';

[User] Now limit to posts with media_type = 'image'.

[Assistant]
SELECT p.post_id, p.content, u.full_name
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id
WHERE p.created_at >= '2024-03-01'
  AND p.created_at < '2024-04-01'
  AND p.media_type = 'image';