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.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] Can you show me all user IDs that have both email and push notifications disabled, along with whether their profile is set to private?

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = false AND push_notifications_enabled = false;

[User] I also want to see the last time they updated their settings.

[Assistant] SELECT user_id, private_profile, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = false AND push_notifications_enabled = false;

[User] Show the user IDs of all users whose theme is set to 'blue'.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE theme = 'blue';

[User] Can you show me the user IDs and their theme settings for all users who have enabled email notifications and have updated their settings in 2024?

[Assistant] SELECT user_id, theme FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] What if I also want to see if their profile is private or not?

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] Actually, I want to see users who have both email AND push notifications enabled.

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] Now, limit the results to users whose theme is 'light' only.

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = TRUE AND theme = 'light' AND updated_at >= '2024-01-01';

[User] Show me all user IDs who changed their profile settings after June 1, 2024.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE updated_at > '2024-06-01';

[User] Which users have disabled both email and push notifications? Please provide their user IDs and whether their profiles are private.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE;

[User] Also, only include those users who have updated their settings in the last 60 days.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE AND updated_at >= NOW() - INTERVAL '60 days';

[User] List the user IDs, theme, and updated_at for users who have disabled email notifications, enabled push notifications, and have a private profile.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE;

[User] Now, only include those whose theme is set to 'light'.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light';

[User] Order these results by the updated_at timestamp in descending order.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light' ORDER BY updated_at DESC;

[User] Limit the results to the top 5.

[Assistant] SELECT user_id, theme, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = TRUE AND private_profile = TRUE AND theme = 'light' ORDER BY updated_at DESC LIMIT 5;

[User] Count the total number of users who have enabled email notifications but disabled push notifications.

[Assistant] SELECT COUNT(*) FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = FALSE;


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 project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )

[User] What is the total investment_value per fundraising round for the year 2023? Order by total investment descending.

[Assistant]
SELECT
  substr(investment_date,1,7) AS month,
  rounds_name,
  SUM(investment_value) AS total_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%'
GROUP BY substr(investment_date,1,7), rounds_name
ORDER BY total_investment DESC;

[User] Which project had the largest single fundraising in each investment round, along with the round's name and introduction?

[Assistant] SELECT t1.project_name, t1.rounds_name, t1.investment_value, t1.introduction FROM project_fundraising_record t1 INNER JOIN (SELECT rounds_name, MAX(investment_value) AS max_value FROM project_fundraising_record GROUP BY rounds_name) t2 ON t1.rounds_name = t2.rounds_name AND t1.investment_value = t2.max_value;

[User] Instead of just one, can you show the top two fundraisings in each round?

[Assistant] SELECT project_name, rounds_name, investment_value, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Can you add the valuation for each project in the output as well?

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Show me only those top two projects per round where the valuation is greater than 100 million.

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2 AND valuation > 100000000;

[User] How many projects raised funds in 2023?

[Assistant]
SELECT COUNT(*) AS project_count
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] Also provide the average investment_value for these projects.

[Assistant]
SELECT COUNT(*) AS project_count, AVG(investment_value) AS avg_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] Which projects raised funds in January 2022?

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] Please also show their introductions.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] List all fundraising rounds where the average investment amount exceeded $10M, and show how many projects participated in each round.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000;

[User] Now, only consider rounds with at least 3 projects.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3;

[User] Add the total raised amount in each selected round.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment, SUM(investment_value) AS total_raised FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3;

[User] Show the result ordered by total_raised in descending order, and only the top 2 rounds.

[Assistant] SELECT rounds_name, project_count, avg_investment, total_raised FROM (SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment, SUM(investment_value) AS total_raised FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3) t ORDER BY total_raised DESC LIMIT 2;

[User] Which project raised the highest investment_value in each fundraising round?

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Can you also include the project's valuation and introduction?

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Now, filter to only rounds where the maximum investment_value is greater than 2000000.

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
    HAVING MAX(investment_value) > 2000000
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Actually, only consider rounds in 2022 and order the results by the maximum investment_value descending.

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022-%'
    GROUP BY rounds_name
    HAVING MAX(investment_value) > 2000000
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment
ORDER BY m.max_investment DESC;

[User] How many fundraising rounds did each project complete?

[Assistant] SELECT project_name, COUNT(*) AS round_count FROM project_fundraising_record GROUP BY project_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 financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )

[User] Show me the average interest rate for each account_type.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate
FROM financial_services.accounts
GROUP BY account_type;

[User] Only include account types with at least 5 accounts and order by average_interest_rate ascending.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate, COUNT(*) AS account_count
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] Add the minimum and maximum interest rate for each account_type to the result.

[Assistant]
SELECT account_type, COUNT(*) AS account_count, AVG(interest_rate) AS average_interest_rate,
       MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] List all accounts with a balance below 1000, showing the account_id, account_number, and currency.

[Assistant]
SELECT account_id, account_number, currency
FROM financial_services.accounts
WHERE balance < 1000;

[User] Now, also include accounts with a negative balance and order the result by balance ascending.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE balance < 1000 OR balance < 0
ORDER BY balance ASC;

[User] I only want to see the accounts where status is not 'Closed'.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE (balance < 1000 OR balance < 0) AND status <> 'Closed'
ORDER BY balance ASC;

[User] What is the average balance for each account_type among accounts with status 'Open'?

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type;

[User] Exclude account types with fewer than 3 accounts.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3;

[User] Sort the results by average balance descending.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3 ORDER BY avg_balance DESC;

[User] List accounts that were opened in the same month and year as another account for the same customer, but have a different account type. Show the account_id, customer_id, account_type, and opened_date for these accounts.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type

[User] Only include pairs where the first account's balance is higher than the second account's balance.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type AND T1.balance  >  T2.balance

[User] I made a mistake, I want the second account's balance to be *lower* than the first account's balance.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type AND T2.balance  <  T1.balance

[User] Also, only show results where the account_type for the first account is 'Savings'.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type AND T2.balance  <  T1.balance AND T1.account_type  =  'Savings'

[User] List all accounts for customers who have at least one account with a balance over 10000 and another account with a balance under 1000. Show customer_id, account_id, account_type, balance, and currency.

[Assistant] SELECT account_id ,  customer_id ,  account_type ,  balance ,  currency FROM financial_services.accounts WHERE customer_id IN ( SELECT T1.customer_id FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id WHERE T1.balance  >  10000 AND T2.balance  <  1000 )

[User] Actually, I only want to see the accounts that meet the specific balance criteria (over 10k or under 1k), not all accounts for those customers. And only include accounts where the status is 'Open'.

[Assistant] SELECT account_id ,  customer_id ,  account_type ,  balance ,  currency FROM financial_services.accounts WHERE customer_id IN ( SELECT T1.customer_id FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id WHERE T1.balance  >  10000 AND T2.balance  <  1000 ) AND (balance  >  10000 OR balance  <  1000) AND status  =  'Open'

[User] Could you also include the opened_date and sort the results by customer_id, then by balance descending?

