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.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    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.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] How many transactions are there for each status?

[Assistant] SELECT status, COUNT(*) AS transaction_count FROM financial_services.transactions GROUP BY status;

[User] Exclude any statuses that have fewer than 100 transactions.

[Assistant] SELECT status, COUNT(*) AS transaction_count FROM financial_services.transactions GROUP BY status HAVING COUNT(*) >= 100;

[User] For each employee who serves as a relationship manager, what is the total transaction amount processed for the accounts they manage?

[Assistant] SELECT e.first_name, e.last_name, SUM(t.amount) AS total_managed_transaction_amount FROM financial_services.employees e JOIN financial_services.accounts a ON e.employee_id = a.relationship_manager_id JOIN financial_services.transactions t ON a.account_id = t.account_id GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Only include transactions with a status of 'Completed' in this calculation.

[Assistant] SELECT e.first_name, e.last_name, SUM(t.amount) AS total_managed_transaction_amount FROM financial_services.employees e JOIN financial_services.accounts a ON e.employee_id = a.relationship_manager_id JOIN financial_services.transactions t ON a.account_id = t.account_id WHERE t.status = 'Completed' GROUP BY e.employee_id, e.first_name, e.last_name;

[User] List all trades, showing the trade ID, account ID, and the ticker symbol and security name of the traded security.

[Assistant] SELECT t.trade_id, t.account_id, s.ticker_symbol, s.security_name FROM financial_services.trades AS t JOIN financial_services.securities AS s ON t.security_id = s.security_id

[User] Filter the results to only include trades with a quantity greater than 100.

[Assistant] SELECT t.trade_id, t.account_id, s.ticker_symbol, s.security_name FROM financial_services.trades AS t JOIN financial_services.securities AS s ON t.security_id = s.security_id WHERE t.quantity > 100

[User] Sort the output by the security name in ascending order.

[Assistant] SELECT t.trade_id, t.account_id, s.ticker_symbol, s.security_name FROM financial_services.trades AS t JOIN financial_services.securities AS s ON t.security_id = s.security_id WHERE t.quantity > 100 ORDER BY s.security_name ASC

[User] List all employees and the department their manager belongs to. Include the employee's full name.

[Assistant] SELECT e.first_name, e.last_name, m.department AS manager_department FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id

[User] Now, filter the list to only include employees who were hired in the last 5 years.

[Assistant] SELECT e.first_name, e.last_name, m.department AS manager_department FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date >= date('now', '-5 years')

[User] Add the employee's department and their job title to the result.

[Assistant] SELECT e.first_name, e.last_name, e.department AS employee_department, e.job_title, m.department AS manager_department FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date >= date('now', '-5 years')

[User] Sort the results by the manager's department ascending, then by the employee's hire date descending.

[Assistant] SELECT e.first_name, e.last_name, e.department AS employee_department, e.job_title, m.department AS manager_department FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date >= date('now', '-5 years') ORDER BY m.department ASC, e.hire_date DESC

[User] For each trade in the past 14 days, show the trade_id, account_id, security_id, and the latest close_price for that security from market_data.

[Assistant]
SELECT tr.trade_id, tr.account_id, tr.security_id, md.close_price AS latest_close_price, md.data_timestamp
FROM financial_services.trades tr
LEFT JOIN LATERAL (
  SELECT m.close_price, m.data_timestamp
  FROM financial_services.market_data m
  WHERE m.security_id = tr.security_id
  ORDER BY m.data_timestamp DESC
  LIMIT 1
) md ON TRUE
WHERE tr.trade_timestamp >= NOW() - INTERVAL '14 days';

[User] Only show trades where the total_amount is above 3,000 and the latest_close_price is available.

[Assistant]
SELECT tr.trade_id, tr.account_id, tr.security_id, md.close_price AS latest_close_price, md.data_timestamp
FROM financial_services.trades tr
LEFT JOIN LATERAL (
  SELECT m.close_price, m.data_timestamp
  FROM financial_services.market_data m
  WHERE m.security_id = tr.security_id
  ORDER BY m.data_timestamp DESC
  LIMIT 1
) md ON TRUE
WHERE tr.trade_timestamp >= NOW() - INTERVAL '14 days'
  AND tr.total_amount > 3000
  AND md.close_price IS NOT NULL;

[User] List all accounts having both a loan and at least one transaction in the last 7 days. Show account_id, account_type, and the total number of transactions in that period.

[Assistant]
SELECT a.account_id, a.account_type, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
INNER JOIN financial_services.loans l ON a.account_id = l.account_id
INNER JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE t.transaction_date >= NOW() - INTERVAL '7 days'
GROUP BY a.account_id, a.account_type;

[User] Add the sum of transaction amounts and the loan principal_amount in the result.

[Assistant]
SELECT a.account_id, a.account_type, COUNT(t.transaction_id) AS transaction_count, SUM(t.amount) AS total_transaction_amount, l.principal_amount
FROM financial_services.accounts a
INNER JOIN financial_services.loans l ON a.account_id = l.account_id
INNER JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE t.transaction_date >= NOW() - INTERVAL '7 days'
GROUP BY a.account_id, a.account_type, l.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 social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )

[User] How many unique hashtags has each post been associated with? Please return post_id and unique_hashtag_count.

[Assistant]
SELECT post_id, COUNT(DISTINCT hashtag_id) AS unique_hashtag_count
FROM social_media.post_hashtags
GROUP BY post_id;

[User] Which posts have been mentioned with at least one hashtag and also have users who joined the conversation corresponding to the post? Please show the post_id and the user_id of participants.

[Assistant]
SELECT ph.post_id, cp.user_id
FROM social_media.post_hashtags ph
INNER JOIN social_media.conversation_participants cp
  ON ph.post_id = cp.conversation_id;

[User] Can you also include the joined_at time for each user in the result?

[Assistant]
SELECT ph.post_id, cp.user_id, cp.joined_at
FROM social_media.post_hashtags ph
INNER JOIN social_media.conversation_participants cp
  ON ph.post_id = cp.conversation_id;

