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.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] List the number of bookings for each day.

[Assistant]
SELECT DATE(booking_time) AS booking_date, COUNT(*) AS booking_count
FROM transportation.bookings
GROUP BY DATE(booking_time);

[User] Now only include days where booking_count > 10.

[Assistant]
SELECT DATE(booking_time) AS booking_date, COUNT(*) AS booking_count
FROM transportation.bookings
GROUP BY DATE(booking_time)
HAVING COUNT(*) > 10;

[User] Also include the total fare collected for those days.

[Assistant]
SELECT DATE(booking_time) AS booking_date,
       COUNT(*) AS booking_count,
       SUM(fare) AS total_fare
FROM transportation.bookings
GROUP BY DATE(booking_time)
HAVING COUNT(*) > 10;

[User] List pairs of bookings made for the same trip, showing booking IDs and their booking_time.

[Assistant]
SELECT b1.booking_id AS booking1,
       b2.booking_id AS booking2,
       b1.trip_id,
       b1.booking_time AS time1,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
  AND b1.booking_id < b2.booking_id;

[User] Actually, only include pairs where the time difference between bookings is less than 2 hours.

[Assistant]
SELECT b1.booking_id AS booking1,
       b2.booking_id AS booking2,
       b1.trip_id,
       b1.booking_time AS time1,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
  AND b1.booking_id < b2.booking_id
WHERE ABS(EXTRACT(EPOCH FROM (b2.booking_time - b1.booking_time))) < 2 * 3600;

[User] Also calculate the difference in minutes between the two booking_time values as diff_minutes.

[Assistant]
SELECT b1.booking_id AS booking1,
       b2.booking_id AS booking2,
       b1.trip_id,
       b1.booking_time AS time1,
       b2.booking_time AS time2,
       ROUND(ABS(EXTRACT(EPOCH FROM (b2.booking_time - b1.booking_time))) / 60, 2) AS diff_minutes
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
  AND b1.booking_id < b2.booking_id
WHERE ABS(EXTRACT(EPOCH FROM (b2.booking_time - b1.booking_time))) < 2 * 3600;

[User] Find all pairs of bookings that share the same payment_transaction_id.

[Assistant]
SELECT b1.booking_id AS booking_id_1, b2.booking_id AS booking_id_2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
 AND b1.booking_id < b2.booking_id;

[User] Now limit the results to pairs where both bookings have status 'Completed'.

[Assistant]
SELECT b1.booking_id AS booking_id_1, b2.booking_id AS booking_id_2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
 AND b1.booking_id < b2.booking_id
WHERE b1.status = 'Completed'
  AND b2.status = 'Completed';

[User] What are the average and maximum fare amounts for each booking status?

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status;

[User] Only include statuses where the average fare is greater than 50.

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status
HAVING AVG(fare) > 50;

[User] List each booking with its previous booking time for the same passenger.

[Assistant]
SELECT b.booking_id,
       b.passenger_id,
       b.booking_time,
       LAG(b.booking_time) OVER (PARTITION BY b.passenger_id ORDER BY b.booking_time) AS previous_booking_time
FROM transportation.bookings b;

[User] I only want records where the gap between bookings is more than 7 days.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';

[User] Also include the total number of bookings for each passenger.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time,
       COUNT(*) OVER (PARTITION BY passenger_id) AS total_bookings
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';

[User] List all booking IDs and their status for bookings that have a special request recorded.

[Assistant]
SELECT booking_id, status
FROM transportation.bookings
WHERE special_requests IS NOT NULL;

[User] Also show passenger_id and the booking_time for these bookings. Only include bookings where the special request contains the word 'meal'.

[Assistant]
SELECT booking_id, passenger_id, status, booking_time
FROM transportation.bookings
WHERE special_requests ILIKE '%meal%';

[User] Order the results by booking_time in descending order and limit the output to the 10 most recent matches.

[Assistant]
SELECT booking_id, passenger_id, status, booking_time
FROM transportation.bookings
WHERE special_requests ILIKE '%meal%'
ORDER BY booking_time DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks (
    block_id character varying(64) NOT NULL,  -- unique identifier for the block
    previous_block_id character varying(64), -- identifier of the previous block
    timestamp timestamp NOT NULL, -- time when the block was mined
    nonce integer NOT NULL, -- nonce value used in the proof of work
    merkle_root character varying(128) NOT NULL, -- root of the Merkle tree for transactions
    difficulty integer NOT NULL, -- difficulty level of the block
    PRIMARY KEY (block_id)
)

[User] Show me the average difficulty for blocks that have a previous block versus those that don't have a previous block.

[Assistant] SELECT CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY block_type;

[User] Now break this down further by year, showing the yearly averages for each block type.

[Assistant] SELECT EXTRACT(YEAR FROM timestamp) AS year, CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY year, block_type ORDER BY year;

[User] Can you also include the count of blocks for each year and type combination?

[Assistant] SELECT EXTRACT(YEAR FROM timestamp) AS year, CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, COUNT(*) AS block_count, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY year, block_type ORDER BY year;

[User] Retrieve the block ID, timestamp, current block's difficulty, and the difficulty of the *previous* block for all blocks where the current block's difficulty is strictly greater than the previous block's difficulty.

[Assistant] SELECT b1.block_id, b1.timestamp, b1.difficulty AS current_difficulty, b2.difficulty AS previous_difficulty FROM blockchain.blocks b1 JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id WHERE b1.difficulty > b2.difficulty;