[Assistant] SELECT account_id ,  customer_id ,  account_type ,  balance ,  currency ,  opened_date FROM financial_services.accounts WHERE customer_id IN ( SELECT T1.customer_id FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id WHERE T1.balance  >  10000 AND T2.balance  <  1000 ) AND (balance  >  10000 OR balance  <  1000) AND status  =  'Open' ORDER BY customer_id ASC ,  balance DESC

[User] Could you list all pairs of active accounts for the same customer, showing customer_id, account_a, and account_b?

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active';

[User] Please only include account pairs where both balances exceed 1000.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000;

[User] Also, filter to accounts opened after 2022-01-01.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000 AND a.opened_date > '2022-01-01' AND b.opened_date > '2022-01-01';

[User] Finally, order the output by customer_id and account_a.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000 AND a.opened_date > '2022-01-01' AND b.opened_date > '2022-01-01' ORDER BY a.customer_id, a.account_number;

[User] List each customer's account in one currency along with another account in a different currency, showing customer_id, account_primary, currency_primary, account_secondary, and currency_secondary.

[Assistant] SELECT a.customer_id, a.account_number AS account_primary, a.currency AS currency_primary, b.account_number AS account_secondary, b.currency AS currency_secondary FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.currency <> b.currency;

[User] Now only include cases where the secondary account balance is greater than the primary account balance.

[Assistant] SELECT a.customer_id, a.account_number AS account_primary, a.currency AS currency_primary, b.account_number AS account_secondary, b.currency AS currency_secondary FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.currency <> b.currency AND b.balance > a.balance;

[User] Also, limit to customers who have created at least one account in 2023.

[Assistant] SELECT a.customer_id, a.account_number AS account_primary, a.currency AS currency_primary, b.account_number AS account_secondary, b.currency AS currency_secondary FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.currency <> b.currency AND b.balance > a.balance AND EXISTS (SELECT 1 FROM financial_services.accounts c WHERE c.customer_id = a.customer_id AND c.opened_date BETWEEN '2023-01-01' AND '2023-12-31');


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
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_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
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, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( 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 ( 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, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount 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_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( 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, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] Show me the historical balance entries for wallet address '0xabc...' and contract address '0xdef...', including the block number and amount.

[Assistant] SELECT block_number, amount FROM erc20_balances_historical WHERE wallet_address = '0xabc...' AND contract_address = '0xdef...'

[User] For these entries, please also include the token symbol and name by joining with the `token_metas` table.

[Assistant] SELECT T1.block_number, T1.amount, T2.symbol, T2.name FROM erc20_balances_historical AS T1 JOIN token_metas AS T2 ON T1.contract_address = T2.contract_address WHERE T1.wallet_address = '0xabc...' AND T1.contract_address = '0xdef...'

[User] Now, add the latest USD price for this token by joining the `token_prices_latest` table.

[Assistant] SELECT T1.block_number, T1.amount, T2.symbol, T2.name, T3.price FROM erc20_balances_historical AS T1 JOIN token_metas AS T2 ON T1.contract_address = T2.contract_address JOIN token_prices_latest AS T3 ON T2.contract_address = T3.address WHERE T1.wallet_address = '0xabc...' AND T1.contract_address = '0xdef...'

[User] Finally, filter the results to only show historical entries where the latest USD price is greater than 100.

[Assistant] SELECT T1.block_number, T1.amount, T2.symbol, T2.name, T3.price FROM erc20_balances_historical AS T1 JOIN token_metas AS T2 ON T1.contract_address = T2.contract_address JOIN token_prices_latest AS T3 ON T2.contract_address = T3.address WHERE T1.wallet_address = '0xabc...' AND T1.contract_address = '0xdef...' AND T3.price > 100

[User] How many total records are there in the `erc20_approval` table?

[Assistant] SELECT COUNT(*) FROM erc20_approval

[User] And how many records are in the `erc1155_approval_for_all` table?

[Assistant] SELECT COUNT(*) FROM erc1155_approval_for_all

[User] List all unique wallet addresses that are present in the `nft_holders` table.

[Assistant] SELECT DISTINCT wallet_address FROM nft_holders

[User] How many unique wallet addresses have ever held an ERC20 token according to the `erc20_balances_historical` table?

[Assistant] SELECT COUNT(DISTINCT wallet_address) FROM erc20_balances_historical

[User] For Avalanche tokens, show me the token `tick`, `creator`, and `max_supply` from the `token_info_avalanche` table.

[Assistant] SELECT tick, creator, max_supply FROM token_info_avalanche

[User] Now, for each of these ticks, calculate the total transfer volume (`amt`) from the `token_activities_avalanche` table over the last 30 days.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply

[User] Filter the results to only include ticks where the `total_volume` is greater than 10000.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply HAVING SUM(T1.amt) > 10000

[User] How many NFTs are currently held for each contract address and token ID? Please show contract address, token id, and total amount held.

[Assistant] SELECT contract_address, token_id, SUM(CAST(amount AS BIGINT)) as total_held FROM nft_holders GROUP BY contract_address, token_id;

[User] Can you also show the highest rarity_score for each NFT from the nft_metadata table?

[Assistant]
SELECT h.contract_address, h.token_id, SUM(CAST(h.amount AS BIGINT)) as total_held, MAX(m.rarity_score) as max_rarity_score
FROM nft_holders h
LEFT JOIN nft_metadata m ON h.contract_address = m.contract_address AND h.token_id = m.token_id
GROUP BY h.contract_address, h.token_id;

[User] Now, only show NFTs where the max_rarity_score is above 90 and list them in descending order of total_held.

[Assistant]
SELECT h.contract_address, h.token_id, SUM(CAST(h.amount AS BIGINT)) as total_held, MAX(m.rarity_score) as max_rarity_score
FROM nft_holders h
LEFT JOIN nft_metadata m ON h.contract_address = m.contract_address AND h.token_id = m.token_id
GROUP BY h.contract_address, h.token_id
HAVING MAX(m.rarity_score) > 90
ORDER BY total_held DESC;

[User] For Sui coins, can you show the coin_type and owner address for each coin where the balance is greater than 100000?

[Assistant] SELECT coin_type, owner FROM sui_coins WHERE CAST(balance AS NUMERIC) > 100000;

[User] Can you also show the symbol and name for each coin by joining with sui_coins_metadata?

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS NUMERIC) > 100000;

[User] Limit the results to only coins where the metadata status is 'exists' and sort the output by owner address ascending.

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

[User] Actually, only show coins owned by addresses starting with '0xabc' and display the first 5 results only.

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS NUMERIC) > 100000 AND scm.status = 'exists' AND sc.owner LIKE '0xabc%' ORDER BY sc.owner ASC LIMIT 5;

[User] List the object ID, collection type, and owner for all Sui NFTs with status 'exists'.

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

[User] Now, only include NFTs from collections with package ID starting with '0x123'.

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

[User] Also show the name of each NFT and order the results by name ascending.

[Assistant] SELECT object_id, collection_type, owner, name FROM sui_nfts WHERE status = 'exists' AND package_id LIKE '0x123%' ORDER BY name ASC;

[User] Show me the total balance for each SUI coin type for coins with status 'exists'. Include the coin type and the sum of balances.