[User] Show me the user_id and number of conversations they have joined. Only include users who joined more than one conversation.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Add the time they joined their most recent conversation as latest_joined_at.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined, MAX(joined_at) AS latest_joined_at
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Also, show the IDs of the conversations for each user as a comma-separated list.

[Assistant]
SELECT user_id,
  COUNT(DISTINCT conversation_id) AS conversations_joined,
  MAX(joined_at) AS latest_joined_at,
  STRING_AGG(DISTINCT conversation_id, ',') AS conversation_ids
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] List all conversation participants along with post_hashtag details where the participant's user_id matches the hashtag_id.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id;

[User] Only include participants who joined after '2024-01-01'.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id
WHERE cp.joined_at > '2024-01-01';

[User] Also, order the results by joined_at descending.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id
WHERE cp.joined_at > '2024-01-01'
ORDER BY cp.joined_at DESC;

[User] Finally, limit the output to the first 10 rows.

[Assistant]
SELECT cp.conversation_id, cp.user_id, ph.post_id, ph.hashtag_id
FROM social_media.conversation_participants cp
INNER JOIN social_media.post_hashtags ph
  ON cp.user_id = ph.hashtag_id
WHERE cp.joined_at > '2024-01-01'
ORDER BY cp.joined_at DESC
LIMIT 10;

[User] List all pairs of users who participated in the same conversation. For each, show conversation_id, user_id1, user_id2.

[Assistant]
SELECT p1.conversation_id,
       p1.user_id AS user_id1,
       p2.user_id AS user_id2
FROM social_media.conversation_participants p1
JOIN social_media.conversation_participants p2
  ON p1.conversation_id = p2.conversation_id
WHERE p1.user_id < p2.user_id;

[User] Only include pairs where both joined after '2024-06-01'.

[Assistant]
SELECT p1.conversation_id,
       p1.user_id AS user_id1,
       p2.user_id AS user_id2
FROM social_media.conversation_participants p1
JOIN social_media.conversation_participants p2
  ON p1.conversation_id = p2.conversation_id
WHERE p1.user_id < p2.user_id
  AND p1.joined_at > '2024-06-01'
  AND p2.joined_at > '2024-06-01';

[User] How many participants are there in each conversation? Return conversation_id and participant_count.

[Assistant]
SELECT conversation_id,
       COUNT(*) AS participant_count
FROM social_media.conversation_participants
GROUP BY conversation_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] List all events and any token transfers that occurred in the same transaction, showing event_id, event_name, transfer_id, and token_symbol.

[Assistant]
SELECT
  e.event_id,
  e.event_name,
  tt.transfer_id,
  tk.token_symbol
FROM web3.events e
LEFT JOIN web3.token_transfers tt
  ON e.transaction_id = tt.transaction_id
LEFT JOIN web3.tokens tk
  ON tt.token_id = tk.token_id
ORDER BY e.transaction_id, e.log_index;

[User] For each contract deployed on network 'mainnet', show its address, status, the number of tokens created by that contract's address, and the total number of events emitted by that contract.

[Assistant]
SELECT
  c.address AS contract_address,
  c.status,
  COUNT(DISTINCT t.token_id) AS token_count,
  COUNT(e.event_id) AS event_count
FROM web3.contracts c
LEFT JOIN web3.tokens t
  ON c.address = t.contract_address
LEFT JOIN web3.events e
  ON c.contract_id = e.contract_id
WHERE c.network_id = 'mainnet'
GROUP BY c.address, c.status;

[User] For each deployer address, show the total supply of all tokens created by the contracts they deployed.

[Assistant]
SELECT c.deployer_address, SUM(t.total_supply) AS total_token_supply
FROM web3.contracts c
JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.deployer_address;

[User] For each token, show its token name, token symbol, the address of the contract it was created on, and the deployer address of that contract.

[Assistant]
SELECT t.token_id, t.token_name, t.token_symbol, t.contract_address, c.deployer_address
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address;

[User] Find all contracts deployed by users who have also conducted transactions with a value greater than 1 ETH (where 1 ETH = 1e18 wei).

[Assistant] SELECT DISTINCT c.contract_id, c.address, c.deployer_address FROM web3.contracts c JOIN web3.transactions t ON c.deployer_address = t.from_address WHERE t.value > 1e18;

[User] For each wallet, list its address, the user_id, and the total value of all token transfers sent from that wallet, along with the contract address of the token.

[Assistant]
SELECT w.wallet_id, w.address, w.user_id, SUM(tt.value) AS total_sent_value, t.contract_address
FROM web3.wallets w
LEFT JOIN web3.token_transfers tt ON w.address = tt.from_address
LEFT JOIN web3.tokens t ON tt.token_id = t.token_id
GROUP BY w.wallet_id, w.address, w.user_id, t.contract_address;


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.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] Show the number of staff members in each position and the average access level, grouping by position.

[Assistant]
SELECT position,
       COUNT(*) AS staff_count,
       AVG(access_level) AS avg_access_level
FROM hospitality_technology.staff
GROUP BY position;

[User] Filter to only include positions where the average access level is greater than 4.

[Assistant]
SELECT position,
       COUNT(*) AS staff_count,
       AVG(access_level) AS avg_access_level
FROM hospitality_technology.staff
GROUP BY position
HAVING AVG(access_level) > 4;

[User] For each service order, list the order_id, reservation_id, the full name of the staff who ordered it as ordered_by, and the full name of the staff who delivered it as delivered_by.

[Assistant]
SELECT so.order_id,
       so.reservation_id,
       ord.first_name || ' ' || ord.last_name AS ordered_by,
       del.first_name || ' ' || del.last_name AS delivered_by,
       so.order_timestamp
FROM hospitality_technology.service_orders so
LEFT JOIN hospitality_technology.staff ord
  ON so.staff_id_ordered = ord.staff_id
LEFT JOIN hospitality_technology.staff del
  ON so.staff_id_delivered = del.staff_id;

