System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] List all pairs of beneficiaries on the same policy, showing policy_id, beneficiary1_id, beneficiary1 first_name, beneficiary1 last_name, beneficiary2_id, beneficiary2 first_name, and beneficiary2 last_name.

[Assistant]
SELECT b1.policy_id,
       b1.beneficiary_id AS beneficiary1_id,
       b1.first_name AS beneficiary1_first,
       b1.last_name AS beneficiary1_last,
       b2.beneficiary_id AS beneficiary2_id,
       b2.first_name AS beneficiary2_first,
       b2.last_name AS beneficiary2_last
FROM insurance.policy_beneficiaries b1
JOIN insurance.policy_beneficiaries b2
  ON b1.policy_id = b2.policy_id
 AND b1.beneficiary_id < b2.beneficiary_id;

[User] Actually, only include pairs where the first beneficiary’s relationship is 'Spouse'.

[Assistant]
SELECT b1.policy_id,
       b1.beneficiary_id AS beneficiary1_id,
       b1.first_name AS beneficiary1_first,
       b1.last_name AS beneficiary1_last,
       b2.beneficiary_id AS beneficiary2_id,
       b2.first_name AS beneficiary2_first,
       b2.last_name AS beneficiary2_last
FROM insurance.policy_beneficiaries b1
JOIN insurance.policy_beneficiaries b2
  ON b1.policy_id = b2.policy_id
 AND b1.beneficiary_id < b2.beneficiary_id
WHERE b1.relationship = 'Spouse';

[User] And also filter to only include cases where the spouse's percentage_share is above 25%.

[Assistant]
SELECT b1.policy_id,
       b1.beneficiary_id AS beneficiary1_id,
       b1.first_name AS beneficiary1_first,
       b1.last_name AS beneficiary1_last,
       b2.beneficiary_id AS beneficiary2_id,
       b2.first_name AS beneficiary2_first,
       b2.last_name AS beneficiary2_last
FROM insurance.policy_beneficiaries b1
JOIN insurance.policy_beneficiaries b2
  ON b1.policy_id = b2.policy_id
 AND b1.beneficiary_id < b2.beneficiary_id
WHERE b1.relationship = 'Spouse'
  AND b1.percentage_share > 25;

[User] How many beneficiaries are there for each relationship type in the policy_beneficiaries table?

[Assistant]
SELECT relationship, COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship;

[User] List all beneficiaries who have a relationship of 'Parent' and a percentage_share less than 25%. Show their beneficiary_id, first_name, last_name, relationship, and percentage_share.

[Assistant]
SELECT beneficiary_id, first_name, last_name, relationship, percentage_share
FROM insurance.policy_beneficiaries
WHERE relationship = 'Parent' AND percentage_share < 25;

[User] List all beneficiaries who do not have any contact information provided. Show beneficiary_id, first_name, and last_name.

[Assistant] SELECT beneficiary_id, first_name, last_name FROM insurance.policy_beneficiaries WHERE contact_info IS NULL OR contact_info = ''

[User] Show me all policy beneficiaries who were added in the last 6 months, along with their full names and relationship to the policyholder.

[Assistant] SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months';

[User] Now filter these results to only show beneficiaries who have a percentage share greater than 30% and include their contact information.

[Assistant] SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share, contact_info FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30;

[User] I also want to see the customer_id for these policies and filter to only show beneficiaries who are listed as 'spouse' or 'child'.

[Assistant] SELECT beneficiary_id, policy_id, customer_id, first_name, last_name, relationship, percentage_share, contact_info FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30 AND relationship IN ('spouse', 'child');

[User] Finally, show me the count of such beneficiaries per policy_id.

[Assistant] SELECT policy_id, COUNT(*) AS beneficiary_count FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30 AND relationship IN ('spouse', 'child') GROUP BY policy_id;

[User] Who are the beneficiaries (first and last names) with a percentage_share over 40% for each policy? I would also like the policy_id.

[Assistant]
SELECT policy_id, first_name, last_name
FROM insurance.policy_beneficiaries
WHERE percentage_share > 40;

[User] Also include the beneficiary's relationship and show only those added after July 1, 2023.

[Assistant]
SELECT policy_id, first_name, last_name, relationship
FROM insurance.policy_beneficiaries
WHERE percentage_share > 40 AND added_at > '2023-07-01';

[User] Please sort the results by percentage_share descending.

[Assistant]
SELECT policy_id, first_name, last_name, relationship, percentage_share
FROM insurance.policy_beneficiaries
WHERE percentage_share > 40 AND added_at > '2023-07-01'
ORDER BY percentage_share DESC;

[User] Now, only show beneficiaries whose relationship is either 'Spouse' or 'Child'.

[Assistant]
SELECT policy_id, first_name, last_name, relationship, percentage_share
FROM insurance.policy_beneficiaries
WHERE percentage_share > 40 AND added_at > '2023-07-01' AND relationship IN ('Spouse', 'Child')
ORDER BY percentage_share DESC;

[User] List the first name, last name, and relationship for all beneficiaries whose percentage share is between 10 and 50, inclusive.

[Assistant] SELECT first_name, last_name, relationship FROM insurance.policy_beneficiaries WHERE percentage_share BETWEEN 10 AND 50;

[User] Could you also include the customer ID and policy ID for these beneficiaries?

[Assistant] SELECT customer_id, policy_id, first_name, last_name, relationship FROM insurance.policy_beneficiaries WHERE percentage_share BETWEEN 10 AND 50;

[User] Actually, only show beneficiaries who were added after January 1st, 2024.

[Assistant] SELECT customer_id, policy_id, first_name, last_name, relationship FROM insurance.policy_beneficiaries WHERE percentage_share BETWEEN 10 AND 50 AND added_at > '2024-01-01';

[User] How many beneficiaries were added on each unique date?

[Assistant] SELECT DATE(added_at), COUNT(*) FROM insurance.policy_beneficiaries GROUP BY DATE(added_at);

[User] Show all beneficiaries added in 2024. Include beneficiary_id, full name, relationship, percentage_share, and the added_at timestamp.

[Assistant]
SELECT beneficiary_id, first_name || ' ' || last_name AS full_name, relationship, percentage_share, added_at
FROM insurance.policy_beneficiaries
WHERE EXTRACT(YEAR FROM added_at) = 2024;

[User] I need to only see beneficiaries whose percentage_share is at least 20%. Please update the results.

[Assistant]
SELECT beneficiary_id, first_name || ' ' || last_name AS full_name, relationship, percentage_share, added_at
FROM insurance.policy_beneficiaries
WHERE EXTRACT(YEAR FROM added_at) = 2024
  AND percentage_share >= 20;

[User] Can you order the results by percentage_share in descending order and only include beneficiaries whose relationship is 'Child'?

[Assistant]
SELECT beneficiary_id, first_name || ' ' || last_name AS full_name, relationship, percentage_share, added_at
FROM insurance.policy_beneficiaries
WHERE EXTRACT(YEAR FROM added_at) = 2024
  AND percentage_share >= 20
  AND relationship = 'Child'
ORDER BY percentage_share DESC;

[User] I got an error about null values. Please update the query to exclude records where percentage_share is null.

[Assistant]
SELECT beneficiary_id, first_name || ' ' || last_name AS full_name, relationship, percentage_share, added_at
FROM insurance.policy_beneficiaries
WHERE EXTRACT(YEAR FROM added_at) = 2024
  AND percentage_share >= 20
  AND relationship = 'Child'
  AND percentage_share IS NOT NULL
ORDER BY percentage_share DESC;

[User] List all beneficiaries added in the last 6 months, showing their full names and relationship to the policyholder.

[Assistant] SELECT first_name, last_name, relationship FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months';

[User] Now include only those beneficiaries who have a contact_info field that contains an email address.