[Assistant] SELECT coin_type, SUM(CAST(balance AS DECIMAL)) AS total_balance FROM sui_coins WHERE status = 'exists' GROUP BY coin_type

[User] Add the symbol and name for each coin type by joining with the metadata table. Only include metadata entries where status is also 'exists'.

[Assistant] SELECT t1.coin_type, t2.symbol, t2.name, SUM(CAST(t1.balance AS DECIMAL)) AS total_balance FROM sui_coins AS t1 JOIN sui_coins_metadata AS t2 ON t1.coin_type = t2.coin_type WHERE t1.status = 'exists' AND t2.status = 'exists' GROUP BY t1.coin_type, t2.symbol, t2.name

[User] Only show coin types where the total balance is greater than 1000000000000 and order by total balance descending.

[Assistant] SELECT t1.coin_type, t2.symbol, t2.name, SUM(CAST(t1.balance AS DECIMAL)) AS total_balance FROM sui_coins AS t1 JOIN sui_coins_metadata AS t2 ON t1.coin_type = t2.coin_type WHERE t1.status = 'exists' AND t2.status = 'exists' GROUP BY t1.coin_type, t2.symbol, t2.name HAVING SUM(CAST(t1.balance AS DECIMAL)) > 1000000000000 ORDER BY total_balance DESC

[User] Filter these results further to only include coin types whose description in the metadata contains 'Liquid Staking'. Limit to the top 5.

[Assistant] SELECT t1.coin_type, t2.symbol, t2.name, SUM(CAST(t1.balance AS DECIMAL)) AS total_balance FROM sui_coins AS t1 JOIN sui_coins_metadata AS t2 ON t1.coin_type = t2.coin_type WHERE t1.status = 'exists' AND t2.status = 'exists' AND t2.description LIKE '%Liquid Staking%' GROUP BY t1.coin_type, t2.symbol, t2.name HAVING SUM(CAST(t1.balance AS DECIMAL)) > 1000000000000 ORDER BY total_balance DESC 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 hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )

[User] Get all pairs of services from the same department where one service is more expensive than another. Show department, service1_name, price1, service2_name, price2.

[Assistant] SELECT s1.department, s1.service_name AS service1_name, s1.price AS price1, s2.service_name AS service2_name, s2.price AS price2 FROM hospitality_technology.services s1 JOIN hospitality_technology.services s2 ON s1.department = s2.department AND s1.price > s2.price;

[User] Now only show pairs where the price difference is greater than 50.

[Assistant] SELECT s1.department, s1.service_name AS service1_name, s1.price AS price1, s2.service_name AS service2_name, s2.price AS price2 FROM hospitality_technology.services s1 JOIN hospitality_technology.services s2 ON s1.department = s2.department AND s1.price > s2.price WHERE s1.price - s2.price > 50;

[User] What is the average price of services grouped by category? Display category and average_price.

[Assistant] SELECT category, AVG(price) AS average_price FROM hospitality_technology.services GROUP BY category;

[User] Only include categories where the average_price is above 100 and order by average_price descending.

[Assistant] SELECT category, AVG(price) AS average_price FROM hospitality_technology.services GROUP BY category HAVING AVG(price) > 100 ORDER BY average_price DESC;

[User] For each department, what is the highest priced available service? Please show department, service_name, and price.

[Assistant] SELECT department, service_name, price FROM hospitality_technology.services WHERE is_available = TRUE AND (department, price) IN (SELECT department, MAX(price) FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department);

[User] The SQL failed due to using a tuple in the IN clause. Can you rewrite it in a way that's compatible with most databases?

[Assistant] SELECT s.department, s.service_name, s.price FROM hospitality_technology.services s JOIN (SELECT department, MAX(price) AS max_price FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department) sub ON s.department = sub.department AND s.price = sub.max_price WHERE s.is_available = TRUE;

[User] Now, only show departments where the maximum price is over 150.

[Assistant] SELECT s.department, s.service_name, s.price FROM hospitality_technology.services s JOIN (SELECT department, MAX(price) AS max_price FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department) sub ON s.department = sub.department AND s.price = sub.max_price WHERE s.is_available = TRUE AND sub.max_price > 150;

[User] Which available services in the 'Wellness' category are offered by each property? Please show property_id, service_name, and price.

[Assistant] SELECT property_id, service_name, price FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = TRUE;

[User] Instead, show only those services with a price greater than 80 and include the department in the result.

[Assistant] SELECT property_id, service_name, price, department FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = TRUE AND price > 80;

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

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

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

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

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

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

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

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

[User] Show me all services that have a price above 100, including their service_id, service_name, and category.

[Assistant]
SELECT service_id, service_name, category
FROM hospitality_technology.services
WHERE price > 100;

[User] Actually, can you also include the property_id and only list services that are currently available?

[Assistant]
SELECT service_id, service_name, category, property_id
FROM hospitality_technology.services
WHERE price > 100 AND is_available = TRUE;

[User] Can you give me the number of available services and their average price for each department?

[Assistant]
SELECT department, COUNT(*) AS available_services_count, AVG(price) AS average_price
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY department;

[User] I want the result to only include departments where the average price is above 80.

[Assistant]
SELECT department, COUNT(*) AS available_services_count, AVG(price) AS average_price
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY department
HAVING AVG(price) > 80;

[User] Also, show the minimum and maximum price of available services for each of those departments.

[Assistant]
SELECT department, COUNT(*) AS available_services_count, AVG(price) AS average_price, MIN(price) AS min_price, MAX(price) AS max_price
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY department
HAVING AVG(price) > 80;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] List all peers with their IP addresses who have not been seen in the last 7 days.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen < NOW() - INTERVAL '7 days';

[User] Count the number of metadata entries for each asset.

[Assistant]
SELECT asset_id, COUNT(*) AS metadata_count
FROM trading_platform.metadata
GROUP BY asset_id;

[User] Show me, for each wallet address, the total sum of amounts for all unspent UTXOs, along with the user ID who owns the wallet.

[Assistant]
SELECT w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.address, w.user_id;

[User] Now, include only the wallets where the total unspent amount is greater than 50, and show the wallet_id as well.

[Assistant]
SELECT w.wallet_id, w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.wallet_id, w.address, w.user_id
HAVING COALESCE(SUM(u.amount), 0) > 50;

[User] List the asset names and symbols for all assets of type 'token'.

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

[User] Show me the order ID, order type, and asset name for all orders that resulted in at least one trade.

[Assistant] SELECT DISTINCT o.order_id, o.order_type, a.name FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id;

[User] The previous result shows duplicate order IDs if an order had multiple trades. I only want each order listed once. Also, add the total quantity traded for each order, not the quantity from the order table itself.

[Assistant] SELECT o.order_id, o.order_type, a.name, SUM(t.quantity) AS total_traded_quantity FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id GROUP BY o.order_id, o.order_type, a.name;

[User] That's better. Now, only show 'buy' orders where the total traded quantity is greater than 50.

[Assistant] SELECT o.order_id, o.order_type, a.name, SUM(t.quantity) AS total_traded_quantity FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id WHERE o.order_type = 'buy' GROUP BY o.order_id, o.order_type, a.name HAVING SUM(t.quantity) > 50;

