[User] List all NFT collections from the sui_nfts table where the owner is not null, including their name and collection_type.

[Assistant] SELECT name, collection_type FROM sui_nfts WHERE owner IS NOT NULL;

[User] Can you also include the display field and filter to only show collections with a package_id starting with '0x'?

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%';

[User] Now sort these results by name in ascending order.

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%' ORDER BY name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
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 NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
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 varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
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 varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, 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 varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_info_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(255) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)


[User] Show smart money addresses with an ROI greater than 3 and a realized ratio greater than 0.7. Display the address, chain, ROI, realized ratio, and most profitable token.

[Assistant] SELECT address, chain, roi, realized_ratio, most_profit_token FROM smart_money_profit WHERE roi > 3 AND realized_ratio > 0.7;

[User] For these tokens (`most_profit_token` from the previous result), what is the total USD value held by CEXes across all chains? Show the token symbol and the total CEX USD value.

[Assistant] WITH HighlyPerformingTokens AS (SELECT DISTINCT most_profit_token FROM smart_money_profit WHERE roi > 3 AND realized_ratio > 0.7 AND most_profit_token IS NOT NULL) SELECT c.token_symbol, SUM(c.usd_value) AS total_cex_usd_value FROM cex_token_balance c JOIN HighlyPerformingTokens h ON c.token_symbol = h.most_profit_token WHERE c.usd_value IS NOT NULL GROUP BY c.token_symbol ORDER BY total_cex_usd_value DESC;

[User] Filter the previous results to only include tokens where the `average_smart_money_roi` is greater than 10 (1000%) and the `average_smart_money_realized_ratio` is greater than 0.8.

[Assistant] WITH CexHeldTokens AS (SELECT DISTINCT token_symbol FROM cex_token_balance WHERE token_symbol IS NOT NULL AND token_symbol != ''), TokenPerformance AS (SELECT s.most_profit_token AS token_symbol, AVG(s.roi) AS average_smart_money_roi, AVG(s.realized_ratio) AS average_smart_money_realized_ratio FROM smart_money_profit s JOIN CexHeldTokens c ON s.most_profit_token = c.token_symbol WHERE s.roi IS NOT NULL AND s.realized_ratio IS NOT NULL GROUP BY s.most_profit_token) SELECT token_symbol, average_smart_money_roi, average_smart_money_realized_ratio FROM TokenPerformance WHERE average_smart_money_roi > 10 AND average_smart_money_realized_ratio > 0.8 ORDER BY average_smart_money_roi DESC;

[User] For these filtered tokens, add the total USD value held by CEXes (`usd_value` from `cex_token_balance`) to the results. Show token symbol, total CEX USD value, average ROI, and average realized ratio.

[Assistant] WITH CexHeldTokens AS (SELECT DISTINCT token_symbol FROM cex_token_balance WHERE token_symbol IS NOT NULL AND token_symbol != ''), TokenPerformance AS (SELECT s.most_profit_token AS token_symbol, AVG(s.roi) AS average_smart_money_roi, AVG(s.realized_ratio) AS average_smart_money_realized_ratio FROM smart_money_profit s JOIN CexHeldTokens c ON s.most_profit_token = c.token_symbol WHERE s.roi IS NOT NULL AND s.realized_ratio IS NOT NULL GROUP BY s.most_profit_token), FilteredPerformance AS (SELECT token_symbol, average_smart_money_roi, average_smart_money_realized_ratio FROM TokenPerformance WHERE average_smart_money_roi > 10 AND average_smart_money_realized_ratio > 0.8) SELECT fp.token_symbol, SUM(c.usd_value) AS total_cex_usd_value, fp.average_smart_money_roi, fp.average_smart_money_realized_ratio FROM FilteredPerformance fp JOIN cex_token_balance c ON fp.token_symbol = c.token_symbol WHERE c.usd_value IS NOT NULL GROUP BY fp.token_symbol, fp.average_smart_money_roi, fp.average_smart_money_realized_ratio ORDER BY fp.average_smart_money_roi DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
  "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) )


[User] What are the qualifications or training history of the staff member who performed the maintenance with record_id 'REC123'?