[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 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 smart contract IDs and the block IDs that were mined within 5 minutes before or after the contract deployment timestamp.

[Assistant] SELECT T1.contract_id, T2.block_id FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute';

[User] Also include the timestamp for both the contract deployment and the block mining.

[Assistant] SELECT T1.contract_id, T1.timestamp AS contract_timestamp, T2.block_id, T2.timestamp AS block_timestamp FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute';

[User] Filter the results to only include contracts deployed in the year 2023.

[Assistant] SELECT T1.contract_id, T1.timestamp AS contract_timestamp, T2.block_id, T2.timestamp AS block_timestamp FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute' WHERE EXTRACT(YEAR FROM T1.timestamp) = 2023;

[User] Order the results by contract ID and then by block ID.

[Assistant] SELECT T1.contract_id, T1.timestamp AS contract_timestamp, T2.block_id, T2.timestamp AS block_timestamp FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute' WHERE EXTRACT(YEAR FROM T1.timestamp) = 2023 ORDER BY T1.contract_id, T2.block_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )

[User] What is the average USD value per address for each narrative across all chains?

[Assistant]
SELECT
  narrative,
  AVG(usd_value / NULLIF(address_amount, 0)) AS avg_usd_per_address
FROM smart_money_token_inflow
GROUP BY narrative;

[User] List the top 5 tokens by total USD inflow and outflow, including net flow, sorted by net flow descending.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net_flow AS (
  SELECT
    i.token_symbol,
    i.chain,
    COALESCE(i.usd_in, 0) AS usd_in,
    COALESCE(o.usd_out, 0) AS usd_out,
    COALESCE(i.usd_in, 0) - COALESCE(o.usd_out, 0) AS net_flow
  FROM inflow i
  LEFT JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, usd_in, usd_out, net_flow
FROM net_flow
ORDER BY net_flow DESC
LIMIT 5;

[User] Now filter the results to only include tokens where net flow is positive.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net_flow AS (
  SELECT
    i.token_symbol,
    i.chain,
    COALESCE(i.usd_in, 0) AS usd_in,
    COALESCE(o.usd_out, 0) AS usd_out,
    COALESCE(i.usd_in, 0) - COALESCE(o.usd_out, 0) AS net_flow
  FROM inflow i
  LEFT JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, usd_in, usd_out, net_flow
FROM net_flow
WHERE net_flow > 0
ORDER BY net_flow DESC
LIMIT 5;

[User] For each chain, find the token with the highest net USD inflow (buys minus sells). Show token_symbol, chain, and net_inflow.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net AS (
  SELECT
    COALESCE(i.token_symbol, o.token_symbol) AS token_symbol,
    COALESCE(i.chain, o.chain) AS chain,
    COALESCE(i.usd_in, 0) - COALESCE(o.usd_out, 0) AS net_inflow
  FROM inflow i
  FULL JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, net_inflow
FROM (
  SELECT
    token_symbol,
    chain,
    net_inflow,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY net_inflow DESC) AS rn
  FROM net
) sub
WHERE rn = 1;

[User] Only include tokens that were involved in at least 10 distinct addresses for buy transactions.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in, SUM(address_amount) AS addr_count
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net AS (
  SELECT
    i.token_symbol,
    i.chain,
    i.usd_in - COALESCE(o.usd_out, 0) AS net_inflow,
    i.addr_count
  FROM inflow i
  LEFT JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, net_inflow
FROM (
  SELECT
    token_symbol,
    chain,
    net_inflow,
    addr_count,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY net_inflow DESC) AS rn
  FROM net
) sub
WHERE rn = 1
  AND addr_count >= 10;

[User] List tokens with net outflow (type=2) on the 'Ethereum' chain. Show token_symbol and total usd_value sold.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol;

[User] Now limit to tokens with total_sold above 10000 and order by total_sold descending.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol
HAVING SUM(usd_value) > 10000
ORDER BY total_sold DESC;

[User] Which chain has the highest total USD inflow from buy transactions (type=1), and how many distinct tokens were involved in that inflow?

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY total_inflow DESC
LIMIT 1;

[User] I also want to see the average price at which those tokens were bought for that chain.

[Assistant]
WITH inflow AS (
  SELECT chain, SUM(usd_value) AS total_inflow
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY chain
), top_chain AS (
  SELECT chain FROM inflow ORDER BY total_inflow DESC LIMIT 1
)
SELECT i.chain, AVG(i.avg_price) AS avg_buy_price
FROM smart_money_token_inflow i
JOIN top_chain t ON i.chain = t.chain
WHERE i.type = 1;

[User] Actually, filter to narratives where the total USD inflow is above 50000.

[Assistant]
SELECT narrative, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY narrative
HAVING SUM(usd_value) > 50000;

[User] Please order the results by average price descending and show the top 2 chains.

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens, AVG(avg_price) AS avg_buy_price
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY avg_buy_price DESC
LIMIT 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )

[User] Give me the list of DApp names and URLs whose description contains any asset symbol from the assets table.

[Assistant]
SELECT DISTINCT d.name, d.url
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%';

[User] Could you also add the matching asset symbol in the result?

[Assistant]
SELECT DISTINCT d.name AS dapp_name, d.url, a.symbol AS asset_symbol
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%';

[User] Show only those DApps where the description contains more than one different asset symbol.

[Assistant]
SELECT d.name AS dapp_name, d.url, COUNT(DISTINCT a.symbol) AS asset_symbol_count
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name, d.url
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Now show for each such DApp: its name, URL, and the comma-separated list of matching asset symbols.

[Assistant]
SELECT d.name AS dapp_name, d.url, STRING_AGG(DISTINCT a.symbol, ', ') AS asset_symbols
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name, d.url
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Show the names, symbols, and types of all assets whose symbol starts with the letter 'B'.

[Assistant]
SELECT name, symbol, type
FROM trading_platform.assets
WHERE symbol LIKE 'B%';

[User] How many distinct IP addresses have ever connected as peers on the platform?

[Assistant]
SELECT COUNT(DISTINCT ip_address) AS distinct_ip_count
FROM trading_platform.peers;

[User] Show the total number of notifications sent per user.

[Assistant]
SELECT user_id, COUNT(*) AS total_notifications
FROM trading_platform.notifications
GROUP BY user_id;

[User] I only want to see users who have received at least 3 notifications, and include the date of their most recent notification.

[Assistant]
SELECT user_id, COUNT(*) AS total_notifications, MAX(sent_at) AS latest_notification
FROM trading_platform.notifications
GROUP BY user_id
HAVING COUNT(*) >= 3;

[User] Instead, please show only those users who have at least 3 unread notifications and sort by number of unread notifications descending.

[Assistant]
SELECT user_id, COUNT(*) AS unread_notifications, MAX(sent_at) AS latest_unread
FROM trading_platform.notifications
WHERE read_at IS NULL
GROUP BY user_id
HAVING COUNT(*) >= 3
ORDER BY unread_notifications DESC;

[User] Show only the top 2 users by unread notifications.

[Assistant]
SELECT user_id, COUNT(*) AS unread_notifications, MAX(sent_at) AS latest_unread
FROM trading_platform.notifications
WHERE read_at IS NULL
GROUP BY user_id
HAVING COUNT(*) >= 3
ORDER BY unread_notifications DESC
LIMIT 2;

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

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

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

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

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

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

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

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

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

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


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.customers ( customer_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, ssn_hash character varying(128), address text NOT NULL, city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, status character varying(32) NOT NULL, risk_profile character varying(50), PRIMARY KEY (customer_id) )
CREATE TABLE financial_services.transactions ( transaction_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, related_account_id character varying(64), transaction_type character varying(50) NOT NULL, amount numeric(19, 4) NOT NULL, currency character varying(3) NOT NULL, transaction_date timestamp NOT NULL, effective_date date NOT NULL, description text, status character varying(32) NOT NULL, reference_number character varying(128), PRIMARY KEY (transaction_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id) )
CREATE TABLE financial_services.securities ( security_id character varying(64) NOT NULL, ticker_symbol character varying(20) NOT NULL UNIQUE, isin_code character varying(12) UNIQUE, cusip_code character varying(9) UNIQUE, security_name text NOT NULL, security_type character varying(50) NOT NULL, exchange character varying(50), currency character varying(3) NOT NULL, issuer_name character varying(255), sector character varying(100), last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (security_id) )
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) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )

[User] List all customers and the total amount they have traded, showing their full name, email, and the total across all their trades. Join customers to their accounts, then to trades.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
GROUP BY c.customer_id, c.first_name, c.last_name, c.email;

[User] Please include only trades with a status of 'EXECUTED' in the calculation.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
WHERE t.status = 'EXECUTED'
GROUP BY c.customer_id, c.first_name, c.last_name, c.email;

[User] Only show customers whose total_trade_amount is greater than 5000.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
WHERE t.status = 'EXECUTED'
GROUP BY c.customer_id, c.first_name, c.last_name, c.email
HAVING SUM(t.total_amount) > 5000;

[User] Sort the result by total_trade_amount in descending order and limit to the first 10 results.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
WHERE t.status = 'EXECUTED'
GROUP BY c.customer_id, c.first_name, c.last_name, c.email
HAVING SUM(t.total_amount) > 5000
ORDER BY total_trade_amount DESC
LIMIT 10;

[User] List each security and the total amount traded for it, with ticker symbol and security name. Only include trades from the last 90 days.

[Assistant]
SELECT s.ticker_symbol, s.security_name, SUM(t.total_amount) AS total_traded_amount
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
GROUP BY s.ticker_symbol, s.security_name;

[User] Also include the number of distinct accounts involved in trades for each security during this period.

[Assistant]
SELECT s.ticker_symbol, s.security_name, SUM(t.total_amount) AS total_traded_amount, COUNT(DISTINCT t.account_id) AS account_count
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
GROUP BY s.ticker_symbol, s.security_name;

[User] Only display securities where the account_count is greater than 5, and sort by total_traded_amount descending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, SUM(t.total_amount) AS total_traded_amount, COUNT(DISTINCT t.account_id) AS account_count
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
GROUP BY s.ticker_symbol, s.security_name
HAVING COUNT(DISTINCT t.account_id) > 5
ORDER BY total_traded_amount DESC;

[User] I need a summary of total traded volume and average price per unit by sector using the trades and securities tables for trades in the last 30 days.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
GROUP BY s.sector;

[User] Only include sectors where the summed quantity is at least 1000.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
GROUP BY s.sector
HAVING SUM(t.quantity) >= 1000;

[User] Sort the result by average price per unit ascending.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
GROUP BY s.sector
HAVING SUM(t.quantity) >= 1000
ORDER BY avg_price_per_unit ASC;

[User] Also ensure sectors are not null.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
  AND s.sector IS NOT NULL
GROUP BY s.sector
HAVING SUM(t.quantity) >= 1000
ORDER BY avg_price_per_unit ASC;

[User] Show me all loans with matching collateral, displaying loan_id, principal_amount, the collateral ticker, and its sector.

[Assistant]
SELECT
  l.loan_id,
  l.principal_amount,
  s.ticker_symbol,
  s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol;

[User] Filter this to loans with status 'Active' and securities of type 'Bond'.

[Assistant]
SELECT
  l.loan_id,
  l.principal_amount,
  s.ticker_symbol,
  s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol
WHERE l.status = 'Active'
  AND s.security_type = 'Bond';

[User] Finally, sort by maturity_date ascending and limit the result to the first 10 rows.

[Assistant]
SELECT
  l.loan_id,
  l.principal_amount,
  s.ticker_symbol,
  s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol
WHERE l.status = 'Active'
  AND s.security_type = 'Bond'
ORDER BY l.maturity_date ASC
LIMIT 10;

[User] List each employee and their manager's full name, showing employee_id, employee full name, and manager full name.