[Assistant] SELECT first_name, last_name, relationship FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND contact_info LIKE '%@%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
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 ( object_id text, status text, coin_type text, balance text, owner text )
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 nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, 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_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash 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 balance history of wallet '0xdeadbeef' for token at contract '0xaaaa...' .

[Assistant]
SELECT block_number, amount
FROM erc20_balances_historical
WHERE wallet_address = '0xdeadbeef'
  AND contract_address = '0xaaaa...';

[User] Only include entries after block 12000000.

[Assistant]
SELECT block_number, amount
FROM erc20_balances_historical
WHERE wallet_address = '0xdeadbeef'
  AND contract_address = '0xaaaa...'
  AND block_number > 12000000;

[User] Add the token symbol and decimals from token_metas.

[Assistant]
SELECT b.block_number,
       b.amount,
       m.symbol,
       m.decimals
FROM erc20_balances_historical b
JOIN token_metas m
  ON b.contract_address = m.contract_address
WHERE b.wallet_address = '0xdeadbeef'
  AND b.contract_address = '0xaaaa...'
  AND b.block_number > 12000000;

[User] Also include the latest price for each entry by joining with token_prices_latest.

[Assistant]
SELECT b.block_number,
       b.amount,
       m.symbol,
       m.decimals,
       p.price
FROM erc20_balances_historical b
JOIN token_metas m
  ON b.contract_address = m.contract_address
JOIN token_prices_latest p
  ON b.contract_address = p.address
WHERE b.wallet_address = '0xdeadbeef'
  AND b.contract_address = '0xaaaa...'
  AND b.block_number > 12000000;

[User] List all wallet addresses holding NFT contract '0xbbbb...' and token ID '99'.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xbbbb...'
  AND token_id = '99';

[User] How many unique holders are there?

[Assistant]
SELECT COUNT(DISTINCT wallet_address) AS unique_holders
FROM nft_holders
WHERE contract_address = '0xbbbb...'
  AND token_id = '99';

[User] Only include wallets holding more than one token.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xbbbb...'
  AND token_id = '99'
  AND CAST(amount AS numeric) > 1;

[User] Sort the result by amount descending and limit to top 5.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xbbbb...'
  AND token_id = '99'
  AND CAST(amount AS numeric) > 1
ORDER BY CAST(amount AS numeric) DESC
LIMIT 5;

[User] Get all active SUI coins with their owner and balance.

[Assistant]
SELECT coin_type, owner, balance
FROM sui_coins
WHERE status = 'active';

[User] Join metadata to include the coin symbol and decimals.

[Assistant]
SELECT c.coin_type,
       m.symbol,
       m.decimals,
       c.owner,
       c.balance
FROM sui_coins c
JOIN sui_coins_metadata m
  ON c.coin_type = m.coin_type
WHERE c.status = 'active';

[User] Only include coins where balance is greater than 500 and add the description.

[Assistant]
SELECT c.coin_type,
       m.symbol,
       m.decimals,
       m.description,
       c.owner,
       c.balance
FROM sui_coins c
JOIN sui_coins_metadata m
  ON c.coin_type = m.coin_type
WHERE c.status = 'active'
  AND CAST(c.balance AS numeric) > 500;

[User] Show the total balance for each SUI coin across all owners. Group by coin_type.

[Assistant]
SELECT coin_type,
       SUM(CAST(balance AS DECIMAL)) AS total_balance
FROM sui_coins
GROUP BY coin_type;

[User] Also include symbol, name, decimals and description from the metadata table by joining on coin_type.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description;

[User] Only include metadata entries where status = 'exists' and description contains the word 'staking'.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
WHERE scm.status = 'exists'
  AND scm.description ILIKE '%staking%'
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description;

[User] Sort the results by total_balance descending and limit to the top 3 coins.

[Assistant]
SELECT sc.coin_type,
       scm.symbol,
       scm.name,
       scm.decimals,
       scm.description,
       SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata scm
  ON sc.coin_type = scm.coin_type
WHERE scm.status = 'exists'
  AND scm.description ILIKE '%staking%'
GROUP BY sc.coin_type, scm.symbol, scm.name, scm.decimals, scm.description
ORDER BY total_balance DESC
LIMIT 3;

[User] List all Avalanche tokens where the circulating total supply is less than the maximum supply. Include tick, creator, max_supply, total_supply (sum of amount), and the difference between max_supply and total_supply.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick;

[User] Also include the number of holders and number of transactions (holders and txs) for each token.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick;

[User] Now restrict to tokens where the supply difference is greater than 1000 and only include records where the info block_number is above 500000.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick
WHERE (bi.max_supply - COALESCE(tb.total_supply, 0)) > 1000
  AND bi.block_number > 500000;

[User] Finally, sort the results by supply_diff descending and limit to the top 5 tokens.

[Assistant]
SELECT bi.tick,
       bi.creator,
       bi.max_supply,
       COALESCE(tb.total_supply, 0) AS total_supply,
       (bi.max_supply - COALESCE(tb.total_supply, 0)) AS supply_diff,
       bi.holders,
       bi.txs
FROM token_info_avalanche bi
LEFT JOIN (
  SELECT tick,
         SUM(amount) AS total_supply
  FROM token_balances_avalanche
  GROUP BY tick
) tb ON bi.tick = tb.tick
WHERE (bi.max_supply - COALESCE(tb.total_supply, 0)) > 1000
  AND bi.block_number > 500000
ORDER BY supply_diff DESC
LIMIT 5;

[User] Show me the total amount held and number of unique wallets for each ERC20 token with a symbol ending in 'X'.

[Assistant] SELECT tm.symbol, SUM(CAST(ebh.amount AS DECIMAL)) AS total_amount, COUNT(DISTINCT ebh.wallet_address) AS unique_wallets FROM token_metas tm JOIN erc20_balances_historical ebh ON tm.contract_address = ebh.contract_address WHERE tm.is_erc20 = 1 AND tm.symbol LIKE '%X' GROUP BY tm.symbol;

[User] Can you also include the token name and the contract address in your results?

[Assistant] SELECT tm.symbol, tm.name, tm.contract_address, SUM(CAST(ebh.amount AS DECIMAL)) AS total_amount, COUNT(DISTINCT ebh.wallet_address) AS unique_wallets FROM token_metas tm JOIN erc20_balances_historical ebh ON tm.contract_address = ebh.contract_address WHERE tm.is_erc20 = 1 AND tm.symbol LIKE '%X' GROUP BY tm.symbol, tm.name, tm.contract_address;

[User] Now, restrict the results to only those tokens where total_amount exceeds 1,000,000.

[Assistant] SELECT tm.symbol, tm.name, tm.contract_address, SUM(CAST(ebh.amount AS DECIMAL)) AS total_amount, COUNT(DISTINCT ebh.wallet_address) AS unique_wallets FROM token_metas tm JOIN erc20_balances_historical ebh ON tm.contract_address = ebh.contract_address WHERE tm.is_erc20 = 1 AND tm.symbol LIKE '%X' GROUP BY tm.symbol, tm.name, tm.contract_address HAVING SUM(CAST(ebh.amount AS DECIMAL)) > 1000000;

[User] Please sort the results by the total_amount in descending order and limit to the top 5 tokens.

[Assistant] SELECT tm.symbol, tm.name, tm.contract_address, SUM(CAST(ebh.amount AS DECIMAL)) AS total_amount, COUNT(DISTINCT ebh.wallet_address) AS unique_wallets FROM token_metas tm JOIN erc20_balances_historical ebh ON tm.contract_address = ebh.contract_address WHERE tm.is_erc20 = 1 AND tm.symbol LIKE '%X' GROUP BY tm.symbol, tm.name, tm.contract_address HAVING SUM(CAST(ebh.amount AS DECIMAL)) > 1000000 ORDER BY total_amount DESC LIMIT 5;