[Assistant] I'm sorry, but I can't provide information about the qualifications or training history of staff members as this data is not stored in the maintenance_records table. This table only contains details about maintenance activities, such as asset information, maintenance type, dates, and costs. If you have another question or need assistance with data available in this table, I'm happy to help.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records (
    record_id character varying(64) NOT NULL, -- Unique identifier for the maintenance record
    asset_id character varying(64) NOT NULL, -- ID of the asset being maintained (train_id, car_id, platform_id, etc.)
    asset_type character varying(32) NOT NULL, -- Type of asset ('Train', 'Car', 'Platform', 'Track')
    maintenance_type character varying(128) NOT NULL, -- e.g., 'Scheduled Inspection', 'Repair', 'Cleaning'
    staff_id character varying(64), -- Staff member performing/overseeing maintenance
    start_datetime timestamp NOT NULL, -- When maintenance started
    end_datetime timestamp, -- When maintenance completed (nullable if ongoing)
    description text NOT NULL, -- Details of the maintenance performed
    cost numeric(12, 2), -- Cost associated with the maintenance
    status character varying(32) NOT NULL DEFAULT 'Completed', -- e.g., 'Scheduled', 'In Progress', 'Completed', 'Cancelled'
    PRIMARY KEY (record_id),
    FOREIGN KEY (staff_id) REFERENCES train_station_management.staff(staff_id)
)


[User] How many 'ApprovalForAll' events are recorded for each ERC1155 contract address in the `erc1155_approval_for_all` table?

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

[User] For these contracts, can you include the collection name from the `nft_collections` table and filter to only show collections on the 'Ethereum' blockchain that have more than 100 approval events?

[Assistant] SELECT a.contract_address, c.name, COUNT(a.contract_address) AS approval_count FROM erc1155_approval_for_all AS a JOIN nft_collections AS c ON a.contract_address = c.contract_address WHERE c.blockchain = 'Ethereum' GROUP BY a.contract_address, c.name HAVING COUNT(a.contract_address) > 100 ORDER BY approval_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
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(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
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 varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(20) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL, -- Address originating the inscription (matches from_address in transactions table)
    minted decimal(38,0) NOT NULL, -- Sum of minted amount
    holders decimal(38,0) NOT NULL, -- Count of holders
    txs decimal(38,0) NOT NULL, -- Count of transactions
    updated_timestamp timestamp(3) NOT NULL, -- Timestamp of update
    completed_timestamp timestamp(3) NOT NULL, -- Timestamp of minted completed
    id varchar(255) NOT NULL  -- id fields for the functionType  in contract asc20
)


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )


[User] List all wallets that were created during the hour of the day which saw the highest number of wallet creations. Show the wallet ID, user ID, address, and creation timestamp.

[Assistant]
WITH HourlyCounts AS (
    SELECT EXTRACT(HOUR FROM created_at) AS hour, COUNT(*) AS wallet_count
    FROM web3.wallets
    GROUP BY 1
),
MaxHour AS (
    SELECT hour
    FROM HourlyCounts
    ORDER BY wallet_count DESC
    LIMIT 1
)
SELECT wallet_id, user_id, address, created_at
FROM web3.wallets
WHERE EXTRACT(HOUR FROM created_at) = (SELECT hour FROM MaxHour);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )


[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal' ORDER BY date_opened ASC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] Show me the average star rating for each property type in the USA.

[Assistant] SELECT property_type, AVG(star_rating) as avg_rating FROM hospitality_technology.properties WHERE country_code = 'US' GROUP BY property_type;

[User] Now, include only property types with an average rating above 3.5 and show the count of properties in each type.

[Assistant] SELECT property_type, AVG(star_rating) as avg_rating, COUNT(*) as property_count FROM hospitality_technology.properties WHERE country_code = 'US' GROUP BY property_type HAVING AVG(star_rating) > 3.5;

[User] The query is missing the state information. Can you include the most common state for each property type?

[Assistant] SELECT property_type, AVG(star_rating) as avg_rating, COUNT(*) as property_count, MODE() WITHIN GROUP (ORDER BY state_province) as most_common_state FROM hospitality_technology.properties WHERE country_code = 'US' GROUP BY property_type HAVING AVG(star_rating) > 3.5;

[User] Actually, I need to see the results ordered by property count in descending order.

[Assistant] SELECT property_type, AVG(star_rating) as avg_rating, COUNT(*) as property_count, MODE() WITHIN GROUP (ORDER BY state_province) as most_common_state FROM hospitality_technology.properties WHERE country_code = 'US' GROUP BY property_type HAVING AVG(star_rating) > 3.5 ORDER BY property_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )


[User] How many distinct users have sent messages in each conversation? Return conversation_id and user_count.

[Assistant]
SELECT conversation_id,
       COUNT(DISTINCT sender_user_id) AS user_count