[Assistant]
SELECT
  e.employee_id,
  e.first_name || ' ' || e.last_name AS employee_name,
  m.first_name || ' ' || m.last_name AS manager_name
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Only include active employees and exclude those without a manager.

[Assistant]
SELECT
  e.employee_id,
  e.first_name || ' ' || e.last_name AS employee_name,
  m.first_name || ' ' || m.last_name AS manager_name
FROM financial_services.employees e
JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.status = 'Active'
  AND e.manager_id IS NOT NULL;

[User] Now sort the output by department ascending and then by employee_name ascending.

[Assistant]
SELECT
  e.employee_id,
  e.first_name || ' ' || e.last_name AS employee_name,
  m.first_name || ' ' || m.last_name AS manager_name
FROM financial_services.employees e
JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.status = 'Active'
  AND e.manager_id IS NOT NULL
ORDER BY e.department ASC, employee_name ASC;

[User] Summarize the total principal amount for loans, grouped by customer and their account type. Include the customer's full name.

[Assistant] SELECT T1.first_name, T1.last_name, T2.account_type, SUM(T3.principal_amount) FROM financial_services.customers AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id = T2.customer_id JOIN financial_services.loans AS T3 ON T2.account_id = T3.account_id GROUP BY T1.customer_id, T1.first_name, T1.last_name, T2.account_type;

[User] Only include accounts and loans that are currently 'Active'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.account_type, SUM(T3.principal_amount) FROM financial_services.customers AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id = T2.customer_id JOIN financial_services.loans AS T3 ON T2.account_id = T3.account_id WHERE T2.status = 'Active' AND T3.status = 'Active' GROUP BY T1.customer_id, T1.first_name, T1.last_name, T2.account_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )

[User] List all time entries that do not have a description, including the entry ID, date worked, hours spent, and the first and last name of the lawyer who recorded the entry.

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

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

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

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

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

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

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

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

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

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

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

[User] Only include entries that have been billed.

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

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

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

[User] Please order the results by total_billed_amount descending.

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )

[User] List all payments processed in USD, showing payment_id, guest_id, amount, and payment_timestamp.

[Assistant]
SELECT payment_id,
       guest_id,
       amount,
       payment_timestamp
FROM hospitality_technology.payments
WHERE currency_code = 'USD';

[User] Actually, only include those with amount greater than 1000.

[Assistant]
SELECT payment_id,
       guest_id,
       amount,
       payment_timestamp
FROM hospitality_technology.payments
WHERE currency_code = 'USD'
  AND amount > 1000;

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

[Assistant]
SELECT payment_id,
       guest_id,
       amount,
       payment_timestamp
FROM hospitality_technology.payments
WHERE currency_code = 'USD'
  AND amount > 1000
ORDER BY amount DESC
LIMIT 5;

[User] Show me all payments made with a credit card (payment_method = 'credit_card') where the amount is greater than $500, including the reservation ID and payment timestamp.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 ORDER BY payment_timestamp DESC;

[User] Now, include only payments that were processed by staff members with ID starting with 'STAFF1' and show the card type used.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp, card_type FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 AND staff_id_processed LIKE 'STAFF1%' ORDER BY payment_timestamp DESC;

[User] Show the total payment amount grouped by currency_code and filtered to only include payments with status 'Pending' or 'Failed'.

[Assistant] SELECT currency_code, SUM(amount) AS total_amount FROM hospitality_technology.payments WHERE status IN ('Pending', 'Failed') GROUP BY currency_code;

[User] Actually, please break down the result further by payment method as well.

[Assistant] SELECT currency_code, payment_method, SUM(amount) AS total_amount FROM hospitality_technology.payments WHERE status IN ('Pending', 'Failed') GROUP BY currency_code, payment_method;

[User] Can you also count the number of distinct guests for each combination of currency_code and payment_method in the result?

[Assistant] SELECT currency_code, payment_method, SUM(amount) AS total_amount, COUNT(DISTINCT guest_id) AS guest_count FROM hospitality_technology.payments WHERE status IN ('Pending', 'Failed') GROUP BY currency_code, payment_method;

[User] Show the total payment amount and the number of payments processed by each staff member, including their staff_id_processed.

[Assistant] SELECT staff_id_processed, SUM(amount) AS total_payment_amount, COUNT(payment_id) AS payment_count FROM hospitality_technology.payments GROUP BY staff_id_processed;

[User] Show the total amount of payments processed by each payment_method.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
GROUP BY payment_method;

[User] Include only payments with status 'Succeeded' or 'Pending', and order by total_amount descending.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
WHERE status IN ('Succeeded', 'Pending')
GROUP BY payment_method
ORDER BY total_amount DESC;

[User] For each payment, list its payment_id, guest_id, payment_timestamp, and the next payment_id and next payment_timestamp made by the same guest.

[Assistant]
SELECT p.payment_id,
       p.guest_id,
       p.payment_timestamp,
       n.payment_id AS next_payment_id,
       n.payment_timestamp AS next_payment_timestamp
FROM hospitality_technology.payments p
LEFT JOIN hospitality_technology.payments n
  ON p.guest_id = n.guest_id
 AND n.payment_timestamp = (
       SELECT MIN(payment_timestamp)
       FROM hospitality_technology.payments
       WHERE guest_id = p.guest_id
         AND payment_timestamp > p.payment_timestamp
     );


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[Assistant] SELECT trip_id, origin_location_id, destination_location_id, route_id FROM transportation.trips WHERE origin_location_id <> destination_location_id;

[User] For each origin and destination location pair, provide the total number of trips along with the average actual_arrival time.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id;

[User] Can you also filter this to only include pairs where the trip count is greater than 3?

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;

[User] Instead of the epoch average, show the average difference (in minutes) between scheduled_arrival and actual_arrival for these pairs.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival - scheduled_arrival)/60.0) AS avg_delay_minutes FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;


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.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)