[User] List all NFTs minted in the last 30 days, including their contract address, token id, and minter address.

[Assistant] SELECT contract_address, token_id, minter FROM nft_metadata WHERE mint_time >= (strftime('%s', 'now') - 2592000);

[User] Can you add the current owner and the NFT's name from the metadata as well?

[Assistant] SELECT contract_address, token_id, minter, owner, name FROM nft_metadata WHERE mint_time >= (strftime('%s', 'now') - 2592000);

[User] Now, for each of those NFTs, show the collection name by joining with nft_collections.

[Assistant] SELECT nm.contract_address, nm.token_id, nm.minter, nm.owner, nm.name AS nft_name, nc.name AS collection_name FROM nft_metadata nm JOIN nft_collections nc ON nm.contract_address = nc.contract_address WHERE nm.mint_time >= (strftime('%s', 'now') - 2592000);

[User] Only include NFTs whose rarity_score is above 80 and order by rarity_score descending.

[Assistant] SELECT nm.contract_address, nm.token_id, nm.minter, nm.owner, nm.name AS nft_name, nc.name AS collection_name, nm.rarity_score FROM nft_metadata nm JOIN nft_collections nc ON nm.contract_address = nc.contract_address WHERE nm.mint_time >= (strftime('%s', 'now') - 2592000) AND nm.rarity_score > 80 ORDER BY nm.rarity_score DESC;

[User] Show me the top 5 NFT collections with the highest token count, along with their names, symbols, and floor prices, but only include collections with a floor price greater than 0.5 ETH.

[Assistant] SELECT nc.name, nc.symbol, nc.floor_price, nc.token_count FROM nft_collections nc WHERE nc.floor_price > '0.5' AND nc.erc_type = 'ERC721' ORDER BY nc.token_count DESC LIMIT 5;

[User] Can you also include the banner image URL for these collections and filter out collections with less than 1000 tokens?

[Assistant] SELECT nc.name, nc.symbol, nc.floor_price, nc.token_count, nc.banner_image_url FROM nft_collections nc WHERE nc.floor_price > '0.5' AND nc.erc_type = 'ERC721' AND nc.token_count >= 1000 ORDER BY nc.token_count DESC LIMIT 5;

[User] Now join this with the nft_metadata table to include the average rarity score for each collection.

[Assistant] SELECT nc.name, nc.symbol, nc.floor_price, nc.token_count, nc.banner_image_url, AVG(nm.rarity_score) as avg_rarity_score FROM nft_collections nc JOIN nft_metadata nm ON nc.contract_address = nm.contract_address WHERE nc.floor_price > '0.5' AND nc.erc_type = 'ERC721' AND nc.token_count >= 1000 GROUP BY nc.name, nc.symbol, nc.floor_price, nc.token_count, nc.banner_image_url ORDER BY nc.token_count DESC LIMIT 5;

[User] Show me the total transfer volume and number of transfers for each token tick on Bitcoin in the past 7 days.

[Assistant]
SELECT tick, SUM(amt) AS total_volume, COUNT(*) AS transfer_count
FROM token_activities_bitcoin
WHERE block_timestamp >= NOW() - INTERVAL '7 days'
GROUP BY tick;

[User] Can you also include the creator of each token by joining with token_info_bitcoin?

[Assistant]
SELECT ta.tick, ti.creator, SUM(ta.amt) AS total_volume, COUNT(*) AS transfer_count
FROM token_activities_bitcoin ta
LEFT JOIN (
    SELECT tick, creator FROM token_info_bitcoin WHERE (tick, block_timestamp) IN (
        SELECT tick, MAX(block_timestamp) FROM token_info_bitcoin GROUP BY tick
    )
) ti ON ta.tick = ti.tick
WHERE ta.block_timestamp >= NOW() - INTERVAL '7 days'
GROUP BY ta.tick, ti.creator;

[User] Only include tokens where the total_volume is greater than 1000 and sort by total_volume descending, limit to top 5 tokens.

[Assistant]
SELECT ta.tick, ti.creator, SUM(ta.amt) AS total_volume, COUNT(*) AS transfer_count
FROM token_activities_bitcoin ta
LEFT JOIN (
    SELECT tick, creator FROM token_info_bitcoin WHERE (tick, block_timestamp) IN (
        SELECT tick, MAX(block_timestamp) FROM token_info_bitcoin GROUP BY tick
    )
) ti ON ta.tick = ti.tick
WHERE ta.block_timestamp >= NOW() - INTERVAL '7 days'
GROUP BY ta.tick, ti.creator
HAVING SUM(ta.amt) > 1000
ORDER BY total_volume DESC
LIMIT 5;

[User] Find all ERC20 tokens (from token_metas) currently held by wallet '0xfoo...' with a balance over 1000. Show the contract address and amount.

[Assistant]
SELECT contract_address, amount
FROM erc20_balances
WHERE wallet_address = '0xfoo...'
  AND CAST(amount AS NUMERIC) > 1000;

[User] Add the symbol and name for each token by joining to token_metas.

[Assistant]
SELECT b.contract_address, b.amount, m.symbol, m.name
FROM erc20_balances b
JOIN token_metas m ON b.contract_address = m.contract_address
WHERE b.wallet_address = '0xfoo...'
  AND CAST(b.amount AS NUMERIC) > 1000;

[User] Actually, I want the results sorted by amount descending and limit to the top 5 tokens.

[Assistant]
SELECT b.contract_address, b.amount, m.symbol, m.name
FROM erc20_balances b
JOIN token_metas m ON b.contract_address = m.contract_address
WHERE b.wallet_address = '0xfoo...'
  AND CAST(b.amount AS NUMERIC) > 1000
ORDER BY CAST(b.amount AS NUMERIC) DESC
LIMIT 5;

[User] Can you also include how many decimal places each token uses?

[Assistant]
SELECT b.contract_address, b.amount, m.symbol, m.name, m.decimals
FROM erc20_balances b
JOIN token_metas m ON b.contract_address = m.contract_address
WHERE b.wallet_address = '0xfoo...'
  AND CAST(b.amount AS NUMERIC) > 1000
ORDER BY CAST(b.amount AS NUMERIC) 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 trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )

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

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

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

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

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

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

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

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

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

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

[User] Show the name of DApps and the count of metadata entries linked to them.

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

[User] Now, also include DApps that have no linked metadata, showing a count of 0, and order the list by DApp name.

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

[User] Forget the metadata counts. Just show me the names and descriptions of DApps where the description contains the word 'tool'.

[Assistant] SELECT name, description FROM trading_platform.dapps WHERE description ILIKE '%tool%';

[User] Okay, now for those 'tool' DApps, find any linked metadata entries. Show the DApp name, URL, and the metadata key and value.

[Assistant] SELECT d.name, d.url, m.key, m.value FROM trading_platform.dapps d JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id WHERE d.description ILIKE '%tool%';

[User] Show the number of UTXOs associated with each unique address in the system.

[Assistant] SELECT address, COUNT(utxo_id) FROM trading_platform.utxos GROUP BY address;

[User] List all assets that have at least one associated metadata entry, showing the asset name, symbol, and the key and value of each metadata entry.

[Assistant] SELECT a.name, a.symbol, m.key, m.value FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id;

[User] Only show metadata entries where the metadata key contains the word 'link' or 'id'.

[Assistant] SELECT a.name, a.symbol, m.key, m.value FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id WHERE m.key ILIKE '%link%' OR m.key ILIKE '%id%';

[User] Find all assets that have metadata linking them to a DApp (where metadata value is a DApp ID), showing asset name, symbol, and the linked DApp name. Assume the metadata key used is 'linked_dapp_id'.

[Assistant] SELECT a.name AS asset_name, a.symbol, d.name AS dapp_name FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id JOIN trading_platform.dapps d ON m.value = d.dapp_id WHERE m.key = 'linked_dapp_id';