FROM social_media.messages
GROUP BY conversation_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id 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.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )


[User] What is the maintenance schedule for platform 3 at station DEF for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for platforms. The data I have only includes static information about platform details such as ID, station, number, track, status, length, and accessibility. For maintenance schedules, you may need to consult the station management or relevant department.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.platforms ( platform_id text, station_id text, platform_number text, track_number text, status text, length_meters numeric, accessible boolean )


[User] List all claim IDs that have both an 'Accident Report' and a 'Damage Assessment' document, and show the earliest upload timestamp for each type.

[Assistant]
SELECT a.claim_id,
       MIN(a.uploaded_at) AS accident_report_date,
       MIN(d.uploaded_at) AS damage_assessment_date
FROM insurance.claim_documents AS a
JOIN insurance.claim_documents AS d
  ON a.claim_id = d.claim_id
WHERE a.document_type = 'Accident Report'
  AND d.document_type = 'Damage Assessment'
GROUP BY a.claim_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] Show me the top 5 projects by valuation that completed fundraising rounds in the last 6 months, along with their narrative information if available.

[Assistant]
SELECT pfr.project_name, pfr.rounds_name, pfr.valuation, pfr.investment_date, ni.narrative, ni.trend_rank
FROM project_fundraising_record pfr
LEFT JOIN narrative_info ni ON pfr.project_name = ni.narrative
WHERE pfr.investment_date >= date_sub(now(), interval 6 month)
ORDER BY pfr.valuation DESC
LIMIT 5;

[User] Can you filter these results to only include projects with valuation over $50 million and add their 24-hour trading volume from the narrative?

[Assistant]
SELECT pfr.project_name, pfr.rounds_name, pfr.valuation, ni.volume_24h
FROM project_fundraising_record pfr
LEFT JOIN narrative_info ni ON pfr.project_name = ni.narrative
WHERE pfr.investment_date >= date_sub(now(), interval 6 month)
AND pfr.valuation > 50000000
ORDER BY pfr.valuation DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
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 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) )


[User] Show me the top 5 games by number of online servers in European regions. I want the game title and the server count.

[Assistant]
SELECT g.title, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.region ILIKE 'eu%' AND s.status = 'online'
GROUP BY g.title
ORDER BY server_count DESC
LIMIT 5;

[User] Now include only those games whose average current_players per online server exceeds 100.

[Assistant]
SELECT g.title,
       COUNT(s.server_id) AS server_count,
       AVG(s.current_players)::numeric(10,2) AS avg_players
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.region ILIKE 'eu%' AND s.status = 'online'
GROUP BY g.title
HAVING AVG(s.current_players) > 100
ORDER BY server_count DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] List the full names and dates of birth for all patients who do not have a phone number on record.

[Assistant] SELECT first_name, last_name, date_of_birth FROM healthcare.patients WHERE phone_number IS NULL OR TRIM(phone_number) = '';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )


[User] List all metadata entries showing the metadata_id, asset_id, key, and value.

[Assistant] SELECT metadata_id, asset_id, key, value FROM metadata

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] For each player, show the timestamp of their first achievement unlock. Include player_id and the timestamp.

[Assistant] SELECT player_id, MIN(unlocked_at) as first_unlock_at FROM gaming_technology.player_achievements GROUP BY player_id ORDER BY first_unlock_at;

[User] For each player, show the timestamp of their second earliest achievement unlock, if they have at least two. Include player_id and the timestamp.

[Assistant] WITH RankedUnlocks AS ( SELECT player_id, unlocked_at, ROW_NUMBER() OVER(PARTITION BY player_id ORDER BY unlocked_at) as rn FROM gaming_technology.player_achievements ) SELECT player_id, unlocked_at as second_unlock_at FROM RankedUnlocks WHERE rn = 2 ORDER BY player_id, second_unlock_at;

[User] List the player_id for players who unlocked their second achievement within 10 minutes of their first.

[Assistant] WITH PlayerFirstUnlock AS ( SELECT player_id, MIN(unlocked_at) as first_unlock_at FROM gaming_technology.player_achievements GROUP BY player_id ), RankedUnlocks AS ( SELECT player_id, unlocked_at, ROW_NUMBER() OVER(PARTITION BY player_id ORDER BY unlocked_at) as rn FROM gaming_technology.player_achievements ) SELECT pfu.player_id FROM PlayerFirstUnlock pfu JOIN RankedUnlocks ru ON pfu.player_id = ru.player_id WHERE ru.rn = 2 AND ru.unlocked_at <= pfu.first_unlock_at + INTERVAL '10 minute' ORDER BY pfu.player_id;