[User] Actually, restrict the list to orders where status is 'Delivered'.

[Assistant]
SELECT so.order_id,
       so.reservation_id,
       ord.first_name || ' ' || ord.last_name AS ordered_by,
       del.first_name || ' ' || del.last_name AS delivered_by,
       so.order_timestamp
FROM hospitality_technology.service_orders so
LEFT JOIN hospitality_technology.staff ord
  ON so.staff_id_ordered = ord.staff_id
LEFT JOIN hospitality_technology.staff del
  ON so.staff_id_delivered = del.staff_id
WHERE so.status = 'Delivered';

[User] Now sort the output by order_timestamp DESC and limit to 10 results.

[Assistant]
SELECT so.order_id,
       so.reservation_id,
       ord.first_name || ' ' || ord.last_name AS ordered_by,
       del.first_name || ' ' || del.last_name AS delivered_by,
       so.order_timestamp
FROM hospitality_technology.service_orders so
LEFT JOIN hospitality_technology.staff ord
  ON so.staff_id_ordered = ord.staff_id
LEFT JOIN hospitality_technology.staff del
  ON so.staff_id_delivered = del.staff_id
WHERE so.status = 'Delivered'
ORDER BY so.order_timestamp DESC
LIMIT 10;

[User] List the full names and email addresses of staff members who have delivered at least one service order in the past 30 days, along with the count of orders they delivered. Sort by count descending.

[Assistant]
SELECT st.staff_id,
       st.first_name || ' ' || st.last_name AS full_name,
       st.work_email,
       COUNT(so.order_id) AS delivered_count
FROM hospitality_technology.staff st
JOIN hospitality_technology.service_orders so
  ON st.staff_id = so.staff_id_delivered
WHERE so.status = 'Delivered'
  AND so.delivery_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY st.staff_id, st.first_name, st.last_name, st.work_email
ORDER BY delivered_count DESC;

[User] Actually, only include staff who delivered more than 5 orders in that period.

[Assistant]
SELECT st.staff_id,
       st.first_name || ' ' || st.last_name AS full_name,
       st.work_email,
       COUNT(so.order_id) AS delivered_count
FROM hospitality_technology.staff st
JOIN hospitality_technology.service_orders so
  ON st.staff_id = so.staff_id_delivered
WHERE so.status = 'Delivered'
  AND so.delivery_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY st.staff_id, st.first_name, st.last_name, st.work_email
HAVING COUNT(so.order_id) > 5
ORDER BY delivered_count DESC;

[User] List staff members who were hired in the last calendar year, showing their full name, position, and hire date.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date);

[User] Now, only include those staff members who are not managers and have an access level greater than 3.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date) AND position != 'Manager' AND access_level > 3;

[User] Which staff members have terminated employment? Show their names, hire and termination dates, and the property ID.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL;

[User] Only include those who worked at properties with an access_level of at least 4.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL AND access_level >= 4;

[User] Actually, show only the staff whose employment lasted less than 2 years.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL
  AND access_level >= 4
  AND (termination_date - hire_date) < INTERVAL '2 years';

[User] Show me all staff members who have a manager assigned, along with each manager's full name.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.manager_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE s.manager_id IS NOT NULL;

[User] Actually, only include managers who are currently active.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.manager_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE s.manager_id IS NOT NULL AND m.is_active = TRUE;


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.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.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) )

[User] Provide the count of applications grouped by their status.

[Assistant]
SELECT status, COUNT(*) AS application_count
FROM government_services.applications
GROUP BY status;

[User] For each service category, count the number of appointments scheduled in the next 7 days. Return the category and appointment count.

[Assistant]
SELECT s.category, COUNT(a.appointment_id) AS upcoming_appointments
FROM government_services.appointments a
JOIN government_services.services s ON a.service_id = s.service_id
WHERE a.scheduled_start_time BETWEEN now() AND now() + interval '7 days'
GROUP BY s.category;

[User] Which employees have verified more than 5 documents in the last 30 days? Return the employee's full name, department, and the number of verifications.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name, e.department, COUNT(d.document_id) AS verification_count
FROM government_services.documents d
JOIN government_services.employees e ON d.verified_by_employee_id = e.employee_id
WHERE d.verification_status = 'Verified'
  AND d.verification_timestamp >= now() - interval '30 days'
GROUP BY e.first_name, e.last_name, e.department
HAVING COUNT(d.document_id) > 5;

[User] Provide a count of documents grouped by their current verification status.

[Assistant] SELECT verification_status, COUNT(*) FROM government_services.documents GROUP BY verification_status

[User] Find the full names of employees who have verified documents that have an expiry date in the past and are marked as 'Verified'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.employees AS T1 JOIN government_services.documents AS T2 ON T1.employee_id = T2.verified_by_employee_id WHERE T2.expiry_date < CURRENT_DATE AND T2.verification_status = 'Verified'

[User] List the application IDs and their submitted dates for applications that have been assigned to an employee in the 'Housing' department.

[Assistant] SELECT T1.application_id, T1.submitted_at FROM government_services.applications AS T1 JOIN government_services.employees AS T2 ON T1.assigned_employee_id = T2.employee_id WHERE T2.department = 'Housing'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

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

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

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

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

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

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

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

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

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

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

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

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

[User] Show all SUI coins that are marked as 'exists' in both sui_coins and sui_coins_metadata, displaying their coin_type, symbol, name, and balance.

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.balance FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND scm.status = 'exists';

[User] Can you add the owner address for each coin and include only those with a balance greater than 1000000?

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner, sc.balance FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS decimal) > 1000000;

[User] Please also show the coin description, and sort by balance descending.

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner, sc.balance, scm.description FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS decimal) > 1000000 ORDER BY CAST(sc.balance AS decimal) DESC;

[User] Now limit the result to the top 10 coins.

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner, sc.balance, scm.description FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS decimal) > 1000000 ORDER BY CAST(sc.balance AS decimal) DESC LIMIT 10;