[User] Only show results for assets whose type is 'cryptocurrency'.

[Assistant] SELECT a.name AS asset_name, a.symbol, d.name AS dapp_name FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id JOIN trading_platform.dapps d ON m.value = d.dapp_id WHERE m.key = 'linked_dapp_id' AND a.type = 'cryptocurrency';

[User] The query didn't work, it returned no results. Maybe the key isn't exactly 'linked_dapp_id'. Can you find assets linked to DApps where the metadata value looks like a DApp ID (starts with 'dapp') and display the metadata key used as well?

[Assistant] SELECT a.name AS asset_name, a.symbol, d.name AS dapp_name, m.key FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id JOIN trading_platform.dapps d ON m.value = d.dapp_id WHERE m.value LIKE 'dapp%';

[User] Okay, great, that worked. Now, only show assets where the metadata key used was 'associated_dapp' and order the results by asset name alphabetically.

[Assistant] SELECT a.name AS asset_name, a.symbol, d.name AS dapp_name, m.key FROM trading_platform.assets a JOIN trading_platform.metadata m ON a.asset_id = m.asset_id JOIN trading_platform.dapps d ON m.value = d.dapp_id WHERE m.key = 'associated_dapp' AND m.value LIKE 'dapp%' ORDER BY a.name;

[User] Show all DApps whose name starts with the letter 'C'.

[Assistant] SELECT * FROM trading_platform.dapps WHERE name ILIKE 'C%';

[User] Could you instead make it case-sensitive so only names that start with an uppercase 'C' are included?

[Assistant] SELECT * FROM trading_platform.dapps WHERE name LIKE 'C%';

[User] Actually, just show their names and descriptions.

[Assistant] SELECT name, description FROM trading_platform.dapps WHERE name LIKE 'C%';

[User] Add the URL in the result too, and order by name alphabetically.

[Assistant] SELECT name, description, url FROM trading_platform.dapps WHERE name LIKE 'C%' ORDER BY name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )

[User] Find the total unbilled but billable hours for each lawyer. Only include lawyers with more than 10 such hours, and sort by total hours descending.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_unbilled_hours FROM legal_services.time_entries WHERE is_billable = TRUE AND is_billed = FALSE GROUP BY lawyer_id HAVING SUM(hours_spent) > 10 ORDER BY total_unbilled_hours DESC;

[User] How many time entries does each client have? Provide the client's first and last name along with the count, sorted by count descending.

[Assistant] SELECT c.first_name, c.last_name, COUNT(te.entry_id) AS entry_count FROM legal_services.clients c JOIN legal_services.time_entries te ON c.client_id = te.lawyer_id GROUP BY c.first_name, c.last_name ORDER BY entry_count DESC;

[User] Actually, include only clients with more than 2 entries and also show the average billing_rate for those entries.

[Assistant] SELECT c.first_name, c.last_name, COUNT(te.entry_id) AS entry_count, AVG(te.billing_rate) AS avg_billing_rate FROM legal_services.clients c JOIN legal_services.time_entries te ON c.client_id = te.lawyer_id GROUP BY c.first_name, c.last_name HAVING COUNT(te.entry_id) > 2 ORDER BY entry_count DESC;

[User] Also, sort the results by average billing rate in ascending order.

[Assistant] SELECT c.first_name, c.last_name, COUNT(te.entry_id) AS entry_count, AVG(te.billing_rate) AS avg_billing_rate FROM legal_services.clients c JOIN legal_services.time_entries te ON c.client_id = te.lawyer_id GROUP BY c.first_name, c.last_name HAVING COUNT(te.entry_id) > 2 ORDER BY avg_billing_rate ASC;

[User] List the first and last names of clients whose client_id matches a lawyer_id in the time_entries table, along with the corresponding entry_id.

[Assistant] SELECT c.first_name, c.last_name, te.entry_id FROM legal_services.clients c JOIN legal_services.time_entries te ON c.client_id = te.lawyer_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)

[User] Can you retrieve the total number of train cars for each train in the database?

[Assistant]
MATCH (t:Train)<-[:PART_OF_TRAIN]-(tc:TrainCar)
RETURN t.train_id, t.train_number, COUNT(tc) AS total_cars
ORDER BY t.train_id

[User] Can you help me find all bookings made by passengers from a specific city, say 'Boston', including the passenger details and the scheduled trip information?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, st.schedule_id

[User] Can you modify the query to include only bookings with a status of 'Confirmed'?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, st.schedule_id

[User] Can you also add the total price of each booking to the result?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, b.total_price, st.schedule_id

[User] Can you sort the results by booking datetime in ascending order?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, b.total_price, st.schedule_id
ORDER BY b.booking_datetime ASC

[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff

[User] Can you help me find all staff members based at a specific station with station_id 'station_xyz', including the station details and platform information they are associated with?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you filter the results to include only staff with the role of 'Manager' and platforms with status 'Operational'?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you sort the results by staff last name and platform number?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status
ORDER BY stf.last_name, p.platform_number

[User] 能否帮我查询特定路线(route_id 为 'route_ne_corr')上的所有车站信息，并包含每个车站的平台数量？

[Assistant]
ZRANGE route:route_ne_corr:stops 0 -1
HGETALL route_station:<route_station_id> for each route_station_id in result
HGETALL station:<station_id> for each station_id in result
SCARD station:<station_id>:platforms for each station_id in result

[User] 能否将结果按照车站的顺序(sequence_order)进行排序？

[Assistant]
ZRANGE route:route_ne_corr:stops 0 -1 WITHSCORES
HGETALL route_station:<route_station_id> for each route_station_id in result
HGETALL station:<station_id> for each station_id in result
SCARD station:<station_id>:platforms for each station_id in result
Sort results by sequence_order (score from ZRANGE)

[User] 能否只显示有超过5个平台的车站信息？

[Assistant]
ZRANGE route:route_ne_corr:stops 0 -1 WITHSCORES
HGETALL route_station:<route_station_id> for each route_station_id in result
HGETALL station:<station_id> for each station_id in result
SCARD station:<station_id>:platforms for each station_id in result
Filter results where SCARD result > 5
Sort results by sequence_order (score from ZRANGE)

[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有平台数量？

[Assistant] SCARD station:station_xyz:platforms

[User] 能否帮我查询特定列车(train_id 为 'train_789')上的所有车辆信息，并关联到该列车所在的路线信息？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule

[User] 能否将查询结果限制在车辆类型为‘Passenger’的车辆上？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result where car_type='Passenger'
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule

[User] 能否再加入车辆的座位容量信息，并按照容量从大到小排序？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result where car_type='Passenger'
SORT car:<car_id> BY capacity DESC
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule

[User] 能否也把路线的起点站和终点站信息加入到结果中？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result where car_type='Passenger'
SORT car:<car_id> BY capacity DESC
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule
ZRANGE route:<route_id>:stops 0 0 for origin_station_id
ZRANGE route:<route_id>:stops -1 -1 for destination_station_id
HGETALL station:<origin_station_id>
HGETALL station:<destination_station_id>

[User] Can you provide the total number of maintenance records for a specific train with train_id 'train_789'?

[Assistant]
MATCH (t:Train {train_id: 'train_789'})<-[:PERFORMED_ON]-(mr:MaintenanceRecord)
RETURN COUNT(mr) AS total_maintenance_records


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.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )

[User] Show me the total fuel cost for each vehicle, grouped by fuel type.

[Assistant] SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_fuel_cost FROM transportation.fuel_logs GROUP BY vehicle_id, fuel_type;

[User] Can you include the average quantity per fuel type for each vehicle as well?

[Assistant] SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_fuel_cost, AVG(quantity) AS average_quantity FROM transportation.fuel_logs GROUP BY vehicle_id, fuel_type;

[User] Now filter this to only show results where the total fuel cost exceeds $1000.

[Assistant] SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_fuel_cost, AVG(quantity) AS average_quantity FROM transportation.fuel_logs GROUP BY vehicle_id, fuel_type HAVING SUM(total_cost) > 1000;

[User] Calculate the monthly total quantity of fuel consumed and the average cost_per_unit for each fuel_type in 2023.

[Assistant]
SELECT date_trunc('month', log_timestamp) AS month,
       fuel_type,
       SUM(quantity)      AS total_quantity,
       AVG(cost_per_unit) AS avg_cost_per_unit
FROM transportation.fuel_logs
WHERE log_timestamp >= '2023-01-01'
  AND log_timestamp <  '2024-01-01'
GROUP BY 1, fuel_type
ORDER BY 1, fuel_type;

[User] Now limit the results to fuel types where the total_quantity exceeds 1000 units in that month.

[Assistant]
SELECT month,
       fuel_type,
       total_quantity,
       avg_cost_per_unit
FROM (
  SELECT date_trunc('month', log_timestamp) AS month,
         fuel_type,
         SUM(quantity)      AS total_quantity,
         AVG(cost_per_unit) AS avg_cost_per_unit
  FROM transportation.fuel_logs
  WHERE log_timestamp >= '2023-01-01'
    AND log_timestamp <  '2024-01-01'
  GROUP BY 1, fuel_type
) sub
WHERE total_quantity > 1000
ORDER BY month, fuel_type;

[User] Calculate the total quantity and average cost_per_unit for each fuel_type in the fuel_logs table.

[Assistant]
SELECT fuel_type,
       SUM(quantity)         AS total_quantity,
       AVG(cost_per_unit)    AS avg_cost_per_unit
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Actually, only include fuel types where the total quantity exceeds 1000 and order the results by avg_cost_per_unit descending.

[Assistant]
SELECT fuel_type,
       SUM(quantity)         AS total_quantity,
       AVG(cost_per_unit)    AS avg_cost_per_unit
FROM transportation.fuel_logs
GROUP BY fuel_type
HAVING SUM(quantity) > 1000
ORDER BY avg_cost_per_unit DESC;

[User] List all pairs of fuel log entries for the same vehicle that occurred more than 7 days apart, showing vehicle_id, first_log_id, second_log_id, and the time difference in days.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days';

[User] Now filter to only include pairs where the quantity increased by at least 50 units.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days'
WHERE (f2.quantity - f1.quantity) >= 50;

[User] Also display the difference in total_cost between the two logs.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference,
       (f2.quantity - f1.quantity)      AS quantity_difference,
       (f2.total_cost - f1.total_cost)  AS cost_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days'
WHERE (f2.quantity - f1.quantity) >= 50;

[User] For each vehicle and unit combination, show the total quantity of fuel refueled and the total cost.

[Assistant]
SELECT vehicle_id, unit, SUM(quantity) AS total_quantity, SUM(total_cost) AS total_cost
FROM transportation.fuel_logs
GROUP BY vehicle_id, unit;

[User] Identify all instances where a vehicle's odometer_reading increased by more than 500 miles between two consecutive fuel log entries.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       a.log_timestamp                       AS previous_time,
       b.log_timestamp                       AS next_time,
       b.odometer_reading - a.odometer_reading AS mile_increase
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500;

[User] Now restrict these increases to those where the time difference between entries is less than 7 days.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       a.log_timestamp                       AS previous_time,
       b.log_timestamp                       AS next_time,
       b.odometer_reading - a.odometer_reading AS mile_increase,
       EXTRACT(epoch FROM (b.log_timestamp - a.log_timestamp))/3600 AS hours_diff
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500
  AND b.log_timestamp - a.log_timestamp < INTERVAL '7 days';

[User] Also include both the mile increase and the time difference in hours in the final output columns.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       b.odometer_reading - a.odometer_reading AS mile_increase,
       EXTRACT(epoch FROM (b.log_timestamp - a.log_timestamp))/3600 AS hours_difference
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500
  AND b.log_timestamp - a.log_timestamp < INTERVAL '7 days';

[User] Show me the number of fuel logs per location, including the location name and city.

[Assistant]
SELECT fl.location_id, loc.name AS location_name, loc.city, COUNT(*) AS fuel_log_count
FROM transportation.fuel_logs fl
JOIN transportation.locations loc ON fl.location_id = loc.location_id
GROUP BY fl.location_id, loc.name, loc.city;

[User] Can you only include locations where there were more than 10 fueling events?

[Assistant]
SELECT fl.location_id, loc.name AS location_name, loc.city, COUNT(*) AS fuel_log_count
FROM transportation.fuel_logs fl
JOIN transportation.locations loc ON fl.location_id = loc.location_id
GROUP BY fl.location_id, loc.name, loc.city
HAVING COUNT(*) > 10;

[User] Also, show the total fuel quantity supplied at each of these locations.

[Assistant]
SELECT fl.location_id, loc.name AS location_name, loc.city, COUNT(*) AS fuel_log_count, SUM(fl.quantity) AS total_fuel_quantity
FROM transportation.fuel_logs fl
JOIN transportation.locations loc ON fl.location_id = loc.location_id
GROUP BY fl.location_id, loc.name, loc.city
HAVING COUNT(*) > 10;

[User] Sort the result so that the location with the highest total fuel quantity supplied comes first.

[Assistant]
SELECT fl.location_id, loc.name AS location_name, loc.city, COUNT(*) AS fuel_log_count, SUM(fl.quantity) AS total_fuel_quantity
FROM transportation.fuel_logs fl
JOIN transportation.locations loc ON fl.location_id = loc.location_id
GROUP BY fl.location_id, loc.name, loc.city
HAVING COUNT(*) > 10
ORDER BY total_fuel_quantity DESC;

[User] List all fuel log IDs along with their vehicle IDs and odometer readings for logs where the quantity is below 10.

[Assistant]
SELECT fuel_log_id, vehicle_id, odometer_reading
FROM transportation.fuel_logs
WHERE quantity < 10;

[User] I received a lot of results. Please show only those logs where the unit is 'gallon'.

[Assistant]
SELECT fuel_log_id, vehicle_id, odometer_reading
FROM transportation.fuel_logs
WHERE quantity < 10 AND unit = 'gallon';

[User] Now, could you also display the cost_per_unit for each of these logs and sort the output by cost_per_unit in ascending order?

[Assistant]
SELECT fuel_log_id, vehicle_id, odometer_reading, cost_per_unit
FROM transportation.fuel_logs
WHERE quantity < 10 AND unit = 'gallon'
ORDER BY cost_per_unit ASC;

[User] For each vehicle, can you show the vehicle_id, the number of unique fuel types it used, and the maximum quantity recorded in a single fuel log? Only include vehicles that have used more than one type of fuel.

[Assistant]
SELECT vehicle_id, COUNT(DISTINCT fuel_type) AS unique_fuel_types, MAX(quantity) AS max_quantity
FROM transportation.fuel_logs
GROUP BY vehicle_id
HAVING COUNT(DISTINCT fuel_type) > 1;

[User] Additionally, for these vehicles, please provide the total fuel cost for each vehicle.

[Assistant]
SELECT vehicle_id, COUNT(DISTINCT fuel_type) AS unique_fuel_types, MAX(quantity) AS max_quantity, SUM(total_cost) AS total_fuel_cost
FROM transportation.fuel_logs
GROUP BY vehicle_id
HAVING COUNT(DISTINCT fuel_type) > 1;

[User] Identify all instances where a vehicle's odometer_reading decreased compared to its previous fuel log entry.

[Assistant]
SELECT curr.vehicle_id,
       prev.fuel_log_id   AS previous_log_id,
       prev.odometer_reading AS previous_reading,
       curr.fuel_log_id   AS current_log_id,
       curr.odometer_reading AS current_reading
FROM transportation.fuel_logs AS curr
JOIN transportation.fuel_logs AS prev
  ON curr.vehicle_id = prev.vehicle_id
  AND curr.log_timestamp > prev.log_timestamp
  AND NOT EXISTS (
    SELECT 1
    FROM transportation.fuel_logs AS mid
    WHERE mid.vehicle_id = curr.vehicle_id
      AND mid.log_timestamp > prev.log_timestamp
      AND mid.log_timestamp < curr.log_timestamp
  )
WHERE curr.odometer_reading < prev.odometer_reading;

[User] Only show decreases greater than 100 miles.

[Assistant]
SELECT curr.vehicle_id,
       prev.fuel_log_id   AS previous_log_id,
       prev.odometer_reading AS previous_reading,
       curr.fuel_log_id   AS current_log_id,
       curr.odometer_reading AS current_reading
FROM transportation.fuel_logs AS curr
JOIN transportation.fuel_logs AS prev
  ON curr.vehicle_id = prev.vehicle_id
  AND curr.log_timestamp > prev.log_timestamp
  AND NOT EXISTS (
    SELECT 1
    FROM transportation.fuel_logs AS mid
    WHERE mid.vehicle_id = curr.vehicle_id
      AND mid.log_timestamp > prev.log_timestamp
      AND mid.log_timestamp < curr.log_timestamp
  )
WHERE prev.odometer_reading - curr.odometer_reading > 100;

[User] Sort the results by the magnitude of the decrease in descending order.

[Assistant]
SELECT curr.vehicle_id,
       prev.fuel_log_id   AS previous_log_id,
       prev.odometer_reading AS previous_reading,
       curr.fuel_log_id   AS current_log_id,
       curr.odometer_reading AS current_reading,
       (prev.odometer_reading - curr.odometer_reading) AS decrease_amount
FROM transportation.fuel_logs AS curr
JOIN transportation.fuel_logs AS prev
  ON curr.vehicle_id = prev.vehicle_id
  AND curr.log_timestamp > prev.log_timestamp
  AND NOT EXISTS (
    SELECT 1
    FROM transportation.fuel_logs AS mid
    WHERE mid.vehicle_id = curr.vehicle_id
      AND mid.log_timestamp > prev.log_timestamp
      AND mid.log_timestamp < curr.log_timestamp
  )
WHERE prev.odometer_reading - curr.odometer_reading > 100
ORDER BY decrease_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )

[User] What are the top 5 tokens by 7-day price change percentage? Show token_symbol, token_name, narrative, and chain, ordered by price_change_percentage_7d descending.

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

[User] For each fundraising round in 2022 and 2023, list the round name, the year, the total investment_value, and the count of distinct projects. Also include the average market_cap of associated tokens by matching project_name to token_symbol in token_basic_info.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_symbol)
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4);

[User] The join returns no rows. Please change the join to match when token_symbol is contained within project_name, case-insensitive.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4);

[User] Now only include rounds where the total investment_value exceeds 5000000.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4)
HAVING SUM(p.investment_value) > 5000000;

[User] Finally, order the results by total_investment descending.

[Assistant]
SELECT p.rounds_name,
  SUBSTRING(p.investment_date FROM 1 FOR 4) AS year,
  SUM(p.investment_value) AS total_investment,
  COUNT(DISTINCT p.project_id) AS project_count,
  AVG(t.market_cap) AS avg_market_cap
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) LIKE '%' || LOWER(t.token_symbol) || '%'
WHERE SUBSTRING(p.investment_date FROM 1 FOR 4) IN ('2022','2023')
GROUP BY p.rounds_name, SUBSTRING(p.investment_date FROM 1 FOR 4)
HAVING SUM(p.investment_value) > 5000000
ORDER BY total_investment DESC;

[User] For each fundraising round, show the round name, the count of distinct projects, the total investment value, and the average current price of associated tokens. Match projects to tokens where project_name = token_name and sort by total investment descending.

[Assistant]
```sql
SELECT
  p.rounds_name,
  COUNT(DISTINCT p.project_id) AS project_count,
  SUM(p.investment_value) AS total_investment,
  AVG(t.price) AS average_token_price
FROM project_fundraising_record p
JOIN token_basic_info t
  ON p.project_name = t.token_name
GROUP BY p.rounds_name
ORDER BY total_investment DESC;
```

[User] Please exclude any NULL round names and only include rounds with more than one project.

[Assistant]
```sql
WITH round_stats AS (
  SELECT
    p.rounds_name,
    COUNT(DISTINCT p.project_id) AS project_count,
    SUM(p.investment_value) AS total_investment,
    AVG(t.price) AS average_token_price
  FROM project_fundraising_record p
  JOIN token_basic_info t
    ON p.project_name = t.token_name
  WHERE p.rounds_name IS NOT NULL
  GROUP BY p.rounds_name
)
SELECT
  rounds_name,
  project_count,
  total_investment,
  average_token_price
FROM round_stats
WHERE project_count > 1
ORDER BY total_investment DESC;
```

[User] Show all tokens on the 'Arbitrum' chain from DEX pools that have a 24-hour trading volume between $100,000 and $500,000. Display token symbol, price, and volume_24h.

[Assistant]
SELECT
  token_symbol,
  price,
  volume_24h
FROM token_dexpool_info
WHERE
  chain = 'Arbitrum' AND volume_24h BETWEEN 100000 AND 500000;

[User] Include their liquidity and 6-hour price change percentage in the results.

[Assistant]
SELECT
  token_symbol,
  price,
  volume_24h,
  liquidity,
  price_change_percentage_6h
FROM token_dexpool_info
WHERE
  chain = 'Arbitrum' AND volume_24h BETWEEN 100000 AND 500000;

[User] For each narrative in token_basic_info, compute the total liquidity and count of tokens from token_dexpool_info. Show narrative, total_liquidity, and token_count.

[Assistant]
SELECT tbi.narrative,
  SUM(td.liquidity) AS total_liquidity,
  COUNT(DISTINCT td.token_symbol) AS token_count
FROM token_basic_info tbi
JOIN token_dexpool_info td
  ON tbi.token_address = td.token_address
GROUP BY tbi.narrative;

[User] Include only tokens where volume_24h > 500000 and price_change_percentage_6h > 0.

[Assistant]
SELECT tbi.narrative,
  SUM(td.liquidity) AS total_liquidity,
  COUNT(DISTINCT td.token_symbol) AS token_count
FROM token_basic_info tbi
JOIN token_dexpool_info td
  ON tbi.token_address = td.token_address
WHERE td.volume_24h > 500000
  AND td.price_change_percentage_6h > 0
GROUP BY tbi.narrative;

[User] Now join narrative_info to also get trend_rank and narrative volume_24h.

[Assistant]
SELECT tbi.narrative,
  ni.trend_rank,
  ni.volume_24h AS narrative_volume,
  SUM(td.liquidity) AS total_liquidity,
  COUNT(DISTINCT td.token_symbol) AS token_count
FROM token_basic_info tbi
JOIN token_dexpool_info td
  ON tbi.token_address = td.token_address
JOIN narrative_info ni
  ON tbi.narrative = ni.narrative
WHERE td.volume_24h > 500000
  AND td.price_change_percentage_6h > 0
GROUP BY tbi.narrative, ni.trend_rank, ni.volume_24h;

[User] Finally, only keep narratives where trend_rank <= 10 and order by total_liquidity descending.

[Assistant]
SELECT tbi.narrative,
  ni.trend_rank,
  ni.volume_24h AS narrative_volume,
  SUM(td.liquidity) AS total_liquidity,
  COUNT(DISTINCT td.token_symbol) AS token_count