[User] Can you also include the user ID of the user who placed the order?

[Assistant] SELECT o.order_id, o.user_id, o.order_type, a.name, SUM(t.quantity) AS total_traded_quantity FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id WHERE o.order_type = 'buy' GROUP BY o.order_id, o.user_id, o.order_type, a.name HAVING SUM(t.quantity) > 50;

[User] List peer IDs and IP addresses for all peers whose IP address starts with '10.'.

[Assistant] SELECT peer_id, ip_address FROM trading_platform.peers WHERE ip_address LIKE '10.%';

[User] List user IDs with approved KYC status and the addresses of their wallets.

[Assistant] SELECT DISTINCT w.user_id, w.address FROM trading_platform.wallets w JOIN trading_platform.kyc_audit k ON w.user_id = k.user_id WHERE k.status = 'approved';

[User] From that list, also show the total number of unspent UTXOs associated with each wallet address.

[Assistant] SELECT w.user_id, w.address, COUNT(u.utxo_id) AS unspent_utxo_count FROM trading_platform.wallets w JOIN trading_platform.kyc_audit k ON w.user_id = k.user_id JOIN trading_platform.utxos u ON w.address = u.address WHERE k.status = 'approved' AND u.spent = FALSE GROUP BY w.user_id, w.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 healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Retrieve all unique chief complaints from medical_records.

[Assistant]
SELECT DISTINCT chief_complaint
FROM healthcare.medical_records;

[User] Now show chief complaints that occur more than 3 times along with their occurrence count.

[Assistant]
SELECT chief_complaint,
       COUNT(*) AS complaint_count
FROM healthcare.medical_records
GROUP BY chief_complaint
HAVING COUNT(*) > 3;

[User] Show prescriptions with their corresponding chief complaint from the medical record. Return prescription_id, record_id, and chief_complaint.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id;

[User] Only include prescriptions where chief_complaint contains 'fever' and the route is 'Oral'.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral';

[User] Also include the medication_name by joining the medications table and sort the results by prescription_date ascending.

[Assistant]
SELECT p.prescription_id,
       p.record_id,
       mr.chief_complaint,
       m.medication_name
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
LEFT JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral'
ORDER BY p.prescription_date ASC;

[User] List scheduled appointments, including the patient's full name, the doctor's full name, and the appointment time.

[Assistant] SELECT p.first_name, p.last_name, d.first_name, d.last_name, a.appointment_time FROM healthcare.appointments AS a JOIN healthcare.patients AS p ON a.patient_id = p.patient_id JOIN healthcare.doctors AS d ON a.doctor_id = d.doctor_id WHERE a.status = 'scheduled'

[User] Now, refine the results to only include appointments where the doctor's specialty is 'Cardiology'.

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

[User] Further filter these cardiology appointments to those occurring after '2024-07-01'.

[Assistant] SELECT p.first_name, p.last_name, d.first_name, d.last_name, a.appointment_time FROM healthcare.appointments AS a JOIN healthcare.patients AS p ON a.patient_id = p.patient_id JOIN healthcare.doctors AS d ON a.doctor_id = d.doctor_id WHERE a.status = 'scheduled' AND d.specialty = 'Cardiology' AND a.appointment_time > '2024-07-01'

[User] Also, include the appointment duration and order the results by appointment time ascending.

[Assistant] SELECT p.first_name, p.last_name, d.first_name, d.last_name, a.appointment_time, a.duration_minutes FROM healthcare.appointments AS a JOIN healthcare.patients AS p ON a.patient_id = p.patient_id JOIN healthcare.doctors AS d ON a.doctor_id = d.doctor_id WHERE a.status = 'scheduled' AND d.specialty = 'Cardiology' AND a.appointment_time > '2024-07-01' ORDER BY a.appointment_time ASC

[User] List all prescriptions, showing the prescription ID, the medication name, and the dosage.

[Assistant] SELECT p.prescription_id, m.medication_name, p.dosage FROM healthcare.prescriptions AS p JOIN healthcare.medications AS m ON p.medication_id = m.medication_id

[User] Count the number of medications provided by the manufacturer 'Novartis'.

[Assistant] SELECT count(*) FROM healthcare.medications WHERE manufacturer = 'Novartis'

[User] Show a list of patients along with their most recent diagnoses, including patient ID, diagnosis description, and the diagnosis date.

[Assistant] SELECT d.patient_id, d.description AS diagnosis_description, d.diagnosis_date FROM healthcare.diagnoses d INNER JOIN (SELECT patient_id, MAX(diagnosis_date) AS latest_date FROM healthcare.diagnoses GROUP BY patient_id) latest ON d.patient_id = latest.patient_id AND d.diagnosis_date = latest.latest_date;

[User] Add the doctor's full name who made each diagnosis to the results.

[Assistant] SELECT d.patient_id, doc.first_name || ' ' || doc.last_name AS doctor_full_name, d.description AS diagnosis_description, d.diagnosis_date FROM healthcare.diagnoses d INNER JOIN (SELECT patient_id, MAX(diagnosis_date) AS latest_date FROM healthcare.diagnoses GROUP BY patient_id) latest ON d.patient_id = latest.patient_id AND d.diagnosis_date = latest.latest_date INNER JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_id;

[User] Could you also include the diagnosis code in the output?

[Assistant] SELECT d.patient_id, doc.first_name || ' ' || doc.last_name AS doctor_full_name, d.diagnosis_code, d.description AS diagnosis_description, d.diagnosis_date FROM healthcare.diagnoses d INNER JOIN (SELECT patient_id, MAX(diagnosis_date) AS latest_date FROM healthcare.diagnoses GROUP BY patient_id) latest ON d.patient_id = latest.patient_id AND d.diagnosis_date = latest.latest_date INNER JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_id;

[User] List all appointments, showing the appointment ID, appointment time, patient's insurance plan name, and status.

[Assistant] SELECT a.appointment_id, a.appointment_time, ip.plan_name, a.status FROM healthcare.appointments a LEFT JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = TRUE LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id;

[User] Only show appointments where the status is 'Scheduled'.

[Assistant] SELECT a.appointment_id, a.appointment_time, ip.plan_name, a.status FROM healthcare.appointments a LEFT JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = TRUE LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE a.status = 'Scheduled';


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.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] Provide the message_subject and agency_name for all notifications that are related to agencies and have a status of 'Sent'.

[Assistant]
SELECT n.message_subject, a.agency_name
FROM government_services.notifications n
JOIN government_services.agencies a ON n.related_entity_id = a.agency_id
WHERE n.related_entity_type = 'agency' AND n.status = 'Sent';

[User] Show me the daily number of notifications sent in March 2024.

[Assistant]
SELECT DATE(sent_at) AS date, COUNT(*) AS notification_count
FROM government_services.notifications
WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
GROUP BY DATE(sent_at);

[User] Now break down those daily counts by channel.

[Assistant]
SELECT DATE(sent_at) AS date, channel, COUNT(*) AS notification_count
FROM government_services.notifications
WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
GROUP BY DATE(sent_at), channel;

[User] Exclude channels that have fewer than 20 notifications total for March 2024.

[Assistant]
WITH daily AS (
  SELECT DATE(sent_at) AS date, channel, COUNT(*) AS notification_count
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY DATE(sent_at), channel
),
channel_totals AS (
  SELECT channel
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY channel
  HAVING COUNT(*) >= 20
)
SELECT d.date, d.channel, d.notification_count
FROM daily d
JOIN channel_totals t ON d.channel = t.channel;

[User] Also include the most recent sent_at timestamp for each channel per day.

[Assistant]
WITH daily AS (
  SELECT DATE(sent_at) AS date,
         channel,
         COUNT(*) AS notification_count,
         MAX(sent_at) AS latest_sent
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY DATE(sent_at), channel
),
channel_totals AS (
  SELECT channel
  FROM government_services.notifications
  WHERE sent_at >= '2024-03-01' AND sent_at < '2024-04-01'
  GROUP BY channel
  HAVING COUNT(*) >= 20
)
SELECT d.date, d.channel, d.notification_count, d.latest_sent
FROM daily d
JOIN channel_totals t ON d.channel = t.channel;

[User] List the name of each agency and the total number of service locations it operates in New York State.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS location_count
FROM government_services.agencies a
LEFT JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.state = 'NY'
GROUP BY a.agency_name;

[User] Actually, only include those service locations that are accessible.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS location_count
FROM government_services.agencies a
LEFT JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.state = 'NY' AND sl.is_accessible = TRUE
GROUP BY a.agency_name;

[User] List the first_name, last_name, and registration_date of citizens who registered in 2023 but are still not verified.

[Assistant]
SELECT first_name,
       last_name,
       registration_date
FROM government_services.citizens
WHERE registration_date >= '2023-01-01'
  AND registration_date <  '2024-01-01'
  AND is_verified = FALSE;

[User] Retrieve all notifications with status 'failed' along with the citizen's full name and contact_phone for those notifications that occurred in the past 30 days.

[Assistant]
SELECT n.notification_id,
       n.sent_at,
       n.status,
       c.first_name || ' ' || c.last_name AS full_name,
       c.contact_phone
FROM government_services.notifications n
JOIN government_services.citizens c
  ON n.citizen_id = c.citizen_id
WHERE n.status = 'failed'
  AND n.sent_at >= NOW() - INTERVAL '30 days';

[User] Find the citizen_id, full name, contact_email, and the number of notifications each citizen has received in the last 7 days. Only include citizens who have received at least 3 notifications.

[Assistant]
SELECT c.citizen_id,
       c.first_name || ' ' || c.last_name AS full_name,
       c.contact_email,
       COUNT(n.notification_id) AS notification_count
FROM government_services.citizens c
JOIN government_services.notifications n
  ON c.citizen_id = n.citizen_id
WHERE n.sent_at >= NOW() - INTERVAL '7 days'
GROUP BY c.citizen_id, c.first_name, c.last_name, c.contact_email
HAVING COUNT(n.notification_id) >= 3;

[User] How many notifications related to services were sent for each service category in the past 7 days?

[Assistant]
SELECT
  s.category,
  COUNT(n.notification_id) AS notification_count
FROM
  government_services.notifications n
  JOIN government_services.services s
    ON n.related_entity_type = 'service'
    AND n.related_entity_id = s.service_id
WHERE
  n.sent_at >= NOW() - INTERVAL '7 days'
GROUP BY
  s.category;


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.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )

[User] Find pairs of consecutive maintenance logs for the same vehicle based on service date. Show the vehicle ID, log IDs, service dates, and odometer readings for both logs in each pair.

[Assistant] SELECT vehicle_id, log_id, service_date, odometer_reading, LAG(log_id) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_log_id, LAG(service_date) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_service_date, LAG(odometer_reading) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_odometer_reading FROM transportation.maintenance_logs ORDER BY vehicle_id, service_date, log_id;

[User] Only show pairs where the odometer reading increased by more than 10000 miles between the consecutive logs.

[Assistant] SELECT vehicle_id, log_id, service_date, odometer_reading, previous_log_id, previous_service_date, previous_odometer_reading FROM ( SELECT vehicle_id, log_id, service_date, odometer_reading, LAG(log_id) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_log_id, LAG(service_date) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_service_date, LAG(odometer_reading) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_odometer_reading FROM transportation.maintenance_logs ) AS subquery WHERE odometer_reading - previous_odometer_reading > 10000 AND previous_log_id IS NOT NULL ORDER BY vehicle_id, service_date;

[User] Also include the service type and cost for the current log entry. Filter results to logs performed in 2023 or later.

[Assistant] SELECT vehicle_id, log_id, service_date, odometer_reading, previous_log_id, previous_service_date, previous_odometer_reading, service_type, cost FROM ( SELECT vehicle_id, log_id, service_date, odometer_reading, service_type, cost, LAG(log_id) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_log_id, LAG(service_date) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_service_date, LAG(odometer_reading) OVER (PARTITION BY vehicle_id ORDER BY service_date, log_id) AS previous_odometer_reading FROM transportation.maintenance_logs ) AS subquery WHERE odometer_reading - previous_odometer_reading > 10000 AND previous_log_id IS NOT NULL AND service_date >= '2023-01-01' ORDER BY vehicle_id, service_date;

[User] Show all maintenance logs where the 'next_service_due_date' is before the current date, including the log ID, service date, service type, and the overdue next service date.

[Assistant] SELECT log_id, service_date, service_type, next_service_due_date FROM transportation.maintenance_logs WHERE next_service_due_date < CURRENT_DATE;

[User] List the log ID, vehicle ID, service date, and cost for all maintenance logs where the cost exceeds 2000 and the odometer reading is greater than 100,000.

[Assistant] SELECT log_id, vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE cost > 2000 AND odometer_reading > 100000;

[User] From that list, also include the service type and mechanic name, and filter to only include 'Engine Service' types performed in the year 2023.

[Assistant] SELECT log_id, vehicle_id, service_date, cost, service_type, mechanic_name FROM transportation.maintenance_logs WHERE cost > 2000 AND odometer_reading > 100000 AND service_type = 'Engine Service' AND EXTRACT(YEAR FROM service_date) = 2023;

[User] Show me all maintenance logs that do not have a next service due date recorded. List the log ID, vehicle ID, and service date.

[Assistant] SELECT log_id, vehicle_id, service_date FROM transportation.maintenance_logs WHERE next_service_due_date IS NULL;

[User] For these logs with no next service date, please also include the description and the cost, and sort the results by service date descending.

[Assistant] SELECT log_id, vehicle_id, service_date, description, cost FROM transportation.maintenance_logs WHERE next_service_due_date IS NULL ORDER BY service_date DESC;

[User] Show me all maintenance logs for vehicles that had an 'Oil Change' service in the last 3 months, including the vehicle ID, service date, and cost.

[Assistant] SELECT vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Can you also include the mechanic name and order the results by the most expensive services first?

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' ORDER BY cost DESC;

[User] Now filter these results to only show oil changes that cost more than $100.

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' AND cost > 100 ORDER BY cost DESC;