[User] For the players identified in the previous query (those whose second unlock was within 10 minutes of the first), list the achievement_id of their first and second unlocks.

[Assistant] WITH PlayerFirstUnlock AS ( SELECT player_id, MIN(unlocked_at) as first_unlock_at FROM gaming_technology.player_achievements GROUP BY player_id ), RankedUnlocks AS ( SELECT player_id, achievement_id, unlocked_at, ROW_NUMBER() OVER(PARTITION BY player_id ORDER BY unlocked_at) as rn FROM gaming_technology.player_achievements ), PlayersWithFastSecondUnlock AS ( SELECT pfu.player_id FROM PlayerFirstUnlock pfu JOIN RankedUnlocks ru ON pfu.player_id = ru.player_id WHERE ru.rn = 2 AND ru.unlocked_at <= pfu.first_unlock_at + INTERVAL '10 minute' ) SELECT pfl.player_id, ru_first.achievement_id as first_achievement_id, ru_second.achievement_id as second_achievement_id FROM PlayersWithFastSecondUnlock pfl JOIN RankedUnlocks ru_first ON pfl.player_id = ru_first.player_id AND ru_first.rn = 1 JOIN RankedUnlocks ru_second ON pfl.player_id = ru_second.player_id AND ru_second.rn = 2 ORDER BY pfl.player_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )


[User] List all follow IDs that were created on '2024-06-18'.

[Assistant] SELECT follow_id FROM social_media.follows WHERE DATE(created_at) = '2024-06-18';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )


[User] For each group chat, list its ID, name, creation time, and the creation time of the next group chat created after it, ordered by creation time.

[Assistant] SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ORDER BY created_at;

[User] Only show pairs where the next group chat was created within 48 hours of the current one, and also include the time difference in hours.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 ORDER BY created_at;

[User] Further refine: Only include group chats whose names contain 'Discuss'.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 AND group_name LIKE '%Discuss%' ORDER BY created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )


[User] Tell me the count of hidden achievements and non-hidden achievements.

[Assistant] SELECT hidden, COUNT(*) FROM achievements GROUP BY hidden;

[User] What's the average point value for hidden vs non-hidden achievements?

[Assistant] SELECT hidden, AVG(points) FROM achievements GROUP BY hidden;

[User] Can you combine the count and average points in one query?

[Assistant] SELECT hidden, COUNT(*), AVG(points) FROM achievements GROUP BY hidden;

[User] Now, add the maximum point value for each group.

[Assistant] SELECT hidden, COUNT(*), AVG(points), MAX(points) FROM achievements GROUP BY hidden;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] What is the performance review score for employee with ID 'EMP456' for the last quarter?

[Assistant] I'm sorry, but I can't assist with information about performance review scores as this data is not included in the employees table.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(128) NOT NULL, skill_certifications text, hire_date date NOT NULL, assigned_line_id character varying(64), employment_status character varying(50) NOT NULL, supervisor_employee_id character varying(64), PRIMARY KEY (employee_id) )


[User] Show me the top 5 NFT collections with the highest token count on Ethereum, along with their names, symbols, and floor prices.

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count FROM nft_collections n WHERE n.blockchain = 'ethereum' ORDER BY n.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 n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count ORDER BY n.token_count DESC LIMIT 5;

[User] Can you filter these results to only show collections with an average rarity score greater than 80?

[Assistant] SELECT n.name, n.symbol, n.floor_price, n.token_count, AVG(m.rarity_score) as avg_rarity_score FROM nft_collections n JOIN nft_metadata m ON n.contract_address = m.contract_address WHERE n.blockchain = 'ethereum' GROUP BY n.name, n.symbol, n.floor_price, n.token_count HAVING AVG(m.rarity_score) > 80 ORDER BY n.token_count DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
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 token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_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 all time entries from the last 90 days, including the entry description, hours spent, the name of the case, and the name of the client.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name, T3.first_name, T3.last_name FROM legal_services.time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN clients AS T3 ON T2.client_id = T3.client_id WHERE T1.date_worked >= CURRENT_DATE - INTERVAL '90 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)


[User] List each patient's active insurance policy and the number of prescriptions they have during that policy. Show patient_id, plan_id, policy_number, and prescription_count.