FROM token_basic_info tbi
JOIN token_dexpool_info td
  ON tbi.token_address = td.token_address
JOIN narrative_info ni
  ON tbi.narrative = ni.narrative
WHERE td.volume_24h > 500000
  AND td.price_change_percentage_6h > 0
  AND ni.trend_rank <= 10
GROUP BY tbi.narrative, ni.trend_rank, ni.volume_24h
ORDER BY total_liquidity DESC;

[User] Which narrative in narrative_info has the highest volume_24h, and what are its top_3_coins and token_num?

[Assistant]
SELECT narrative,
  top_3_coins,
  token_num
FROM narrative_info
ORDER BY volume_24h DESC
LIMIT 1;

[User] Also include the narrative's price_change_percentage_7d in the output.

[Assistant]
SELECT narrative,
  top_3_coins,
  token_num,
  price_change_percentage_7d
FROM narrative_info
ORDER BY volume_24h DESC
LIMIT 1;

[User] List all tokens on the 'BSC' chain with a trend rank between 6 and 20 (inclusive), along with their symbol, price, and liquidity.

[Assistant]
SELECT t.token_symbol, t.price, d.liquidity
FROM token_basic_info t
JOIN token_dexpool_info d ON lower(t.token_symbol) = lower(d.token_symbol) AND t.chain = d.chain
WHERE t.chain = 'BSC' AND t.trend_rank BETWEEN 6 AND 20;

[User] Could you also show their 24-hour trading volume and only include tokens with a positive 24-hour price change percentage?

[Assistant]
SELECT t.token_symbol, t.price, d.liquidity, d.volume_24h
FROM token_basic_info t
JOIN token_dexpool_info d ON lower(t.token_symbol) = lower(d.token_symbol) AND t.chain = d.chain
WHERE t.chain = 'BSC' AND t.trend_rank BETWEEN 6 AND 20 AND t.price_change_percentage_24h > 0;

[User] Add the narrative for each token and order the results by liquidity descending, showing only the top 5.

[Assistant]
SELECT t.token_symbol, t.price, d.liquidity, d.volume_24h, t.narrative
FROM token_basic_info t
JOIN token_dexpool_info d ON lower(t.token_symbol) = lower(d.token_symbol) AND t.chain = d.chain
WHERE t.chain = 'BSC' AND t.trend_rank BETWEEN 6 AND 20 AND t.price_change_percentage_24h > 0
ORDER BY d.liquidity DESC
LIMIT 5;

[User] What is the average profit of smart money addresses whose profit is above $1,000, grouped by chain?

[Assistant]
SELECT chain, AVG(profit) AS avg_profit
FROM smart_money_profit
WHERE profit > 1000
GROUP BY chain;

[User] List all projects that raised funds in March 2023. For each project, show its name, amount raised, fundraising round, and the token symbol and price of its associated token.

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%'

[User] Can you also include the current market cap and chain of each token in the result?

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%'

[User] I only want to see projects that raised more than $5,000,000. Please update the query.

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%' AND p.investment_value > 5000000

[User] It seems some tokens are not matched because names are not identical. Can you try joining where the token_name contains the project_name (case-insensitive)?

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(t.token_name) LIKE '%' || LOWER(p.project_name) || '%'
WHERE p.investment_date LIKE '2023-03%' AND p.investment_value > 5000000

[User] Which narrative from narrative_info has the highest token_num, and what is the total market cap and 24h volume for that narrative?

[Assistant]
SELECT narrative, market_cap, volume_24h, token_num
FROM narrative_info
ORDER BY token_num DESC
LIMIT 1;

[User] Can you show the top 3 narratives by token_num instead, but only for those where the 24h price change percentage is positive?

[Assistant]
SELECT narrative, market_cap, volume_24h, token_num, price_change_percentage_24h
FROM narrative_info
WHERE price_change_percentage_24h > 0
ORDER BY token_num DESC
LIMIT 3;

[User] I'd like to also see their top_3_coins and ensure only narratives with a market cap above 1,000,000,000 are included. Please revise the query.

[Assistant]
SELECT narrative, market_cap, volume_24h, token_num, price_change_percentage_24h, top_3_coins
FROM narrative_info
WHERE price_change_percentage_24h > 0 AND market_cap > 1000000000
ORDER BY token_num DESC
LIMIT 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.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] I want to know the usernames of users who have followed more than three different people, along with the date they created their accounts.

[Assistant]
SELECT u.username, u.created_at, COUNT(DISTINCT f.following_user_id) AS following_count
FROM social_media.users u
JOIN social_media.follows f ON u.user_id = f.follower_user_id
GROUP BY u.user_id, u.username, u.created_at
HAVING COUNT(DISTINCT f.following_user_id) > 3;

[User] Also include the usernames of up to two users they are following for each user in the result.

[Assistant]
SELECT u.username AS follower_username, u.created_at, uf.username AS following_username
FROM social_media.users u
JOIN social_media.follows f ON u.user_id = f.follower_user_id
JOIN social_media.users uf ON f.following_user_id = uf.user_id
WHERE u.user_id IN (
  SELECT f1.follower_user_id
  FROM social_media.follows f1
  GROUP BY f1.follower_user_id
  HAVING COUNT(DISTINCT f1.following_user_id) > 3
)
ORDER BY u.username, f.created_at
LIMIT 2;

[User] Can you instead provide all usernames they follow, not just two, and include the follow creation date as well?

[Assistant]
SELECT u.username AS follower_username, u.created_at AS follower_created_at, uf.username AS following_username, f.created_at AS follow_created_at
FROM social_media.users u
JOIN social_media.follows f ON u.user_id = f.follower_user_id
JOIN social_media.users uf ON f.following_user_id = uf.user_id
WHERE u.user_id IN (
  SELECT f1.follower_user_id
  FROM social_media.follows f1
  GROUP BY f1.follower_user_id
  HAVING COUNT(DISTINCT f1.following_user_id) > 3
)
ORDER BY u.username, f.created_at;

[User] Show me all users along with the total number of unique hashtags used in their posts.

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

[User] Can you include only the users who have used more than 2 unique hashtags?

[Assistant]
SELECT u.user_id, u.username, COUNT(DISTINCT ph.hashtag_id) AS unique_hashtag_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
LEFT JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
GROUP BY u.user_id, u.username
HAVING COUNT(DISTINCT ph.hashtag_id) > 2;

[User] Which users have participated in the highest number of unique conversations? Show their usernames and the count of unique conversations they joined.

[Assistant]
SELECT u.username, COUNT(DISTINCT cp.conversation_id) AS conversation_count
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
GROUP BY u.username
ORDER BY conversation_count DESC;

[User] Only include users who joined more than 3 conversations.

[Assistant]
SELECT u.username, COUNT(DISTINCT cp.conversation_id) AS conversation_count
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
GROUP BY u.username
HAVING COUNT(DISTINCT cp.conversation_id) > 3
ORDER BY conversation_count DESC;

[User] Also, show the most recent join time (joined_at) for each user.

[Assistant]
SELECT u.username, COUNT(DISTINCT cp.conversation_id) AS conversation_count, MAX(cp.joined_at) AS last_joined_at
FROM social_media.users u
JOIN social_media.conversation_participants cp ON u.user_id = cp.user_id
GROUP BY u.username
HAVING COUNT(DISTINCT cp.conversation_id) > 3
ORDER BY conversation_count DESC;

[User] Show the usernames and email addresses of all users who have never created a post.

[Assistant]
SELECT u.username, u.email
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.post_id IS NULL;

[User] Retrieve the usernames and email addresses of users who updated their profiles in the last 30 days.

[Assistant]
SELECT username, email
FROM social_media.users
WHERE updated_at >= NOW() - INTERVAL '30 days';

[User] I want to see each user's username and the number of posts they've made that include a media attachment of type 'image'.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username;

[User] Only include users with more than 2 image posts.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username
HAVING COUNT(*) > 2;

[User] Show a list of group chat names with their conversation_id, the total number of participants, and the total number of messages sent in each group chat.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name;

[User] Please filter to include only group chats that have at least 5 participants.

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

[User] Now order the results by message_count descending and limit to the top 10 group chats.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(cp.participant_id) >= 5
ORDER BY message_count DESC
LIMIT 10;

[User] List all users who have participated in group conversations created in April 2024, showing their username, conversation ID, and the group name.

[Assistant]
SELECT DISTINCT u.username, c.conversation_id, c.group_name
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
WHERE c.is_group_chat = true
  AND c.created_at >= '2024-04-01' AND c.created_at < '2024-05-01';

[User] Instead of all users, show only those who joined the group conversation after it was created.

[Assistant]
SELECT DISTINCT u.username, c.conversation_id, c.group_name
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
WHERE c.is_group_chat = true
  AND c.created_at >= '2024-04-01' AND c.created_at < '2024-05-01'
  AND cp.joined_at > c.created_at;

[User] I only care about group conversations where the group name contains the word 'Study'.

[Assistant]
SELECT DISTINCT u.username, c.conversation_id, c.group_name
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
WHERE c.is_group_chat = true
  AND c.created_at >= '2024-04-01' AND c.created_at < '2024-05-01'
  AND cp.joined_at > c.created_at
  AND c.group_name ILIKE '%Study%';

[User] Show the post ID and hashtags for all posts containing the word 'conference' in their content.

[Assistant]
SELECT p.post_id, h.hashtag_id, h.tag_name
FROM social_media.posts p
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE p.content ILIKE '%conference%';

[User] I want a report of public posts with images in the last 30 days that shows post_id, content, author's username and email, and the count of likes, ordered by like count descending, limit to top 5.

[Assistant] SELECT p.post_id, p.content, u.username, u.email, COUNT(l.like_id) AS like_count FROM social_media.posts p JOIN social_media.users u ON p.user_id = u.user_id LEFT JOIN social_media.likes l ON l.post_id = p.post_id WHERE p.visibility = 'public' AND p.media_type = 'image' AND p.created_at >= now() - interval '30 days' GROUP BY p.post_id, p.content, u.username, u.email ORDER BY like_count DESC LIMIT 5;

[User] Actually, only include posts created by verified users.

[Assistant] SELECT p.post_id, p.content, u.username, u.email, COUNT(l.like_id) AS like_count FROM social_media.posts p JOIN social_media.users u ON p.user_id = u.user_id LEFT JOIN social_media.likes l ON l.post_id = p.post_id WHERE p.visibility = 'public' AND p.media_type = 'image' AND p.created_at >= now() - interval '30 days' AND u.is_verified = true GROUP BY p.post_id, p.content, u.username, u.email ORDER BY like_count DESC LIMIT 5;

[User] Also, filter to posts within 50 kilometers of latitude 40.0 and longitude -74.0.

[Assistant] SELECT p.post_id, p.content, u.username, u.email, COUNT(l.like_id) AS like_count FROM social_media.posts p JOIN social_media.users u ON p.user_id = u.user_id LEFT JOIN social_media.likes l ON l.post_id = p.post_id WHERE p.visibility = 'public' AND p.media_type = 'image' AND p.created_at >= now() - interval '30 days' AND u.is_verified = true AND p.location_lat BETWEEN 40.0 - 0.45 AND 40.0 + 0.45 AND p.location_lon BETWEEN -74.0 - 0.45 AND -74.0 + 0.45 GROUP BY p.post_id, p.content, u.username, u.email ORDER BY like_count DESC LIMIT 5;

[User] Finally, reduce the limit to top 3 posts only.

[Assistant] SELECT p.post_id, p.content, u.username, u.email, COUNT(l.like_id) AS like_count FROM social_media.posts p JOIN social_media.users u ON p.user_id = u.user_id LEFT JOIN social_media.likes l ON l.post_id = p.post_id WHERE p.visibility = 'public' AND p.media_type = 'image' AND p.created_at >= now() - interval '30 days' AND u.is_verified = true AND p.location_lat BETWEEN 40.0 - 0.45 AND 40.0 + 0.45 AND p.location_lon BETWEEN -74.0 - 0.45 AND -74.0 + 0.45 GROUP BY p.post_id, p.content, u.username, u.email ORDER BY like_count DESC LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] Get the number of insurance products grouped by product_type and their active status. Return product_type, is_active, and the count of products.

[Assistant]
SELECT product_type, is_active, COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type, is_active;

[User] List all pairs of insurance products that share the same product_type but have differing active statuses. Return both product_ids, the product_type, and each is_active flag.

[Assistant]
SELECT p1.product_id AS product_id_1, p2.product_id AS product_id_2, p1.product_type, p1.is_active AS is_active_1, p2.is_active AS is_active_2
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.is_active <> p2.is_active
WHERE p1.product_id < p2.product_id;

[User] Which insurance products have 'comprehensive' in their coverage details? Show the product_id and product_name.

[Assistant] SELECT product_id, product_name FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Can you also add the product_type to the output?

[Assistant] SELECT product_id, product_name, product_type FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Show me product_id, product_name, and base_premium for products created after '2023-01-01'.

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01';

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

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000;

[User] Can you also order the results by base_premium descending and limit to the top 5?

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
ORDER BY base_premium DESC
LIMIT 5;

[User] Now, I need the total number of such products per product_type.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
GROUP BY product_type;

[User] Give me the product name and description of all insurance products that have been updated in the last 30 days.

[Assistant] SELECT product_name, description FROM insurance.insurance_products WHERE updated_at >= NOW() - INTERVAL '30 days';

[User] List all insurance products along with their type and base premium. Also, show whether each product is active.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products;

[User] Can you filter the results to only show insurance products of type 'auto'?

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products WHERE product_type = 'auto';

[User] Also, sort these results by the base premium in ascending order.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products WHERE product_type = 'auto' ORDER BY base_premium ASC;

[User] Retrieve the count of active insurance products for each product_type and order the results by the count descending.

[Assistant]
SELECT product_type,
       COUNT(*) AS active_count
FROM insurance.insurance_products
WHERE is_active = TRUE
GROUP BY product_type
ORDER BY active_count DESC;

[User] List all insurance products along with their product types and the date they were last updated, but only include products where the base premium is greater than 2000.

[Assistant]
SELECT product_id, product_name, product_type, updated_at
FROM insurance.insurance_products
WHERE base_premium > 2000;

[User] Show me all insurance products of type 'Health' or 'Dental'.

[Assistant]
SELECT *
FROM insurance.insurance_products
WHERE product_type IN ('Health', 'Dental');

[User] I only want to see those that are currently inactive.

[Assistant]
SELECT *
FROM insurance.insurance_products
WHERE product_type IN ('Health', 'Dental')
  AND is_active = FALSE;

[User] From those, only show products with a base premium between 200 and 800, and list their product_name, base_premium, and created_at.

[Assistant]
SELECT product_name, base_premium, created_at
FROM insurance.insurance_products
WHERE product_type IN ('Health', 'Dental')
  AND is_active = FALSE
  AND base_premium BETWEEN 200 AND 800;

[User] Order the results by base_premium ascending and updated_at descending.

[Assistant]
SELECT product_name, base_premium, created_at
FROM insurance.insurance_products
WHERE product_type IN ('Health', 'Dental')
  AND is_active = FALSE
  AND base_premium BETWEEN 200 AND 800
ORDER BY base_premium ASC, updated_at DESC;

[User] List all active products, showing their product ID, name, and type, ordered by their creation date.

[Assistant] SELECT product_id, product_name, product_type FROM insurance.insurance_products WHERE is_active = TRUE ORDER BY created_at;