[User] Show me every unique combination of mechanic and service type that has performed maintenance, and the total number of such services per combination.

[Assistant] SELECT mechanic_name, service_type, COUNT(*) AS total_services FROM transportation.maintenance_logs GROUP BY mechanic_name, service_type;

[User] Now, only display combinations where the total number of services equals or exceeds 3.

[Assistant] SELECT mechanic_name, service_type, COUNT(*) AS total_services FROM transportation.maintenance_logs GROUP BY mechanic_name, service_type HAVING COUNT(*) >= 3;

[User] For each maintenance log, find the upcoming scheduled service by joining on next_service_due_date matching another log's service_date. Show l1.log_id, l1.vehicle_id, l1.service_date, l2.log_id AS upcoming_log_id, and l2.service_date AS upcoming_service_date.

[Assistant]
SELECT
  l1.log_id,
  l1.vehicle_id,
  l1.service_date,
  l2.log_id AS upcoming_log_id,
  l2.service_date AS upcoming_service_date
FROM transportation.maintenance_logs l1
LEFT JOIN transportation.maintenance_logs l2
  ON l1.vehicle_id = l2.vehicle_id
  AND l1.next_service_due_date = l2.service_date;

[User] Actually, also include the upcoming mechanic name.

[Assistant]
SELECT
  l1.log_id,
  l1.vehicle_id,
  l1.service_date,
  l2.log_id AS upcoming_log_id,
  l2.service_date AS upcoming_service_date,
  l2.mechanic_name AS upcoming_mechanic
FROM transportation.maintenance_logs l1
LEFT JOIN transportation.maintenance_logs l2
  ON l1.vehicle_id = l2.vehicle_id
  AND l1.next_service_due_date = l2.service_date;

[User] Finally, filter out entries where there is no upcoming log (upcoming_log_id is null).

[Assistant]
SELECT
  l1.log_id,
  l1.vehicle_id,
  l1.service_date,
  l2.log_id AS upcoming_log_id,
  l2.service_date AS upcoming_service_date,
  l2.mechanic_name AS upcoming_mechanic
FROM transportation.maintenance_logs l1
JOIN transportation.maintenance_logs l2
  ON l1.vehicle_id = l2.vehicle_id
  AND l1.next_service_due_date = l2.service_date;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] List all trips with their trip_id, vehicle_id, and the corresponding origin_location_id and destination_location_id, but only where the origin and destination are not the same.

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)

[User] How many messages currently have a media file attached?

[Assistant] SELECT COUNT(*) FROM social_media.messages WHERE media_url IS NOT NULL;

[User] For each user, show their username and how many unique conversations they have sent at least one message in where the conversation is a group chat.

[Assistant] SELECT T1.username ,  COUNT(DISTINCT T2.conversation_id) FROM users AS T1 JOIN messages AS T2 ON T1.user_id  =  T2.sender_user_id JOIN group_chats AS T3 ON T2.conversation_id  =  T3.conversation_id GROUP BY T1.user_id

[User] Instead, show only users who have sent messages in more than one group chat, and include their email addresses.

[Assistant] SELECT T1.username ,  T1.email ,  COUNT(DISTINCT T2.conversation_id) FROM users AS T1 JOIN messages AS T2 ON T1.user_id  =  T2.sender_user_id JOIN group_chats AS T3 ON T2.conversation_id  =  T3.conversation_id GROUP BY T1.user_id HAVING COUNT(DISTINCT T2.conversation_id)  >  1

[User] Also add the most recent message time sent by each user in these group chats.

[Assistant] SELECT T1.username ,  T1.email ,  COUNT(DISTINCT T2.conversation_id) ,  MAX(T2.sent_at) FROM users AS T1 JOIN messages AS T2 ON T1.user_id  =  T2.sender_user_id JOIN group_chats AS T3 ON T2.conversation_id  =  T3.conversation_id GROUP BY T1.user_id HAVING COUNT(DISTINCT T2.conversation_id)  >  1

[User] List message IDs and their sent time for messages containing media attachments.

[Assistant] SELECT message_id ,  sent_at FROM social_media.messages WHERE media_type IS NOT NULL

[User] List the content and sent time for messages sent by user 'U101'.

[Assistant] SELECT content, sent_at FROM social_media.messages WHERE sender_user_id = 'U101';

[User] Could you also include the group name for those messages and only show messages sent in group chats?

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group';

[User] Now filter to include only messages sent in June 2024 and order them by sent time descending.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC;

[User] Also limit the results to the top 15.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC LIMIT 15;

[User] List the usernames of users who have sent messages containing the word 'urgent', along with the message content and sent time.

[Assistant] SELECT u.username, m.content, m.sent_at FROM social_media.messages m JOIN social_media.users u ON m.sender_user_id = u.user_id WHERE m.content LIKE '%urgent%';

[User] Only include messages sent in private conversations.

[Assistant] SELECT u.username, m.content, m.sent_at FROM social_media.messages m JOIN social_media.users u ON m.sender_user_id = u.user_id JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.content LIKE '%urgent%' AND c.type = 'private';

[User] Which users have sent messages in multiple different conversations? Show the user ID and the count of unique conversations.

[Assistant] SELECT sender_user_id, COUNT(DISTINCT conversation_id) AS unique_conversation_count FROM social_media.messages GROUP BY sender_user_id HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Okay, now filter this list to only show users who have sent messages in more than 5 unique conversations.

[Assistant] SELECT sender_user_id, COUNT(DISTINCT conversation_id) AS unique_conversation_count FROM social_media.messages GROUP BY sender_user_id HAVING COUNT(DISTINCT conversation_id) > 5;

[User] Additionally, show the timestamp of the first message sent by each of these users, and order the results by the unique conversation count descending.

[Assistant] SELECT sender_user_id, COUNT(DISTINCT conversation_id) AS unique_conversation_count, MIN(sent_at) AS first_message_time FROM social_media.messages GROUP BY sender_user_id HAVING COUNT(DISTINCT conversation_id) > 5 ORDER BY unique_conversation_count DESC;

[User] Find the fastest reply for each conversation, showing conversation_id, initial_message_id, reply_message_id, and response_time in seconds.

[Assistant]
SELECT m1.conversation_id,
       m1.message_id AS initial_message_id,
       m2.message_id AS reply_message_id,
       EXTRACT(EPOCH FROM (m2.sent_at - m1.sent_at)) AS response_time
FROM social_media.messages m1
JOIN social_media.messages m2
  ON m1.conversation_id = m2.conversation_id
  AND m2.sent_at > m1.sent_at
WHERE m1.sent_at = (
    SELECT MIN(sent_at)
    FROM social_media.messages
    WHERE conversation_id = m1.conversation_id
)
ORDER BY response_time ASC;

[User] Only include replies where both messages were sent on the same calendar day.

[Assistant]
SELECT m1.conversation_id,
       m1.message_id AS initial_message_id,
       m2.message_id AS reply_message_id,
       EXTRACT(EPOCH FROM (m2.sent_at - m1.sent_at)) AS response_time
FROM social_media.messages m1
JOIN social_media.messages m2
  ON m1.conversation_id = m2.conversation_id
  AND m2.sent_at > m1.sent_at
WHERE m1.sent_at = (
    SELECT MIN(sent_at)
    FROM social_media.messages
    WHERE conversation_id = m1.conversation_id
)
  AND DATE(m1.sent_at) = DATE(m2.sent_at)
ORDER BY response_time ASC;

[User] Also show the response time in minutes rounded to two decimals, and limit to the top 10 fastest replies overall.

[Assistant]
SELECT m1.conversation_id,
       m1.message_id AS initial_message_id,
       m2.message_id AS reply_message_id,
       EXTRACT(EPOCH FROM (m2.sent_at - m1.sent_at)) AS response_time_seconds,
       ROUND(EXTRACT(EPOCH FROM (m2.sent_at - m1.sent_at)) / 60, 2) AS response_time_minutes
FROM social_media.messages m1
JOIN social_media.messages m2
  ON m1.conversation_id = m2.conversation_id
  AND m2.sent_at > m1.sent_at
WHERE m1.sent_at = (
    SELECT MIN(sent_at)
    FROM social_media.messages
    WHERE conversation_id = m1.conversation_id
)
  AND DATE(m1.sent_at) = DATE(m2.sent_at)
ORDER BY response_time_seconds ASC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed int, prescription_date timestamp )

[User] Show prescription ID, patient ID, and medication ID for prescriptions that have a start date before their end date.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date;

[User] Only include those where the refills allowed is zero.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0;

[User] Further narrow down to prescriptions with a 'daily' frequency.

[Assistant] SELECT prescription_id, patient_id, medication_id FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0 AND frequency = 'daily';

[User] Count how many such prescriptions were issued by each doctor.

[Assistant] SELECT doctor_id, COUNT(*) FROM healthcare.prescriptions WHERE start_date IS NOT NULL AND end_date IS NOT NULL AND start_date < end_date AND refills_allowed = 0 AND frequency = 'daily' GROUP BY doctor_id;

[User] List each doctor and how many prescriptions they have written, sorted by the highest count first.

[Assistant]
SELECT doctor_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY doctor_id
ORDER BY prescription_count DESC;

[User] Find pairs of prescriptions issued to the same patient but for different medications, issued on the same date. Show the patient ID, the prescription IDs of the two prescriptions, and their medication IDs and prescription dates.

[Assistant] SELECT p1.patient_id, p1.prescription_id AS prescription1_id, p1.medication_id AS medication1_id, p2.prescription_id AS prescription2_id, p2.medication_id AS medication2_id, p1.prescription_date FROM healthcare.prescriptions p1 JOIN healthcare.prescriptions p2 ON p1.patient_id = p2.patient_id AND p1.prescription_date = p2.prescription_date AND p1.medication_id <> p2.medication_id AND p1.prescription_id < p2.prescription_id;

[User] Show me all prescriptions, including the prescription ID, medication ID, prescription date, and the prescribing doctor's ID, for patients who have received more than 2 prescriptions.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id
FROM healthcare.prescriptions
WHERE patient_id IN (
  SELECT patient_id
  FROM healthcare.prescriptions
  GROUP BY patient_id
  HAVING COUNT(*) > 2
);

[User] Only show prescriptions where the end_date is null, meaning the prescription is still ongoing.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id
FROM healthcare.prescriptions
WHERE end_date IS NULL
  AND patient_id IN (
    SELECT patient_id
    FROM healthcare.prescriptions
    GROUP BY patient_id
    HAVING COUNT(*) > 2
  );

[User] Add the dosage and quantity_dispensed fields to the result.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id, dosage, quantity_dispensed
FROM healthcare.prescriptions
WHERE end_date IS NULL
  AND patient_id IN (
    SELECT patient_id
    FROM healthcare.prescriptions
    GROUP BY patient_id
    HAVING COUNT(*) > 2
  );

[User] Now, restrict results to prescriptions written after January 1, 2024.

[Assistant]
SELECT prescription_id, medication_id, prescription_date, doctor_id, patient_id, dosage, quantity_dispensed
FROM healthcare.prescriptions
WHERE end_date IS NULL
  AND prescription_date > '2024-01-01'
  AND patient_id IN (
    SELECT patient_id
    FROM healthcare.prescriptions
    GROUP BY patient_id
    HAVING COUNT(*) > 2
  );

[User] List all distinct medication IDs that have been prescribed with more than 5 refills allowed.

[Assistant] SELECT DISTINCT medication_id FROM healthcare.prescriptions WHERE refills_allowed > 5;

[User] What is the average quantity_dispensed per route for prescriptions with start_date in 2024? Return route and avg_quantity.

[Assistant]
SELECT route,
       AVG(quantity_dispensed) AS avg_quantity
FROM healthcare.prescriptions
WHERE start_date >= '2024-01-01'
GROUP BY route;

[User] Refine to only include routes with more than 20 prescriptions and round avg_quantity to two decimal places.

[Assistant]
SELECT route,
       ROUND(AVG(quantity_dispensed), 2) AS avg_quantity
FROM healthcare.prescriptions
WHERE start_date >= '2024-01-01'
GROUP BY route
HAVING COUNT(*) > 20;

[User] For each prescription, find the next prescription for the same patient. Return current prescription_id, next_prescription_id, patient_id, and days between start dates.

[Assistant]
SELECT p1.patient_id,
       p1.prescription_id AS current_id,
       p2.prescription_id AS next_id,
       (p2.start_date - p1.start_date) AS days_between
FROM healthcare.prescriptions p1
JOIN healthcare.prescriptions p2
  ON p1.patient_id = p2.patient_id
 AND p2.start_date = (
       SELECT MIN(start_date)
       FROM healthcare.prescriptions p3
       WHERE p3.patient_id = p1.patient_id
         AND p3.start_date > p1.start_date
   );

[User] Only include pairs where days_between is less than 30 days.

[Assistant]
SELECT p1.patient_id,
       p1.prescription_id AS current_id,
       p2.prescription_id AS next_id,
       (p2.start_date - p1.start_date) AS days_between
FROM healthcare.prescriptions p1
JOIN healthcare.prescriptions p2
  ON p1.patient_id = p2.patient_id
 AND p2.start_date = (
       SELECT MIN(start_date)
       FROM healthcare.prescriptions p3
       WHERE p3.patient_id = p1.patient_id
         AND p3.start_date > p1.start_date
   )
WHERE (p2.start_date - p1.start_date) < 30;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )

[User] Show me the full name of every lawyer, their specialization, and the number of cases they are the lead lawyer for.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, l.specialization, COUNT(c.case_id) AS lead_case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
GROUP BY l.first_name, l.last_name, l.specialization;

[User] List all time entries showing the lawyer's full name, the case name, hours spent, and description.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, c.case_name, te.hours_spent, te.description
FROM legal_services.time_entries te
LEFT JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id
LEFT JOIN legal_services.cases c ON te.case_id = c.case_id;

[User] Only show entries where the description contains the word 'hearing'.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, c.case_name, te.hours_spent, te.description
FROM legal_services.time_entries te
LEFT JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id
LEFT JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.description ILIKE '%hearing%';

[User] Now, sort the results by hours spent in descending order and limit it to the top 10 entries.

[Assistant]
SELECT CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name, c.case_name, te.hours_spent, te.description
FROM legal_services.time_entries te
LEFT JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id
LEFT JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.description ILIKE '%hearing%'
ORDER BY te.hours_spent DESC
LIMIT 10;

[User] Show me the total billable hours and total billed amount for each lawyer who worked on 'Civil Litigation' cases in 2023, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
ORDER BY total_billed_amount DESC;

[User] Actually, I'd like to include only those lawyers who have at least 10 billable entries in that period.

[Assistant]
SELECT te.lawyer_id,
       SUM(te.hours_spent) AS total_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS total_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id
HAVING COUNT(*) >= 10
ORDER BY total_billed_amount DESC;

[User] Also break down the report by case, listing each lawyer and case_number along with their billable hours and billed amount per case, sorted by billed amount descending.

[Assistant]
SELECT te.lawyer_id,
       c.case_number,
       SUM(te.hours_spent) AS case_billable_hours,
       SUM(te.hours_spent * te.billing_rate) AS case_billed_amount
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = true
  AND te.is_billed = true
  AND c.case_type = 'Civil Litigation'
  AND te.date_worked BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY te.lawyer_id, c.case_number
ORDER BY case_billed_amount DESC;

[User] List all active clients with their client_id, first_name, last_name, and the website of their law firm, matching on company_name = firm_name.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
WHERE cl.status = 'active';

[User] Include only those law firms founded after 2010-01-01 and exclude any with no website.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
WHERE cl.status = 'active'
  AND lf.founded_date > '2010-01-01'
  AND lf.website IS NOT NULL;

[User] Also show the number of cases each client has opened.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website,
       COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
WHERE cl.status = 'active'
  AND lf.founded_date > '2010-01-01'
  AND lf.website IS NOT NULL
GROUP BY cl.client_id, cl.first_name, cl.last_name, lf.website;

[User] Finally, sort the results by case count descending and limit to the top 20.

[Assistant]
SELECT cl.client_id,
       cl.first_name,
       cl.last_name,
       lf.website,
       COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
WHERE cl.status = 'active'
  AND lf.founded_date > '2010-01-01'
  AND lf.website IS NOT NULL
GROUP BY cl.client_id, cl.first_name, cl.last_name, lf.website
ORDER BY case_count DESC
LIMIT 20;

[User] List all open cases with case_number, case_name, and the client's email and phone.

[Assistant]
SELECT c.case_number,
       c.case_name,
       cl.email,
       cl.phone
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
WHERE c.status = 'Open';

[User] Also include the law_firm name based on the client's company_name, and only include cases opened in the last 6 months.

[Assistant]
SELECT c.case_number,
       c.case_name,
       cl.email,
       cl.phone,
       lf.firm_name
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
LEFT JOIN legal_services.law_firms lf ON cl.company_name = lf.firm_name
WHERE c.status = 'Open'
  AND c.date_opened >= CURRENT_DATE - INTERVAL '6 months';

[User] Show me each lawyer’s full name and the count of distinct cases they have logged time against.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id
GROUP BY l.first_name, l.last_name;

[User] Only include lawyers who have worked on more than 3 distinct cases.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id
GROUP BY l.first_name, l.last_name
HAVING COUNT(DISTINCT te.case_id) > 3;

[User] Restrict the entries to those dated in 2024.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te
  ON l.lawyer_id = te.lawyer_id
  AND te.date_worked BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY l.first_name, l.last_name
HAVING COUNT(DISTINCT te.case_id) > 3;

[User] Also include their specialization in the result set.

[Assistant]
SELECT l.first_name || ' ' || l.last_name AS lawyer_name, l.specialization, COUNT(DISTINCT te.case_id) AS case_count
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te
  ON l.lawyer_id = te.lawyer_id
  AND te.date_worked BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY l.first_name, l.last_name, l.specialization
HAVING COUNT(DISTINCT te.case_id) > 3;

[User] I need the case_number and case_name along with the total billing amount (hours_spent * billing_rate) for cases that are currently open.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent * te.billing_rate) AS total_billing
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE c.status = 'Open'
GROUP BY c.case_number, c.case_name;

[User] Now order the results by total_billing in descending order and limit to the top 5.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent * te.billing_rate) AS total_billing
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE c.status = 'Open'
GROUP BY c.case_number, c.case_name
ORDER BY total_billing DESC
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 government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )

[User] How many documents are in each verification_status?

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

[User] Only include statuses with more than 100 documents.

[Assistant]
SELECT verification_status, COUNT(*) AS document_count
FROM government_services.documents
GROUP BY verification_status
HAVING COUNT(*) > 100;

[User] Order the results by document_count in descending order.

[Assistant]
SELECT verification_status, COUNT(*) AS document_count
FROM government_services.documents
GROUP BY verification_status
HAVING COUNT(*) > 100
ORDER BY document_count DESC;

[User] Also exclude documents where expiry_date is before today.

[Assistant]
SELECT verification_status, COUNT(*) AS document_count
FROM government_services.documents
WHERE expiry_date >= CURRENT_DATE
GROUP BY verification_status
HAVING COUNT(*) > 100
ORDER BY document_count DESC;

[User] Can you list pairs of documents uploaded by the same citizen? Show both document IDs and the citizen ID.

[Assistant]
SELECT d1.document_id AS document1, d2.document_id AS document2, d1.citizen_id
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.citizen_id = d2.citizen_id
  AND d1.document_id < d2.document_id;

[User] Now, only include pairs where at least one of the documents has a verification_status = 'Pending'.

[Assistant]
SELECT d1.document_id AS document1, d2.document_id AS document2, d1.citizen_id
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.citizen_id = d2.citizen_id
  AND d1.document_id < d2.document_id
WHERE d1.verification_status = 'Pending'
   OR d2.verification_status = 'Pending';

[User] List all document IDs and document types for documents that have been verified by an employee, along with the verification timestamp and the ID of the verifying employee.

[Assistant] SELECT document_id, document_type, verification_timestamp, verified_by_employee_id FROM government_services.documents WHERE verified_by_employee_id IS NOT NULL;

[User] How many documents were uploaded in the month of October 2023?

[Assistant] SELECT COUNT(*) FROM government_services.documents WHERE upload_timestamp >= '2023-10-01 00:00:00' AND upload_timestamp < '2023-11-01 00:00:00';

[User] For each employee who has verified documents, show their full name and the total number of documents they have verified with a status of 'Verified'.

[Assistant] SELECT e.full_name, COUNT(d.document_id) FROM government_services.documents d JOIN employees e ON d.verified_by_employee_id = e.employee_id WHERE d.verification_status = 'Verified' GROUP BY e.full_name;

[User] How many documents have a file reference assigned?

[Assistant] SELECT COUNT(*) FROM government_services.documents WHERE file_reference IS NOT NULL AND file_reference <> '';

[User] List the full names of employees who have verified 'Proof of Identity' documents.

[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.document_type = 'Proof of Identity';