[Assistant]
SELECT pi.patient_id, pi.plan_id, pi.policy_number, COUNT(p.prescription_id) AS prescription_count
FROM healthcare.patient_insurance pi
LEFT JOIN healthcare.prescriptions p
  ON pi.patient_id = p.patient_id
  AND DATE(p.prescription_date) BETWEEN pi.effective_date AND COALESCE(pi.expiration_date, CURRENT_DATE)
GROUP BY pi.patient_id, pi.plan_id, pi.policy_number;

[User] Only include patients with more than 5 prescriptions.

[Assistant]
SELECT pi.patient_id, pi.plan_id, pi.policy_number, COUNT(p.prescription_id) AS prescription_count
FROM healthcare.patient_insurance pi
LEFT JOIN healthcare.prescriptions p
  ON pi.patient_id = p.patient_id
  AND DATE(p.prescription_date) BETWEEN pi.effective_date AND COALESCE(pi.expiration_date, CURRENT_DATE)
GROUP BY pi.patient_id, pi.plan_id, pi.policy_number
HAVING COUNT(p.prescription_id) > 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] How many hashtags have been created in March 2024?

[Assistant]
```sql
SELECT COUNT(*) AS march_2024_hashtag_count
FROM social_media.hashtags
WHERE created_at >= '2024-03-01'
  AND created_at <  '2024-04-01';
```

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, 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 bool )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )


[User] What is the current number of passengers at station with ID 'ST123' right now?

[Assistant] I'm sorry, but I can't provide information on the current number of passengers at a station. The data I have access to only includes static details about stations such as their name, location, and number of platforms, not real-time passenger counts.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.stations (
    station_id character varying(64) NOT NULL,  -- Unique identifier for the station
    station_name character varying(128) NOT NULL, -- Name of the station
    city character varying(100) NOT NULL, -- City where the station is located
    state_province character varying(100), -- State or province
    country_code character varying(3) NOT NULL, -- ISO country code
    address text, -- Full address of the station
    timezone character varying(64) NOT NULL, -- Timezone ID (e.g., 'America/New_York')
    number_of_platforms integer NOT NULL DEFAULT 0, -- Total number of platforms
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was created
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- When the station record was last updated
    PRIMARY KEY (station_id)
)


[User] Show me all token names and their contract addresses along with the wallet addresses of users who created wallets in the last 30 days, sorted by wallet creation date.

[Assistant] SELECT t.token_name, t.contract_address, w.address AS wallet_address FROM web3.tokens t JOIN web3.wallets w ON 1=1 WHERE w.created_at >= CURRENT_DATE - INTERVAL '30 days' ORDER BY w.created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )


[User] Which vehicles have a total maintenance cost exceeding 10000 across all their maintenance logs?

[Assistant] SELECT vehicle_id, SUM(cost) AS total_maintenance_cost FROM transportation.maintenance_logs GROUP BY vehicle_id HAVING SUM(cost) > 10000;

[User] For these vehicles, also show the count of maintenance logs and the average cost per log.

[Assistant] SELECT vehicle_id, COUNT(log_id) AS maintenance_log_count, AVG(cost) AS average_maintenance_cost FROM transportation.maintenance_logs GROUP BY vehicle_id HAVING SUM(cost) > 10000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )


[User] Show me each product_type along with the count of products for that type, but only include types where the average base_premium exceeds 500. Order the results by the product count in descending order.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type
HAVING AVG(base_premium) > 500
ORDER BY product_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, 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] 我想查看所有检查记录中检查员的ID和检查结果，同时统计每个检查员的检查次数。

[Assistant]
db.inspections.aggregate([
  {
    $group: {
      _id: '$inspector_employee_id',
      total_inspections: { $count: {} },
      results: { $push: '$result' }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      total_inspections: 1,
      results: 1,
      _id: 0
    }
  }
]);

[User] 如果我想只统计检查结果为'Fail'的次数，应该怎么改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Fail'
    }
  },
  {
    $group: {
      _id: '$inspector_employee_id',
      failed_inspections: { $count: {} }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      failed_inspections: 1,
      _id: 0
    }
  }
]);

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
Collection 'inspections'. Document structure: { _id: <ObjectId (or inspection_id)>, inspection_id: String, build_id: String (reference), component_id: String (reference, optional), step_id: String (reference, optional), inspection_type: String, inspector_employee_id: String (reference), inspection_timestamp: ISODate, result: String, remarks: String }. Required: inspection_id, build_id, inspection_type, inspector_employee_id, inspection_timestamp, result. Indexes on build_id, component_id, step_id, inspector_employee_id, result.