[User] Show me the top 5 token balances by amount for wallet '0xabc123abcdef' in the erc20_balances table.

[Assistant]
SELECT contract_address, amount
FROM erc20_balances
WHERE wallet_address = '0xabc123abcdef'
ORDER BY CAST(amount AS numeric) DESC
LIMIT 5;

[User] Include token symbol and decimals from token_prices_latest by joining on contract_address = address.

[Assistant]
SELECT eb.contract_address, eb.amount, tpl.symbol, tpl.decimals
FROM erc20_balances eb
JOIN token_prices_latest tpl ON eb.contract_address = tpl.address
WHERE eb.wallet_address = '0xabc123abcdef'
ORDER BY CAST(eb.amount AS numeric) DESC
LIMIT 5;

[User] Filter to tokens where the latest price is greater than 1.0.

[Assistant]
SELECT eb.contract_address, eb.amount, tpl.symbol, tpl.decimals
FROM erc20_balances eb
JOIN token_prices_latest tpl ON eb.contract_address = tpl.address
WHERE eb.wallet_address = '0xabc123abcdef'
  AND tpl.price > 1.0
ORDER BY CAST(eb.amount AS numeric) DESC
LIMIT 5;

[User] Add a computed column usd_value as amount * price.

[Assistant]
SELECT eb.contract_address,
       eb.amount,
       tpl.symbol,
       tpl.decimals,
       tpl.price,
       CAST(eb.amount AS numeric) * tpl.price AS usd_value
FROM erc20_balances eb
JOIN token_prices_latest tpl ON eb.contract_address = tpl.address
WHERE eb.wallet_address = '0xabc123abcdef'
  AND tpl.price > 1.0
ORDER BY CAST(eb.amount AS numeric) DESC
LIMIT 5;

[User] I need a list of all SUI coins with their object ID, coin type, and balance.

[Assistant] SELECT object_id, coin_type, balance FROM sui_coins;

[User] Only include coins where status is 'exists'.

[Assistant] SELECT object_id, coin_type, balance FROM sui_coins WHERE status = 'exists';

[User] Add the symbol and name by joining the sui_coins_metadata table on coin_type.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists';

[User] Filter the result to only coins whose description contains 'Utility' and sort by balance descending.

[Assistant]
SELECT sc.object_id, sc.coin_type, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists'
  AND scm.description LIKE '%Utility%'
ORDER BY CAST(sc.balance AS numeric) DESC;

[User] List all wallets holding the NFT with contract_address '0xabc123' and token_id '100' and the amount held.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xabc123'
  AND token_id = '100';

[User] Also include the NFT name from nft_metadata by joining on contract_address and token_id.

[Assistant]
SELECT nh.wallet_address,
       nh.amount,
       nm.name
FROM nft_holders nh
JOIN nft_metadata nm ON nh.contract_address = nm.contract_address
                   AND nh.token_id = nm.token_id
WHERE nh.contract_address = '0xabc123'
  AND nh.token_id = '100';

[User] Finally, add the collection name from nft_collections where blockchain is 'Ethereum'.

[Assistant]
SELECT nh.wallet_address,
       nh.amount,
       nm.name,
       nc.name AS collection_name
FROM nft_holders nh
JOIN nft_metadata nm ON nh.contract_address = nm.contract_address
                   AND nh.token_id = nm.token_id
JOIN nft_collections nc ON nh.contract_address = nc.contract_address
                      AND nc.blockchain = 'Ethereum'
WHERE nh.contract_address = '0xabc123'
  AND nh.token_id = '100';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )

[User] List all tokens with a price below $1 and a 24-hour trading volume over $5 million.

[Assistant] SELECT token_name, token_symbol, price, total_volume FROM token_basic_info WHERE price < 1 AND total_volume::numeric > 5000000;

[User] Show tokens with a trend rank worse than 30 (higher number) that also have a positive price change over the last 24 hours. Display their symbol, chain, price, trend rank, and 24h price change.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0

[User] Only show results for tokens on the 'Ethereum' chain.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0 AND chain = 'Ethereum'

[User] Also filter for tokens with a market cap greater than $100,000,000.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0 AND chain = 'Ethereum' AND market_cap > 100000000

[User] Order the results by 24-hour price change percentage descending and show the top 10.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0 AND chain = 'Ethereum' AND market_cap > 100000000 ORDER BY price_change_percentage_24h DESC LIMIT 10

[User] For the 'DeFi' narrative, what is the average price, average market cap, and average 24-hour trading volume of its tokens?

[Assistant] SELECT AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume FROM token_basic_info WHERE narrative = 'DeFi'

[User] Instead of just 'DeFi', show these average metrics (price, market cap, 24h volume) for *all* narratives.

[Assistant] SELECT narrative, AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume FROM token_basic_info WHERE narrative IS NOT NULL GROUP BY narrative

[User] Only include narratives with at least 10 tokens and an average market cap above $500,000,000. Order the results by average market cap descending and show the top 5.

[Assistant] SELECT narrative, AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume FROM token_basic_info WHERE narrative IS NOT NULL GROUP BY narrative HAVING COUNT(*) >= 10 AND AVG(market_cap) > 500000000 ORDER BY avg_market_cap DESC LIMIT 5

[User] Also include the average trend rank for each of these narratives.

[Assistant] SELECT narrative, AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume, AVG(trend_rank) AS avg_trend_rank FROM token_basic_info WHERE narrative IS NOT NULL GROUP BY narrative HAVING COUNT(*) >= 10 AND AVG(market_cap) > 500000000 ORDER BY avg_market_cap DESC LIMIT 5

[User] Show me the top 3 tokens by trend rank in the 'NFT' narrative, along with their price and 24-hour trading volume.

[Assistant] SELECT token_name, token_symbol, price, total_volume FROM token_basic_info WHERE narrative = 'NFT' ORDER BY trend_rank ASC LIMIT 3;

[User] Can you also include their 1-hour and 7-day price change percentages?

[Assistant] SELECT token_name, token_symbol, price, total_volume, price_change_percentage_1h, price_change_percentage_7d FROM token_basic_info WHERE narrative = 'NFT' ORDER BY trend_rank ASC LIMIT 3;

[User] Actually, I only want tokens with positive price changes in both time frames.

[Assistant] SELECT token_name, token_symbol, price, total_volume, price_change_percentage_1h, price_change_percentage_7d FROM token_basic_info WHERE narrative = 'NFT' AND price_change_percentage_1h > 0 AND price_change_percentage_7d > 0 ORDER BY trend_rank ASC LIMIT 3;

[User] Now order the results by 24-hour trading volume instead of trend rank.

[Assistant] SELECT token_name, token_symbol, price, total_volume, price_change_percentage_1h, price_change_percentage_7d FROM token_basic_info WHERE narrative = 'NFT' AND price_change_percentage_1h > 0 AND price_change_percentage_7d > 0 ORDER BY total_volume::numeric DESC LIMIT 3;

[User] List the top 5 tokens by price_change_percentage_7d, showing token_symbol, narrative, and price_change_percentage_7d.

[Assistant]
SELECT token_symbol, narrative, price_change_percentage_7d
FROM token_basic_info
ORDER BY price_change_percentage_7d DESC
LIMIT 5;

[User] List tokens that have a 24-hour trading volume greater than $10,000,000 and a negative price change percentage over the last 24 hours. Show the token symbol, chain, total volume, and the 24-hour price change percentage.

[Assistant] SELECT token_symbol, chain, total_volume, price_change_percentage_24h FROM token_basic_info WHERE CAST(REPLACE(total_volume, ',', '') AS numeric) > 10000000 AND price_change_percentage_24h < 0

[User] From those results, filter further to only include tokens with a market cap rank of 100 or better. Order the results by 24-hour trading volume in descending order.

[Assistant] SELECT token_symbol, chain, total_volume, price_change_percentage_24h FROM token_basic_info WHERE CAST(REPLACE(total_volume, ',', '') AS numeric) > 10000000 AND price_change_percentage_24h < 0 AND market_cap_rank IS NOT NULL AND market_cap_rank <= 100 ORDER BY CAST(REPLACE(total_volume, ',', '') AS numeric) 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 healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_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 patients who have had at least one appointment with a doctor specializing in 'Cardiology'. Include the patient's full name, appointment time, and doctor's full name.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology';

[User] Can you only include appointments that are marked as 'Completed'?

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed';

[User] Only show appointments that lasted at least 45 minutes.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed' AND a.duration_minutes >= 45;

[User] Could you also include the doctor's specialty in the result?

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, d.specialty
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed' AND a.duration_minutes >= 45;

[User] Provide each patient's most recent medical-record doctor's full name along with their primary insurance plan name. Return patient_id, first_name, last_name, primary_plan_name, doctor_first_name, doctor_last_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name      AS primary_plan_name,
       d.first_name      AS doctor_first_name,
       d.last_name       AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id
 AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans AS ip
  ON pi.plan_id = ip.plan_id
JOIN (
  SELECT DISTINCT ON (patient_id)
         patient_id,
         doctor_id,
         record_date
  FROM healthcare.medical_records
  ORDER BY patient_id, record_date DESC
) AS mr
  ON p.patient_id = mr.patient_id
JOIN healthcare.doctors AS d
  ON mr.doctor_id = d.doctor_id;

[User] Actually, restrict to only those whose primary plan_type is 'PPO'.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name      AS primary_plan_name,
       d.first_name      AS doctor_first_name,
       d.last_name       AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id
 AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans AS ip
  ON pi.plan_id = ip.plan_id
JOIN (
  SELECT DISTINCT ON (patient_id)
         patient_id,
         doctor_id,
         record_date
  FROM healthcare.medical_records
  ORDER BY patient_id, record_date DESC
) AS mr
  ON p.patient_id = mr.patient_id
JOIN healthcare.doctors AS d
  ON mr.doctor_id = d.doctor_id
WHERE ip.plan_type = 'PPO';

[User] Retrieve each patient's full name, total number of appointments, and date of their most recent appointment.

[Assistant] SELECT p.first_name || ' ' || p.last_name AS patient_name, COUNT(a.appointment_id) AS appointment_count, MAX(a.appointment_time) AS most_recent_appointment_time FROM healthcare.patients p LEFT JOIN healthcare.appointments a ON p.patient_id = a.patient_id GROUP BY p.patient_id, p.first_name, p.last_name;

[User] Only include patients who have had at least one appointment and sort by appointment_count descending.

[Assistant] SELECT p.first_name || ' ' || p.last_name AS patient_name, COUNT(a.appointment_id) AS appointment_count, MAX(a.appointment_time) AS most_recent_appointment_time FROM healthcare.patients p JOIN healthcare.appointments a ON p.patient_id = a.patient_id GROUP BY p.patient_id, p.first_name, p.last_name HAVING COUNT(a.appointment_id) > 0 ORDER BY appointment_count DESC;

[User] List the full names and dates of birth of all patients whose emergency contact phone matches the phone number of any doctor.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, p.date_of_birth
FROM healthcare.patients p
JOIN healthcare.doctors d
  ON p.emergency_contact_phone IS NOT NULL
 AND p.emergency_contact_phone = d.phone_number;

[User] Now, also include the doctor's full name and specialty in the result.

[Assistant]
SELECT DISTINCT p.first_name AS patient_first_name, p.last_name AS patient_last_name, p.date_of_birth,
                d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, d.specialty
FROM healthcare.patients p
JOIN healthcare.doctors d
  ON p.emergency_contact_phone IS NOT NULL
 AND p.emergency_contact_phone = d.phone_number;

[User] How many active insurance policies does each patient have? Return patient_id and active_policy_count.

[Assistant]
SELECT patient_id,
       COUNT(*) AS active_policy_count
FROM healthcare.patient_insurance
WHERE expiration_date IS NULL
   OR expiration_date >= CURRENT_DATE
GROUP BY patient_id;

[User] Actually, only include patients who have more than one active insurance policy.

[Assistant]
SELECT patient_id,
       COUNT(*) AS active_policy_count
FROM healthcare.patient_insurance
WHERE expiration_date IS NULL
   OR expiration_date >= CURRENT_DATE
GROUP BY patient_id
HAVING COUNT(*) > 1;

[User] List all medical record entries where the treatment_plan mentions a medication name. Return patient_id, record_id, and the matching medication_name.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%';

[User] Actually, only include medications manufactured by 'Pfizer'.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer';

[User] Also sort the results by record_date descending.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer'
ORDER BY mr.record_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )

[User] Find the wallet address, user ID, and the contract address of any contract where that wallet is listed as the deployer.

[Assistant]
SELECT w.address AS wallet_address, w.user_id, c.address AS contract_address
FROM web3.wallets w
JOIN web3.contracts c ON w.address = c.deployer_address;

[User] For each token transfer, show the transfer id, token symbol, and the username of the user who owns the sender address. Please order the result by transfer id.

[Assistant]
SELECT tt.transfer_id, tk.token_symbol, u.username
FROM web3.token_transfers tt
JOIN web3.tokens tk ON tt.token_id = tk.token_id
JOIN web3.wallets w ON tt.from_address = w.address
JOIN web3.users u ON w.user_id = u.user_id
ORDER BY tt.transfer_id;

[User] List all contracts along with the number of tokens deployed at each contract address.

[Assistant]
SELECT c.contract_id, c.address AS contract_address, COUNT(t.token_id) AS token_count
FROM web3.contracts c
LEFT JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.contract_id, c.address;

[User] Actually, just show contracts that have deployed at least 2 tokens.

[Assistant]
SELECT c.contract_id, c.address AS contract_address, COUNT(t.token_id) AS token_count
FROM web3.contracts c
LEFT JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.contract_id, c.address
HAVING COUNT(t.token_id) >= 2;

[User] For each contract, how many tokens are deployed at the contract address? Show contract_id, address, and token_count.

[Assistant]
SELECT c.contract_id, c.address, COUNT(t.token_id) AS token_count
FROM web3.contracts c
LEFT JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.contract_id, c.address;

[User] Can you modify the query to only show contracts where at least 3 tokens are deployed?

[Assistant]
SELECT c.contract_id, c.address, COUNT(t.token_id) AS token_count
FROM web3.contracts c
LEFT JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.contract_id, c.address
HAVING COUNT(t.token_id) >= 3;

[User] Show the transfer id, token symbol, and the total supply of the token for every token transfer, but only for transfers where the transferred value is less than 100. Order by transfer_id.

[Assistant]
SELECT tt.transfer_id, tk.token_symbol, tk.total_supply
FROM web3.token_transfers tt
JOIN web3.tokens tk ON tt.token_id = tk.token_id
WHERE tt.value < 100
ORDER BY tt.transfer_id;

[User] For each user, count the number of distinct smart contracts they have called. Return user_id, username, and contract_count, ordered by contract_count descending.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(DISTINCT tx.to_address) AS contract_count
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions tx ON w.address = tx.from_address
JOIN web3.contracts c ON tx.to_address = c.address
GROUP BY u.user_id, u.username
ORDER BY contract_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Show conversations that are group chats and have more than 5 participants. List the conversation_id and group_name.

[Assistant] SELECT c.conversation_id, c.group_name FROM social_media.conversations AS c JOIN social_media.conversation_participants AS cp ON c.conversation_id = cp.conversation_id WHERE c.is_group_chat = true GROUP BY c.conversation_id, c.group_name HAVING COUNT(cp.user_id) > 5;

[User] Also, include the total number of messages sent in these group chats.

[Assistant] SELECT c.conversation_id, c.group_name, COUNT(m.message_id) AS total_messages FROM social_media.conversations AS c JOIN social_media.conversation_participants AS cp ON c.conversation_id = cp.conversation_id LEFT JOIN social_media.messages AS m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true GROUP BY c.conversation_id, c.group_name HAVING COUNT(cp.user_id) > 5;

[User] Further filter the results to only include group chats where the last message was sent after '2024-06-01'.

[Assistant] SELECT c.conversation_id, c.group_name, COUNT(m.message_id) AS total_messages FROM social_media.conversations AS c JOIN social_media.conversation_participants AS cp ON c.conversation_id = cp.conversation_id LEFT JOIN social_media.messages AS m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND c.last_message_at > '2024-06-01' GROUP BY c.conversation_id, c.group_name HAVING COUNT(cp.user_id) > 5;

[User] Find posts that have been liked by users the author of the post is following. List the post_id and the user_id of the post author.

[Assistant] SELECT p.post_id, p.user_id AS post_author_user_id FROM social_media.posts AS p JOIN social_media.likes AS l ON p.post_id = l.post_id JOIN social_media.follows AS f ON f.follower_user_id = p.user_id AND f.following_user_id = l.user_id;

[User] Can you refine this to only include posts where the author started following the user *before* the post was created?

[Assistant] SELECT p.post_id, p.user_id AS post_author_user_id FROM social_media.posts AS p JOIN social_media.likes AS l ON p.post_id = l.post_id JOIN social_media.follows AS f ON f.follower_user_id = p.user_id AND f.following_user_id = l.user_id WHERE f.created_at < p.created_at;

[User] List all hashtags that have been used on posts created in the last 90 days. Show the tag_name and the date it was first used on a post within this period.

[Assistant] SELECT h.tag_name, MIN(p.created_at) AS first_use_date_in_period FROM social_media.posts AS p JOIN social_media.post_hashtags AS ph ON p.post_id = ph.post_id JOIN social_media.hashtags AS h ON ph.hashtag_id = h.hashtag_id WHERE p.created_at >= NOW() - INTERVAL '90 days' GROUP BY h.hashtag_id, h.tag_name;

[User] Which users have commented on posts that contain media? Please show the commenter username and the post ID.

[Assistant]
SELECT DISTINCT u.username, c.post_id
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';

[User] Can you also include the content of the comment and the type of media for each post?

[Assistant]
SELECT u.username, c.post_id, c.content AS comment_content, p.media_type
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';

[User] Now only show comments that were created after May 1, 2024, and include the comment creation time.

[Assistant]
SELECT u.username, c.post_id, c.content AS comment_content, p.media_type, c.created_at AS comment_created_at
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> ''
  AND c.created_at > '2024-05-01';

[User] List the message_id, content, sender's username, and group_name for all messages in group chats.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
WHERE c.is_group_chat = TRUE;

[User] Exclude group chats that have fewer than 3 participants.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
JOIN (
  SELECT conversation_id
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) >= 3
) cp ON c.conversation_id = cp.conversation_id
WHERE c.is_group_chat = TRUE;

[User] And only show messages sent after '2024-06-01', ordering by sent_at ascending.

[Assistant]
SELECT m.message_id, m.content, u.username, c.group_name
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
JOIN (
  SELECT conversation_id
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) >= 3
) cp ON c.conversation_id = cp.conversation_id
WHERE c.is_group_chat = TRUE
  AND m.sent_at > '2024-06-01'
ORDER BY m.sent_at ASC;

[User] Show me the usernames and the group names for each user who has sent at least one message in a group chat.

[Assistant]
SELECT DISTINCT u.username, c.group_name
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.messages m ON c.conversation_id = m.conversation_id AND u.user_id = m.sender_user_id
WHERE c.is_group_chat = true;

[User] Can you include the total number of messages each user has sent in each group chat as well?

[Assistant]
SELECT u.username, c.group_name, COUNT(m.message_id) AS message_count
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.messages m ON c.conversation_id = m.conversation_id AND u.user_id = m.sender_user_id
WHERE c.is_group_chat = true
GROUP BY u.username, c.group_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 government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )
CREATE TABLE blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text, public_key text, balance numeric )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )

[User] List the block_id, timestamp, and the total amount of transactions for each block, along with the sender and receiver addresses for each transaction that occurred on April 10th, 2023.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, t.receiver_address, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
WHERE DATE(t.timestamp) = '2023-04-10'
GROUP BY b.block_id, b.timestamp, t.sender_address, t.receiver_address;

[User] Can you also include the balance of both sender and receiver addresses at the time of the transaction?

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10'
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

[User] Now only show those transactions where the sender's balance was greater than 5000 at that time.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10' AND sa.balance > 5000
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

[User] Sorry, the sender_address seems incorrect. Use sender_address from transactions table instead of addresses.

[Assistant]
SELECT b.block_id, b.timestamp, t.sender_address, sa.balance AS sender_balance, t.receiver_address, ra.balance AS receiver_balance, SUM(t.amount) as total_amount_in_block
FROM blockchain.blocks b
JOIN blockchain.transactions t ON b.block_id = t.block_id
LEFT JOIN blockchain.addresses sa ON t.sender_address = sa.address_id
LEFT JOIN blockchain.addresses ra ON t.receiver_address = ra.address_id
WHERE DATE(t.timestamp) = '2023-04-10' AND sa.balance > 5000
GROUP BY b.block_id, b.timestamp, t.sender_address, sa.balance, t.receiver_address, ra.balance;

[User] Show me each transaction with its ID, amount, timestamp, and the usernames of both sender and receiver.

[Assistant]
SELECT t.transaction_id, t.amount, t.timestamp, us.username AS sender_username, ur.username AS receiver_username
FROM blockchain.transactions t
LEFT JOIN blockchain.wallets ws ON t.sender_address = ws.address_id
LEFT JOIN blockchain.users us ON ws.user_id = us.user_id
LEFT JOIN blockchain.wallets wr ON t.receiver_address = wr.address_id
LEFT JOIN blockchain.users ur ON wr.user_id = ur.user_id;

[User] List all address IDs with a balance under 50, along with the count of transactions they have received.

[Assistant]
SELECT a.address_id, a.balance, COUNT(t.transaction_id) AS received_count
FROM blockchain.addresses a
LEFT JOIN blockchain.transactions t ON a.address_id = t.receiver_address
WHERE a.balance < 50
GROUP BY a.address_id, a.balance;

[User] Now only include addresses that have received at least 5 transactions.

[Assistant]
SELECT a.address_id, a.balance, COUNT(t.transaction_id) AS received_count
FROM blockchain.addresses a
LEFT JOIN blockchain.transactions t ON a.address_id = t.receiver_address
WHERE a.balance < 50
GROUP BY a.address_id, a.balance
HAVING COUNT(t.transaction_id) >= 5;

[User] Also include the latest transaction timestamp for each address.

[Assistant]
SELECT a.address_id, a.balance, COUNT(t.transaction_id) AS received_count, MAX(t.timestamp) AS last_received
FROM blockchain.addresses a
LEFT JOIN blockchain.transactions t ON a.address_id = t.receiver_address
WHERE a.balance < 50
GROUP BY a.address_id, a.balance
HAVING COUNT(t.transaction_id) >= 5;

[User] I need to list each user’s ID, email, and the total amount they've sent in transactions.

[Assistant]
SELECT u.user_id, u.email, COALESCE(SUM(t.amount), 0) AS total_sent
FROM blockchain.users u
JOIN blockchain.wallets w ON u.user_id = w.user_id
JOIN blockchain.transactions t ON w.address_id = t.sender_address
GROUP BY u.user_id, u.email;

[User] Actually, I'd like to filter only those users who have sent more than 10000 in total.

[Assistant]
SELECT u.user_id, u.email, SUM(t.amount) AS total_sent
FROM blockchain.users u
JOIN blockchain.wallets w ON u.user_id = w.user_id
JOIN blockchain.transactions t ON w.address_id = t.sender_address
GROUP BY u.user_id, u.email
HAVING SUM(t.amount) > 10000;

[User] Can you also include the average transaction amount per user?

[Assistant]
SELECT u.user_id, u.email, SUM(t.amount) AS total_sent, AVG(t.amount) AS avg_sent
FROM blockchain.users u
JOIN blockchain.wallets w ON u.user_id = w.user_id
JOIN blockchain.transactions t ON w.address_id = t.sender_address
GROUP BY u.user_id, u.email
HAVING SUM(t.amount) > 10000;

[User] One more thing: restrict this to transactions from the last 30 days and order by total_sent descending.

[Assistant]
SELECT u.user_id, u.email, SUM(t.amount) AS total_sent, AVG(t.amount) AS avg_sent
FROM blockchain.users u
JOIN blockchain.wallets w ON u.user_id = w.user_id
JOIN blockchain.transactions t ON w.address_id = t.sender_address
WHERE t.timestamp >= current_date - INTERVAL '30 days'
GROUP BY u.user_id, u.email
HAVING SUM(t.amount) > 10000
ORDER BY total_sent DESC;

[User] Find all blocks where the difficulty is between 1000 and 2000.

[Assistant] SELECT * FROM blockchain.blocks WHERE difficulty BETWEEN 1000 AND 2000;

[User] Now filter these results to only show blocks mined after June 1, 2023.

[Assistant] SELECT * FROM blockchain.blocks WHERE difficulty BETWEEN 1000 AND 2000 AND timestamp > '2023-06-01';

[User] Actually, I want to see the count of such blocks grouped by month in 2023.

[Assistant]
SELECT DATE_TRUNC('month', timestamp) AS month, COUNT(*) AS block_count
FROM blockchain.blocks
WHERE difficulty BETWEEN 1000 AND 2000 AND timestamp BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY month
ORDER BY month;

[User] Can you also include the average difficulty for each month in the results?

[Assistant]
SELECT DATE_TRUNC('month', timestamp) AS month, COUNT(*) AS block_count, AVG(difficulty) AS avg_difficulty
FROM blockchain.blocks
WHERE difficulty BETWEEN 1000 AND 2000 AND timestamp BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY month
ORDER BY month;

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)

[User] For each trip, show the trip ID, vehicle ID, driver ID, and both the actual starting and ending location IDs.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id FROM transportation.trips;

[User] List all unique pairs of origin and destination location IDs that have been used in trips, and count how many trips have occurred for each pair.

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

[User] Find pairs of trip IDs where both trips departed on the same calendar day, shared the same origin and destination locations, but were distinct trips.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id;

[User] From those pairs, filter the results to only include pairs where the actual departure times were within 2 hours of each other.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date,
  t1.actual_departure AS actual_departure_1,
  t2.actual_departure AS actual_departure_2
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id
WHERE
  t1.actual_departure IS NOT NULL
  AND t2.actual_departure IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (t1.actual_departure - t2.actual_departure))) <= 7200;

[User] Show me the trip details including actual and scheduled times, and the difference between them for all trips associated with a specific driver, say driver_id 'DRV789'.

[Assistant]
SELECT
  trip_id,
  vehicle_id,
  scheduled_departure,
  actual_departure,
  scheduled_arrival,
  actual_arrival,
  status,
  (actual_departure - scheduled_departure) AS departure_delay,
  (actual_arrival - scheduled_arrival) AS arrival_delay
FROM transportation.trips
WHERE
  driver_id = 'DRV789';

[User] Now, focusing on driver 'DRV789', identify consecutive pairs of trips based on scheduled departure time. Show the trip IDs and scheduled times for both trips in each pair.

[Assistant]
SELECT
  t1.trip_id AS first_trip_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.trip_id AS next_trip_id,
  t2.scheduled_departure AS next_scheduled_departure
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.driver_id = t2.driver_id
WHERE
  t1.driver_id = 'DRV789'
  AND t2.scheduled_departure = (
    SELECT MIN(scheduled_departure)
    FROM transportation.trips AS t3
    WHERE
      t3.driver_id = t1.driver_id
      AND t3.scheduled_departure > t1.scheduled_departure
  )
ORDER BY
  t1.scheduled_departure;

[User] Filter these consecutive trips for driver 'DRV789' to only show pairs where the destination location of the first trip is the same as the origin location of the second trip.

[Assistant]
SELECT
  t1.trip_id AS first_trip_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t1.destination_location_id AS first_trip_destination,
  t2.trip_id AS next_trip_id,
  t2.scheduled_departure AS next_scheduled_departure,
  t2.origin_location_id AS next_trip_origin
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.driver_id = t2.driver_id
WHERE
  t1.driver_id = 'DRV789'
  AND t2.scheduled_departure = (
    SELECT MIN(scheduled_departure)
    FROM transportation.trips AS t3
    WHERE
      t3.driver_id = t1.driver_id
      AND t3.scheduled_departure > t1.scheduled_departure
  )
  AND t1.destination_location_id = t2.origin_location_id
ORDER BY
  t1.scheduled_departure;

[User] Show me all in-progress trips with their current locations (origin_location_id) and destinations, along with the scheduled vs actual departure time difference in minutes.

[Assistant] SELECT trip_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress';

[User] Can you also include the vehicle_id and driver_id, and order by the departure delay in descending order?

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress' ORDER BY departure_delay_minutes DESC;

[User] Now filter to only show trips that have been delayed by more than 30 minutes.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress' AND EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 > 30 ORDER BY departure_delay_minutes DESC;

[User] Show me the count of trips by status for each vehicle, but only include vehicles that have had more than 5 trips total.

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

[User] Now filter this to only show vehicles that have had at least 2 cancelled trips.

[Assistant] SELECT vehicle_id, COUNT(*) as cancelled_trips FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2;

[User] Combine both queries to show me vehicles with more than 5 total trips and at least 2 cancelled trips, along with their complete status distribution.

[Assistant] SELECT t.vehicle_id, t.status, COUNT(*) as trip_count FROM transportation.trips t JOIN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 5 INTERSECT SELECT vehicle_id FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2) v ON t.vehicle_id = v.vehicle_id GROUP BY t.vehicle_id, t.status;