[User] Show the number of claims filed for each distinct status, ordered by the count in descending order.

[Assistant]
SELECT status, COUNT(*) AS claim_count
FROM insurance.claims
GROUP BY status
ORDER BY claim_count DESC;

[User] List each claim_handler_id along with the number of claims they've handled and the total settlement_amount they've paid out.

[Assistant]
SELECT claim_handler_id,
       COUNT(*) AS total_claims,
       SUM(settlement_amount) AS total_settlement
FROM insurance.claims
GROUP BY claim_handler_id;

[User] In addition, include the claim_id of the single claim with the highest settlement_amount for each handler.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

[User] Only include handlers who have managed at least 3 claims and have a non-null claim_handler_id.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

[User] Finally, sort the results by total_settlement in descending order.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  )
ORDER BY ag.total_settlement DESC;

[User] Calculate the average number of days between when an incident occurred and when the claim was reported, but only for claims that were settled in the year 2023.

[Assistant]
SELECT
  AVG(EXTRACT(EPOCH FROM (reported_date - incident_date)) / 86400.0)::numeric(10, 2)
FROM
  insurance.claims
WHERE
  settlement_date IS NOT NULL AND EXTRACT(YEAR FROM settlement_date) = 2023;

[User] What is the average estimated_loss for claims with status 'Filed' or 'Approved'?

[Assistant]
SELECT AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
WHERE status IN ('Filed', 'Approved');

[User] List the claim ID, policy ID, reported date, and settlement date for claims that have been processed by a claim handler.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL;

[User] Actually, only show claims where the settlement date is not null as well.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL;

[User] Now, filter to only include claims settled after January 1, 2024.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01';

[User] Also, add a column showing the number of days between the reported date and the settlement date, and sort results by that column in descending order.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date,
       (settlement_date - reported_date::date) AS days_to_settle
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01'
ORDER BY days_to_settle DESC;

[User] How many agents are currently active in each license state?

[Assistant]
SELECT license_state, COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] Find all top-level agencies that do not have a parent agency. Display their agency_id and agency_name.

[Assistant]
SELECT agency_id, agency_name
FROM government_services.agencies
WHERE parent_agency_id IS NULL;

[User] Find currently employed employees whose direct manager has been terminated. Display the employee's full name, hire date, manager's full name, and manager's termination date.

[Assistant]
SELECT e.employee_id,
       CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name,
       e.hire_date,
       CONCAT(m.first_name, ' ', m.last_name) AS manager_full_name,
       m.termination_date
FROM government_services.employees e
JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE e.termination_date IS NULL
  AND m.termination_date IS NOT NULL;

[User] For all appointments scheduled after '2024-07-01', list the appointment ID, the full name of the citizen, the location name, and the city.

[Assistant]
SELECT a.appointment_id,
       CONCAT(c.first_name, ' ', c.last_name) AS citizen_full_name,
       l.location_name,
       l.city
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.service_locations l ON a.location_id = l.location_id
WHERE a.scheduled_start_time > '2024-07-01';

[User] List the full name of employees and the names of the agencies they work for, but only for employees who are currently employed.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS employee_full_name, a.agency_name
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
WHERE e.termination_date IS NULL;

[User] Show the payment ID, amount, and payment method for all payments made in USD with an amount greater than 50.

[Assistant]
SELECT payment_id, amount, payment_method
FROM government_services.payments
WHERE currency = 'USD' AND amount > 50;

[User] For each service, show the service name and the total number of applications submitted for it.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS total_applications
FROM government_services.services s
LEFT JOIN government_services.applications a ON s.service_id = a.service_id
GROUP BY s.service_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 transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] Show me the first name, last name, and email address for all passengers who are part of the loyalty program with ID 'Gold'.

[Assistant] SELECT first_name ,  last_name ,  email FROM transportation.passengers WHERE loyalty_program_id  =  'Gold'

[User] Now, narrow this list to only include those passengers whose record was created after January 1, 2023.

[Assistant] SELECT first_name ,  last_name ,  email FROM transportation.passengers WHERE loyalty_program_id  =  'Gold' AND created_at  >  '2023-01-01'

[User] For each vehicle that appears in both the maintenance logs and fuel logs tables, calculate the total maintenance cost and the total fuel cost. Display the vehicle ID and these two total costs.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(T2.total_cost) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id

[User] Now, only include vehicles where the total maintenance cost exceeds 5000.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(T2.total_cost) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id HAVING SUM(T1.cost)  >  5000

[User] Also, only consider fuel log entries from the year 2023 for the fuel cost calculation.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(CASE WHEN STRFTIME('%Y', T2.log_timestamp) = '2023' THEN T2.total_cost ELSE 0 END) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id HAVING SUM(T1.cost)  >  5000

[User] Show the total number of maintenance logs for each vehicle along with the vehicle's make and model.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(m.log_id) AS maintenance_count
FROM transportation.vehicles v
LEFT JOIN transportation.maintenance_logs m ON v.vehicle_id = m.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model;

[User] List all bookings with the first and last name of the passenger and trip_id.

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Add the date when the booking was made and the booking status.

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Filter to only show bookings where the status is either 'Pending' or 'Confirmed'.

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status IN ('Pending', 'Confirmed');

[User] Can you sort the results by booking_time in descending order and limit to the 10 most recent?

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status IN ('Pending', 'Confirmed')
ORDER BY b.booking_time DESC
LIMIT 10;

[User] For each trip, can you show the trip_id, number of passengers, and the make and model of the assigned vehicle?

[Assistant]
SELECT b.trip_id, COUNT(b.passenger_id) AS passenger_count, v.make, v.model
FROM transportation.bookings b
JOIN transportation.vehicles v ON b.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs WHERE vehicle_id = v.vehicle_id
)
GROUP BY b.trip_id, v.make, v.model;

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
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 )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_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, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_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, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] Show me all male patients who have received more than one prescription, including their full name, date of birth, and the total number of prescriptions.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Could you also include the names of the medications they've been prescribed?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Actually, I only want to see patients who also have at least one active diagnosis.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(DISTINCT pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] One of the medication_ids columns seems off, could you instead also show the medication_id and dosage for each prescription individually, as well as the diagnosis_code for their active diagnosis?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, pr.prescription_id, pr.medication_id, pr.dosage, d.diagnosis_code
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active';

[User] Show all prescriptions made in 2024 for medications prescribed during appointments scheduled at location 'LOC001', including prescription_id, patient_id, medication_id, and appointment_time.

[Assistant]
SELECT pr.prescription_id, pr.patient_id, pr.medication_id, ap.appointment_time
FROM healthcare.prescriptions pr
JOIN healthcare.medical_records mr ON pr.record_id = mr.record_id
JOIN healthcare.appointments ap ON mr.appointment_id = ap.appointment_id
WHERE ap.location_id = 'LOC001'
  AND EXTRACT(YEAR FROM pr.prescription_date) = 2024;

[User] List the contact phone and website for all insurance plans provided by 'Continental Health'.

[Assistant]
SELECT plan_name, contact_phone, website
FROM healthcare.insurance_plans
WHERE insurance_provider = 'Continental Health';

[User] List all medical record IDs and the record date for records created by doctors specializing in 'Gastroenterology'.

[Assistant] SELECT mr.record_id, mr.record_date FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id WHERE d.specialty = 'Gastroenterology';

[User] Could you also include the patient's first and last name for these records?

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology';

[User] Now, only show records for male patients.

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male';

[User] Additionally, restrict the results to medical records that have at least one associated diagnosis with status 'Resolved'.

[Assistant] SELECT DISTINCT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id JOIN healthcare.diagnoses diag ON mr.record_id = diag.record_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male' AND diag.status = 'Resolved';

[User] What is the average number of refills allowed across all prescriptions?

[Assistant] SELECT AVG(refills_allowed) FROM healthcare.prescriptions;

[User] List each chronic active diagnosis along with the prescribed medication details, showing diagnosis_id, diagnosis_code, medication_id, dosage, and diagnosis_date.

[Assistant] SELECT d.diagnosis_id, d.diagnosis_code, p.medication_id, p.dosage, d.diagnosis_date FROM healthcare.diagnoses d JOIN healthcare.prescriptions p ON d.record_id = p.record_id AND d.patient_id = p.patient_id WHERE d.is_chronic = TRUE AND d.status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.loans (
    loan_id character varying(64) NOT NULL, -- unique identifier for the loan, could be same as account_id
    account_id character varying(64) NOT NULL UNIQUE, -- link to the general account record
    loan_type character varying(50) NOT NULL, -- e.g., Mortgage, Personal, Auto, Student
    principal_amount numeric(19, 4) NOT NULL, -- original loan amount
    current_principal_balance numeric(19, 4) NOT NULL, -- remaining principal
    interest_rate numeric(6, 4) NOT NULL, -- annual interest rate
    term_months integer NOT NULL, -- loan term in months
    origination_date date NOT NULL, -- date the loan was disbursed
    maturity_date date NOT NULL, -- date the loan is due to be fully repaid
    monthly_payment numeric(12, 4), -- scheduled monthly payment amount
    collateral_description text, -- description of collateral, if secured loan
    status character varying(32) NOT NULL, -- e.g., Active, Paid Off, Defaulted
    PRIMARY KEY (loan_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id)
)

[User] Retrieve all pairs of loans for the same account where both loans are active and have different loan types. Show account_id, loan_id as loan_a, loan_type as type_a, loan_id as loan_b, and loan_type as type_b.

[Assistant]
SELECT a.account_id,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type;

[User] Actually, only include pairs where loan_a has a higher principal_amount than loan_b.

[Assistant]
SELECT a.account_id,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type
  AND a.principal_amount > b.principal_amount;

[User] Now restrict to accounts where the total number of active loans is at least 3.

[Assistant]
SELECT a.account_id,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type
  AND a.principal_amount > b.principal_amount
  AND a.account_id IN (
    SELECT account_id
    FROM financial_services.loans
    WHERE status = 'Active'
    GROUP BY account_id
    HAVING COUNT(*) >= 3
  );

[User] Finally, also include the number of active loans for each account as loan_count.

[Assistant]
WITH active_counts AS (
  SELECT account_id,
         COUNT(*) AS loan_count
  FROM financial_services.loans
  WHERE status = 'Active'
  GROUP BY account_id
)
SELECT a.account_id,
       ac.loan_count,
       a.loan_id AS loan_a,
       a.loan_type AS type_a,
       b.loan_id AS loan_b,
       b.loan_type AS type_b
FROM financial_services.loans a
JOIN financial_services.loans b
  ON a.account_id = b.account_id
 AND a.loan_id < b.loan_id
JOIN active_counts ac
  ON a.account_id = ac.account_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
  AND a.loan_type <> b.loan_type
  AND a.principal_amount > b.principal_amount
  AND ac.loan_count >= 3;

[User] For each account opening year, I'd like the total principal amount of loans and the count of loans. Please join loans with accounts.

[Assistant]
SELECT EXTRACT(YEAR FROM a.created_at) AS open_year,
       SUM(l.principal_amount) AS total_principal,
       COUNT(*) AS loan_count
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY open_year;

[User] Actually, only include accounts whose status is 'Active'.

[Assistant]
SELECT EXTRACT(YEAR FROM a.created_at) AS open_year,
       SUM(l.principal_amount) AS total_principal,
       COUNT(*) AS loan_count
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE a.status = 'Active'
GROUP BY open_year;

[User] Then order those years by total_principal ascending.

[Assistant]
SELECT EXTRACT(YEAR FROM a.created_at) AS open_year,
       SUM(l.principal_amount) AS total_principal,
       COUNT(*) AS loan_count
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE a.status = 'Active'
GROUP BY open_year
ORDER BY total_principal ASC;

[User] Show me a summary per loan_type with the minimum interest_rate, maximum interest_rate, and the average current_principal_balance.

[Assistant]
SELECT loan_type,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
GROUP BY loan_type;

[User] Only include loans that were originated on or after 2022-01-01.

[Assistant]
SELECT loan_type,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
WHERE origination_date >= DATE '2022-01-01'
GROUP BY loan_type;

[User] And restrict to loans with a term longer than 24 months.

[Assistant]
SELECT loan_type,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
WHERE origination_date >= DATE '2022-01-01'
  AND term_months > 24
GROUP BY loan_type;

[User] For each loan, calculate the number of days until maturity. Display loan_id, account_id, maturity_date, and days_to_maturity as the difference between maturity_date and CURRENT_DATE.

[Assistant]
SELECT loan_id,
       account_id,
       maturity_date,
       (maturity_date - CURRENT_DATE) AS days_to_maturity
FROM financial_services.loans;

[User] Actually, only include loans where days_to_maturity is between 30 and 180 days.

[Assistant]
SELECT loan_id,
       account_id,
       maturity_date,
       (maturity_date - CURRENT_DATE) AS days_to_maturity
FROM financial_services.loans
WHERE (maturity_date - CURRENT_DATE) BETWEEN 30 AND 180;

[User] Finally, join to the accounts table to include account_type in the result.

[Assistant]
SELECT l.loan_id,
       l.account_id,
       a.account_type,
       l.maturity_date,
       (l.maturity_date - CURRENT_DATE) AS days_to_maturity
FROM financial_services.loans l
JOIN financial_services.accounts a
  ON l.account_id = a.account_id
WHERE (l.maturity_date - CURRENT_DATE) BETWEEN 30 AND 180;

[User] I need a report that shows, for each account status and loan type, how many loans there are and the average principal amount.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY a.status, l.loan_type;

[User] Actually, include only loans whose status is 'Active'.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE l.status = 'Active'
GROUP BY a.status, l.loan_type;

[User] Also exclude any loan_type groups that have fewer than 5 loans.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE l.status = 'Active'
GROUP BY a.status, l.loan_type
HAVING COUNT(*) >= 5;

[User] Finally, sort the output by average_principal in descending order.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE l.status = 'Active'
GROUP BY a.status, l.loan_type
HAVING COUNT(*) >= 5
ORDER BY average_principal DESC;

[User] List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)

[User] Show me all invoice numbers together with the client IDs and related case IDs for invoices issued after March 1st, 2024.

[Assistant] SELECT invoice_number, client_id, case_id FROM legal_services.invoices WHERE issue_date > '2024-03-01';

[User] I only want to include invoices that have a total_amount greater than 5000. Can you update the query?

[Assistant] SELECT invoice_number, client_id, case_id FROM legal_services.invoices WHERE issue_date > '2024-03-01' AND total_amount > 5000;

[User] Add the invoice status to the result, and only show invoices where the status is either 'Overdue' or 'Partially Paid'.

[Assistant] SELECT invoice_number, client_id, case_id, status FROM legal_services.invoices WHERE issue_date > '2024-03-01' AND total_amount > 5000 AND status IN ('Overdue', 'Partially Paid');

[User] Give me a count of invoices issued for each case this year, and show the case ID with the count.

[Assistant]
SELECT case_id, COUNT(*) AS invoice_count
FROM legal_services.invoices
WHERE EXTRACT(YEAR FROM issue_date) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY case_id;

[User] Some cases might not have any invoices yet—can you modify the query to include such cases as well, showing 0 for those without invoices?

[Assistant]
SELECT cases.case_id, COALESCE(COUNT(invoices.invoice_id), 0) AS invoice_count
FROM cases
LEFT JOIN legal_services.invoices ON cases.case_id = invoices.case_id AND EXTRACT(YEAR FROM invoices.issue_date) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY cases.case_id;

[User] Now, only show cases where the invoice_count is less than 2.

[Assistant]
SELECT cases.case_id, COALESCE(COUNT(invoices.invoice_id), 0) AS invoice_count
FROM cases
LEFT JOIN legal_services.invoices ON cases.case_id = invoices.case_id AND EXTRACT(YEAR FROM invoices.issue_date) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY cases.case_id
HAVING COALESCE(COUNT(invoices.invoice_id), 0) < 2;

[User] List pairs of invoice_number for invoices that share the same due_date.

[Assistant]
SELECT a.due_date,
       a.invoice_number AS invoice1,
       b.invoice_number AS invoice2
FROM legal_services.invoices a
JOIN legal_services.invoices b
  ON a.due_date = b.due_date
  AND a.invoice_id < b.invoice_id;

[User] Only include pairs where the due_date is in March 2024.

[Assistant]
SELECT a.due_date,
       a.invoice_number AS invoice1,
       b.invoice_number AS invoice2
FROM legal_services.invoices a
JOIN legal_services.invoices b
  ON a.due_date = b.due_date
  AND a.invoice_id < b.invoice_id
WHERE a.due_date BETWEEN '2024-03-01' AND '2024-03-31';

[User] Can you list the invoice numbers, issue dates, and due dates for all invoices, sorted by issue date ascending?

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices ORDER BY issue_date ASC;

[User] I only want to see invoices with a due date in May 2024. Please modify the query.

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' ORDER BY issue_date ASC;

[User] Also, only include invoices that have not been paid in full yet (amount_paid < total_amount).

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' AND amount_paid < total_amount ORDER BY issue_date ASC;

[User] Add the status column and sort the results by due_date descending.

[Assistant] SELECT invoice_number, issue_date, due_date, status FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' AND amount_paid < total_amount ORDER BY due_date DESC;

[User] Which invoices have a status of 'Partially Paid' and have not reached their due date yet? Show the invoice number, client ID, due date, and amount paid.

[Assistant]
SELECT invoice_number, client_id, due_date, amount_paid
FROM legal_services.invoices
WHERE status = 'Partially Paid' AND due_date > CURRENT_DATE;

[User] Show me all invoices, displaying their invoice number and the payment date, for invoices that have been fully paid.

[Assistant] SELECT invoice_number, payment_date FROM legal_services.invoices WHERE status = 'Paid';


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.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] Can you list all appointments along with the scheduled start time, purpose, and booking method, as well as the employee ID and location ID for each appointment?

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments;

[User] Now, only include appointments that are scheduled for a future date and have the status 'Scheduled'.

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments WHERE scheduled_start_time > CURRENT_TIMESTAMP AND status = 'Scheduled';

[User] How many appointments have a status of 'Cancelled' for each service?

[Assistant] SELECT service_id, COUNT(*) AS cancelled_appointments FROM government_services.appointments WHERE status = 'Cancelled' GROUP BY service_id;

[User] Show me all appointment IDs and their scheduled start times along with the employee ID and service ID for appointments that have been booked using the 'Kiosk' booking method.

[Assistant] SELECT appointment_id, scheduled_start_time, employee_id, service_id FROM government_services.appointments WHERE booking_method = 'Kiosk';

[User] Only include appointments that are currently in 'Scheduled' status.

[Assistant] SELECT appointment_id, scheduled_start_time, employee_id, service_id FROM government_services.appointments WHERE booking_method = 'Kiosk' AND status = 'Scheduled';

[User] List the location ID and the total number of appointments scheduled at each location in the month of February 2024.

[Assistant] SELECT location_id, COUNT(*) AS appointment_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' GROUP BY location_id;

[User] I also want to see only those locations with more than 3 appointments in that month.

[Assistant] SELECT location_id, COUNT(*) AS appointment_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' GROUP BY location_id HAVING COUNT(*) > 3;

[User] Can you add the distinct number of citizens who had appointments at each qualifying location?

[Assistant] SELECT location_id, COUNT(*) AS appointment_count, COUNT(DISTINCT citizen_id) AS distinct_citizen_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' GROUP BY location_id HAVING COUNT(*) > 3;

[User] Now, only include appointments where the booking method used was 'Online'.

[Assistant] SELECT location_id, COUNT(*) AS appointment_count, COUNT(DISTINCT citizen_id) AS distinct_citizen_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' AND booking_method = 'Online' GROUP BY location_id HAVING COUNT(*) > 3;

[User] For each location, count the total number of appointments scheduled. Show the location name and the count.

[Assistant] SELECT T2.location_name, COUNT(T1.appointment_id) FROM government_services.appointments AS T1 JOIN locations AS T2 ON T1.location_id = T2.location_id GROUP BY T2.location_name;

[User] Find all appointments where the employee ID is not null and show the appointment ID, employee ID, and the scheduled start time.

[Assistant] SELECT appointment_id, employee_id, scheduled_start_time FROM government_services.appointments WHERE employee_id IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] Which accounts have executed trades with a total value greater than 1,000,000?

[Assistant]
SELECT account_id, SUM(total_amount) AS total_traded_amount
FROM financial_services.trades
GROUP BY account_id
HAVING SUM(total_amount) > 1000000;

[User] Can you include the account holder's name as well?

[Assistant]
SELECT a.account_id, a.account_holder_name, SUM(t.total_amount) AS total_traded_amount
FROM financial_services.trades t
JOIN financial_services.accounts a ON t.account_id = a.account_id
GROUP BY a.account_id, a.account_holder_name
HAVING SUM(t.total_amount) > 1000000;

[User] Show me all trades for account 'ACC654321' executed after January 1, 2024.

[Assistant]
SELECT *
FROM financial_services.trades
WHERE account_id = 'ACC654321' AND trade_timestamp > '2024-01-01';

[User] Actually, I only want the buy trades.

[Assistant]
SELECT *
FROM financial_services.trades
WHERE account_id = 'ACC654321' AND trade_timestamp > '2024-01-01' AND trade_type = 'Buy';

[User] Include the security names in the result.

[Assistant]
SELECT t.*, s.security_name
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.account_id = 'ACC654321' AND t.trade_timestamp > '2024-01-01' AND t.trade_type = 'Buy';

[User] List the total traded amount and total commission for each security, including the security name.

[Assistant]
SELECT s.security_id, s.security_name, SUM(t.total_amount) AS total_traded_amount, SUM(t.commission) AS total_commission
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
GROUP BY s.security_id, s.security_name;

[User] Can you filter this to only include trades executed at the 'NASDAQ' venue?

[Assistant]
SELECT s.security_id, s.security_name, SUM(t.total_amount) AS total_traded_amount, SUM(t.commission) AS total_commission
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.execution_venue = 'NASDAQ'
GROUP BY s.security_id, s.security_name;

[User] Show me the total number of trades and the sum of total_amount for each status in the trades table.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status
FROM financial_services.trades t
GROUP BY t.status;

[User] Now, only include statuses where trade_count is greater than 100, and restrict to trades executed in the last 30 days.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status
FROM financial_services.trades t
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY t.status
HAVING COUNT(t.trade_id) > 100;

[User] Exclude any statuses where the sum of commission is null or less than 1000.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status,
  SUM(t.commission) AS total_commission
FROM financial_services.trades t
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY t.status
HAVING COUNT(t.trade_id) > 100
   AND SUM(t.commission) >= 1000;