[User] Show me all business center services (category = 'Business Center') along with their property IDs and descriptions, where the service is available.

[Assistant] SELECT service_name, property_id, description FROM hospitality_technology.services WHERE category = 'Business Center' AND is_available = true;

[User] Now, join this with another query to include the property names from the properties table (assuming properties table has property_id and property_name columns).

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;

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

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;

[User] Actually, I need to see only services priced per hour (unit = 'Per Hour'), and order them by property name in alphabetical order.

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true AND s.unit = 'Per Hour' ORDER BY p.property_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)


[User] List all agencies that do not have a website URL specified. Return their agency_id, agency_name, and main_phone_number.

[Assistant] SELECT agency_id, agency_name, main_phone_number FROM government_services.agencies WHERE website_url IS NULL OR website_url = '';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )


[User] List all assets mentioned in DApp descriptions along with the DApp name and URL.

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

[User] Actually, only include assets of type 'cryptocurrency'.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)


[User] List document names and versions for documents that share the same case_id, showing each pair of versions.

[Assistant] SELECT d1.case_id, d1.document_name AS doc_name_v1, d1.version AS version1, d2.document_name AS doc_name_v2, d2.version AS version2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.case_id = d2.case_id AND d1.version < d2.version;

[User] Actually, I only want to compare the highest version against the second highest version per case.

[Assistant] SELECT d_prev.case_id, d_prev.document_name AS prev_doc, d_prev.version AS prev_version, d_latest.document_name AS latest_doc, d_latest.version AS latest_version FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id);

[User] Also include the upload timestamps and restrict to cases with at least three versions.

[Assistant] SELECT d_latest.case_id, d_prev.document_name AS prev_doc, d_prev.upload_timestamp AS prev_upload, d_latest.document_name AS latest_doc, d_latest.upload_timestamp AS latest_upload FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id) AND (SELECT COUNT(*) FROM legal_services.documents d2 WHERE d2.case_id = d_latest.case_id) >= 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)


[User] Count the total number of premium payments made in the year 2024.

[Assistant] SELECT COUNT(*) FROM premium_payments WHERE EXTRACT(YEAR FROM payment_date) = 2024

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )


[User] List all medical records, showing the record ID, record date, and the full name of the doctor who created the record. Include the patient ID as well.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id;

[User] Refine this to only include records where the chief_complaint is not null or empty and the doctor's specialty is 'Cardiology'.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology';

[User] Also, sort the results by record_date in descending order and limit the output to the top 10 records.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology' ORDER BY mr.record_date DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)


[User] What are the training programs or certifications completed by a staff member with the role of Platform Supervisor?

[Assistant] I'm sorry, but I don't have access to information about the training programs or certifications completed by staff members. The data available to me only includes basic staff details such as name, role, and contact information. For details on training or certifications, please refer to the HR department or relevant training records.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.staff ( staff_id text PRIMARY KEY, first_name text, last_name text, role text, primary_station_id text, employee_number text UNIQUE, hire_date date, contact_email text UNIQUE, contact_phone text, is_active boolean )


[User] For each booking, show the booking_id, seat_number, fare, and the city of the origin location for the trip that was booked.

[Assistant]
SELECT b.booking_id, b.seat_number, b.fare, orig.city AS origin_city
FROM transportation.bookings b
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.locations orig ON r.origin_location_id = orig.location_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


[User] Find the contract address and name for all NFT collections listed on the 'Ethereum' blockchain.

[Assistant] SELECT contract_address, name FROM nft_collections WHERE blockchain = 'Ethereum'

[User] For these collections, can you show the count of unique wallet addresses holding NFTs in each collection by joining with nft_holders?

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name

[User] Please filter the results to only include collections that have more than 100 unique holders.

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name HAVING COUNT(DISTINCT T2.wallet_address) > 100

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] List pairs of wallet IDs owned by the same user where the creation dates are more than one year apart. Show the user ID and the wallet IDs of both wallets.

[Assistant] SELECT w1.user_id, w1.wallet_id AS wallet_id_1, w2.wallet_id AS wallet_id_2 FROM web3.wallets w1 JOIN web3.wallets w2 ON w1.user_id = w2.user_id AND w2.created_at > w1.created_at + INTERVAL '1 year' ORDER BY w1.user_id, w1.created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )


[User] How many notifications have been sent for comments in total?

[Assistant]
SELECT COUNT(*)
FROM social_media.notifications
WHERE target_entity_type = 'comment';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )