[User] Find medical records where the assessment mentions the generic name of any medication. Show the record ID, record date, patient ID, and the generic name mentioned.

[Assistant] SELECT T1.record_id, T1.record_date, T1.patient_id, T2.generic_name FROM healthcare.medical_records AS T1 JOIN healthcare.medications AS T2 ON T1.assessment LIKE '%' || T2.generic_name || '%' WHERE T2.generic_name IS NOT NULL AND T2.generic_name != ''

[User] Filter these results to only include records for patient 'pat123' and include the medication name in the output.

[Assistant] SELECT T1.record_id, T1.record_date, T1.patient_id, T2.generic_name, T2.medication_name FROM healthcare.medical_records AS T1 JOIN healthcare.medications AS T2 ON T1.assessment LIKE '%' || T2.generic_name || '%' WHERE T2.generic_name IS NOT NULL AND T2.generic_name != '' AND T1.patient_id = 'pat123'

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 text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )


[User] Find all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient, ordered by count in descending order.

[Assistant]
SELECT patient_id, COUNT(*) AS group_plan_count
FROM healthcare.patient_insurance
WHERE group_number IS NOT NULL
GROUP BY patient_id
ORDER BY group_plan_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 healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] For each ERC1155 NFT contract on Ethereum, show the `contract_address`, `token_id`, total amount held across all wallets, and number of unique holders.

[Assistant]
SELECT nh.contract_address,
       nh.token_id,
       SUM(CAST(nh.amount AS bigint)) AS total_amount,
       COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM nft_holders nh
JOIN nft_metadata nm
  ON nh.contract_address = nm.contract_address
  AND nh.token_id = nm.token_id
WHERE nm.blockchain = 'Ethereum'
  AND nm.erc_type = 'ERC1155'
GROUP BY nh.contract_address, nh.token_id;

[User] Only include NFTs where the `total_amount` is greater than 1000.

[Assistant]
SELECT nh.contract_address,
       nh.token_id,
       SUM(CAST(nh.amount AS bigint)) AS total_amount,
       COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM nft_holders nh
JOIN nft_metadata nm
  ON nh.contract_address = nm.contract_address
  AND nh.token_id = nm.token_id
WHERE nm.blockchain = 'Ethereum'
  AND nm.erc_type = 'ERC1155'
GROUP BY nh.contract_address, nh.token_id
HAVING SUM(CAST(nh.amount AS bigint)) > 1000;

[User] Add the NFT `name` from `nft_metadata` in the result.

[Assistant]
SELECT nh.contract_address,
       nh.token_id,
       nm.name,
       SUM(CAST(nh.amount AS bigint)) AS total_amount,
       COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM nft_holders nh
JOIN nft_metadata nm
  ON nh.contract_address = nm.contract_address
  AND nh.token_id = nm.token_id
WHERE nm.blockchain = 'Ethereum'
  AND nm.erc_type = 'ERC1155'
GROUP BY nh.contract_address, nh.token_id, nm.name
HAVING SUM(CAST(nh.amount AS bigint)) > 1000;

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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE 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 sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE 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, -- 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 NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    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 mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


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

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

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

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

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, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

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


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

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

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

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

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

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

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

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

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 text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] What is the ticket price for a journey on train number T4321?

[Assistant] I'm sorry, but I don't have access to information about ticket prices for specific trains. The data I have is limited to train details such as model, manufacturer, capacity, and maintenance schedules. For ticket pricing, please consult the ticketing office or the official website.

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.trains ( train_id text PRIMARY KEY, train_number text UNIQUE, model text, manufacturer text, year_manufactured int, capacity int, status text, last_maintenance_date date, next_maintenance_date date )


[User] Show me all reservations with more than 2 adults, along with their property names and room types.

[Assistant] SELECT r.reservation_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2;

[User] Now, include only reservations with a total amount over $500 and order them by check-in date.

[Assistant] SELECT r.reservation_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 ORDER BY r.check_in_date;

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

[Assistant] SELECT r.reservation_id, r.guest_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 ORDER BY r.check_in_date;

[User] Actually, I need to see only reservations from properties with a star rating of 4.0 or higher.

[Assistant] SELECT r.reservation_id, r.guest_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount, p.star_rating FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 AND p.star_rating >= 4.0 ORDER BY r.check_in_date;

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 character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Provide a count of citizens registered per calendar year.

[Assistant] SELECT CAST(EXTRACT(YEAR FROM registration_date) AS INTEGER) AS registration_year, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY 1 ORDER BY 1;

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.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)


[User] List all servers that are currently online and have a player count greater than their average player count across all servers in the same region.

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online' AND s.current_players > r.avg_players;

[User] Can you also include the maximum players of each server in the result?

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, s.max_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online' AND s.current_players > r.avg_players;

[User] Now only show servers where current_players is at least 75% of max_players.

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, s.max_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online'
  AND s.current_players > r.avg_players
  AND s.current_players >= 0.75 * s.max_players;

[User] Please also show the average player count for the region in each row.

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, s.max_players, r.avg_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online'
  AND s.current_players > r.avg_players
  AND s.current_players >= 0.75 * s.max_players;

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.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
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) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )


[User] List all fuel refueling events with the refueled vehicle's make and model, the fuel type used, and the fueling location ID.

[Assistant]
SELECT fl.fuel_log_id, fl.log_timestamp, v.make, v.model, fl.fuel_type, fl.quantity, fl.unit, fl.total_cost, fl.location_id
FROM transportation.fuel_logs fl
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_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.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_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] 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] Show each contract's address along with the total number of events it has emitted and the total number of transactions sent to it.

[Assistant]
SELECT
  c.address,
  COUNT(e.event_id) AS event_count,
  COUNT(t.transaction_id) AS tx_count
FROM web3.contracts c
LEFT JOIN web3.events e
  ON c.contract_id = e.contract_id
LEFT JOIN web3.transactions t
  ON c.address = t.to_address
GROUP BY c.address;

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.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
CREATE TABLE web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)


[User] List the first and last names of employees and the full name of the citizens for whom they have scheduled appointments.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T3.first_name ,  T3.last_name FROM government_services.employees AS T1 JOIN government_services.appointments AS T2 ON T1.employee_id  =  T2.employee_id JOIN government_services.citizens AS T3 ON T2.citizen_id  =  T3.citizen_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 government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Find all pairs of different insurance records that share the same group_number, and show group_number, the patient_insurance_id of both records, and their corresponding patient_ids.

[Assistant]
SELECT a.group_number,
       a.patient_insurance_id AS pi_id1,
       a.patient_id            AS patient1_id,
       b.patient_insurance_id AS pi_id2,
       b.patient_id            AS patient2_id
FROM healthcare.patient_insurance a
JOIN healthcare.patient_insurance b
  ON a.group_number = b.group_number
 AND a.patient_insurance_id < b.patient_insurance_id
WHERE a.group_number IS NOT NULL;

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.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] Identify all instances where a vehicle's odometer_reading increased by more than 500 miles between two consecutive fuel log entries.

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

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

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

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

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

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


[User] Give me a breakdown of the number of reviews per day for the last 14 days, including the review_date and review count.

[Assistant]
SELECT DATE(review_date) AS review_day, COUNT(*) AS review_count
FROM hospitality_technology.reviews
WHERE review_date >= CURRENT_DATE - INTERVAL '14 days'
GROUP BY DATE(review_date)
ORDER BY review_day ASC;

[User] Add the number of public reviews for each day in a separate column named public_review_count.

[Assistant]
SELECT DATE(review_date) AS review_day,
       COUNT(*) AS review_count,
       SUM(CASE WHEN is_public THEN 1 ELSE 0 END) AS public_review_count
FROM hospitality_technology.reviews
WHERE review_date >= CURRENT_DATE - INTERVAL '14 days'
GROUP BY DATE(review_date)
ORDER BY review_day ASC;

[User] Now, also include the number of reviews per day with a rating_overall below 3 as a column called low_rating_count.

[Assistant]
SELECT DATE(review_date) AS review_day,
       COUNT(*) AS review_count,
       SUM(CASE WHEN is_public THEN 1 ELSE 0 END) AS public_review_count,
       SUM(CASE WHEN rating_overall < 3 THEN 1 ELSE 0 END) AS low_rating_count
FROM hospitality_technology.reviews
WHERE review_date >= CURRENT_DATE - INTERVAL '14 days'
GROUP BY DATE(review_date)
ORDER BY review_day 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.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] List the vehicle_id, make, model, and total maintenance cost for each vehicle that has undergone maintenance, ordering by total maintenance cost descending.

[Assistant]
SELECT m.vehicle_id, v.make, v.model, SUM(m.cost) AS total_maintenance_cost
FROM transportation.maintenance_logs m
JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id
GROUP BY m.vehicle_id, v.make, v.model
ORDER BY total_maintenance_cost DESC;

[User] Now further include the count of maintenance entries per vehicle and only include vehicles with more than 3 maintenance logs.

[Assistant]
SELECT m.vehicle_id, v.make, v.model, COUNT(*) AS maintenance_count, SUM(m.cost) AS total_maintenance_cost
FROM transportation.maintenance_logs m
JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id
GROUP BY m.vehicle_id, v.make, v.model
HAVING COUNT(*) > 3
ORDER BY total_maintenance_cost 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 transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] I want a list of game_id and the count of hidden achievements for each game.

[Assistant]
SELECT game_id, COUNT(*) AS hidden_achievement_count
FROM gaming_technology.achievements
WHERE hidden = TRUE
GROUP BY game_id;

[User] Now only include games where the hidden_achievement_count is greater than 5.

[Assistant]
SELECT game_id, COUNT(*) AS hidden_achievement_count
FROM gaming_technology.achievements
WHERE hidden = TRUE
GROUP BY game_id
HAVING COUNT(*) > 5;

[User] Also order the results by hidden_achievement_count in descending order.

[Assistant]
SELECT game_id, COUNT(*) AS hidden_achievement_count
FROM gaming_technology.achievements
WHERE hidden = TRUE
GROUP BY game_id
HAVING COUNT(*) > 5
ORDER BY hidden_achievement_count DESC;

[User] Finally, include the average points of those hidden achievements as avg_hidden_points.

[Assistant]
SELECT game_id,
       COUNT(*) AS hidden_achievement_count,
       AVG(points) AS avg_hidden_points
FROM gaming_technology.achievements
WHERE hidden = TRUE
GROUP BY game_id
HAVING COUNT(*) > 5
ORDER BY hidden_achievement_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 gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
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.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )
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, game_id.uuid, name.text, description.text, icon_url.text, points.integer, 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] List each transaction along with its status and the names of any events that were emitted during that transaction.

[Assistant]
SELECT tr.transaction_id, tr.status, e.event_name
FROM web3.transactions tr
LEFT JOIN web3.events e ON tr.transaction_id = e.transaction_id;

[User] Only show transactions that had more than one event emitted, and list the number of events for each such transaction.

[Assistant]
SELECT tr.transaction_id, tr.status, COUNT(e.event_id) AS event_count
FROM web3.transactions tr
JOIN web3.events e ON tr.transaction_id = e.transaction_id
GROUP BY tr.transaction_id, tr.status
HAVING COUNT(e.event_id) > 1;

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.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] What proportion of posts have received at least one like? Return the ratio as a decimal between 0 and 1.

[Assistant]
SELECT COUNT(DISTINCT CASE WHEN l.post_id IS NOT NULL THEN p.post_id END)::float / COUNT(DISTINCT p.post_id) AS like_ratio
FROM social_media.posts p
LEFT JOIN social_media.likes l ON p.post_id = l.post_id;

[User] Please break down this ratio by media_type, excluding posts without a media_type.

[Assistant]
SELECT p.media_type,
       COUNT(DISTINCT CASE WHEN l.post_id IS NOT NULL THEN p.post_id END)::float / COUNT(*) AS like_ratio
FROM social_media.posts p
LEFT JOIN social_media.likes l ON p.post_id = l.post_id
WHERE p.media_type IS NOT NULL
GROUP BY p.media_type;

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 average age of verified citizens as of today?

[Assistant]
SELECT AVG(EXTRACT(YEAR FROM AGE(NOW(), date_of_birth))) AS average_age_verified
FROM government_services.citizens
WHERE is_verified = TRUE;

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.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Which patients have insurance policies that are effective between May 1st, 2023 and October 1st, 2023? Show their patient_id, policy_number, and effective_date, and also include the related plan_id.

[Assistant] SELECT patient_id, policy_number, effective_date, plan_id FROM healthcare.patient_insurance WHERE effective_date >= '2023-05-01' AND effective_date <= '2023-10-01';

[User] I only want to see policies that are still primary. Could you adjust the query to add that condition?

[Assistant] SELECT patient_id, policy_number, effective_date, plan_id FROM healthcare.patient_insurance WHERE effective_date >= '2023-05-01' AND effective_date <= '2023-10-01' AND is_primary = true;

[User] Actually, please also show only entries where the subscriber_name starts with the letter 'A'.

[Assistant] SELECT patient_id, policy_number, effective_date, plan_id FROM healthcare.patient_insurance WHERE effective_date >= '2023-05-01' AND effective_date <= '2023-10-01' AND is_primary = true AND subscriber_name LIKE 'A%';

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.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List all case numbers and names, along with the full name of the client associated with each case.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN clients AS T2 ON T1.client_id = T2.client_id;

[User] Now, only include cases that were opened after 2023-06-01.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN clients AS T2 ON T1.client_id = T2.client_id WHERE T1.date_opened > '2023-06-01';

[User] Please order the results by the client's last name in ascending order.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN clients AS T2 ON T1.client_id = T2.client_id WHERE T1.date_opened > '2023-06-01' ORDER BY T2.last_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 legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )


[User] For each user, list all the distinct actions they have performed along with the count of each action.

[Assistant] SELECT user_id, action, COUNT(*) FROM trading_platform.logs GROUP BY user_id, action ORDER BY user_id, action;

[User] Now, only show users who have performed more than 5 distinct actions.

[Assistant] SELECT user_id FROM trading_platform.logs GROUP BY user_id HAVING COUNT(DISTINCT action) > 5 ORDER BY user_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 trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )


[User] Which is the token with the largest difference between its highest and lowest price in the last 24h on each chain, and what is the token's symbol and current price?

[Assistant]
SELECT chain, token_symbol, price, (highest_price_24h - lowest_price_24h) AS price_diff_24h
FROM token_basic_info
WHERE (chain, highest_price_24h - lowest_price_24h) IN (
  SELECT chain, MAX(highest_price_24h - lowest_price_24h) AS diff
  FROM token_basic_info
  GROUP BY chain
)
ORDER BY price_diff_24h DESC;

[User] Could you also include the percentage change over 24 hours for each token in the result?

[Assistant]
SELECT chain, token_symbol, price, price_change_percentage_24h, (highest_price_24h - lowest_price_24h) AS price_diff_24h
FROM token_basic_info
WHERE (chain, highest_price_24h - lowest_price_24h) IN (
  SELECT chain, MAX(highest_price_24h - lowest_price_24h) AS diff
  FROM token_basic_info
  GROUP BY chain
)
ORDER BY price_diff_24h DESC;

[User] I'm only interested in tokens where this price difference exceeds $5. Can you filter for that?

[Assistant]
SELECT chain, token_symbol, price, price_change_percentage_24h, (highest_price_24h - lowest_price_24h) AS price_diff_24h
FROM token_basic_info
WHERE (chain, highest_price_24h - lowest_price_24h) IN (
  SELECT chain, MAX(highest_price_24h - lowest_price_24h) AS diff
  FROM token_basic_info
  GROUP BY chain
)
AND (highest_price_24h - lowest_price_24h) > 5
ORDER BY price_diff_24h 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 token_basic_info (",
    "coin_id character varying(100) NOT NULL, -- the id of the token",
    "token_name character varying(100) NOT NULL, -- the token's name",
    "token_symbol character varying(100) NOT NULL, -- the token's symbol",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "chain text, -- the chain that the token resides",
    "price double precision, -- the current price of the token",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days",
    "highest_price_24h double precision, -- the highest price of the token in 24 hours",
    "lowest_price_24h double precision,  -- the lowest price of the token in 24 hours",
    "market_cap double precision, -- the market cap of the token",
    "market_cap_rank bigint, -- the rank of the token market cap in desc",
    "market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours",
    "total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX)",
    "narrative text, -- the category or narrative of the token",
    "trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token.",
    ",PRIMARY KEY (coin_id, chain));",


[User] Find all in-game items that have a 'mana_cost' attribute in their attributes JSON. Show the item ID, item name, and the value of the 'mana_cost'.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost'

[User] Now, only include items where the 'mana_cost' is greater than 50.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost' AND (attributes ->> 'mana_cost')::int > 50

[User] Add the item's rarity and the title of the game it belongs to in the output.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50

[User] Filter the results to only include items from games in the 'Fantasy' genre.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50 AND t2.genre = 'Fantasy'

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.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.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
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] Show me the object ID, coin type, and balance for all SUI coins where the status is 'active'.

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

[User] Also, include the owner address in the result.

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

[User] Filter the results to only show coins where the balance is greater than '100000000000'.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND CAST(balance AS NUMERIC) > 100000000000

[User] Sort the results by balance in descending order and limit the output to 10.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND CAST(balance AS NUMERIC) > 100000000000 ORDER BY CAST(balance AS NUMERIC) 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 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] What is the total market cap for all tokens listed on the 'Polygon' chain?

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon';

[User] Only sum the market cap for tokens on 'Polygon' that have a 24-hour volume greater than 500000.

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Also show the number of unique tokens that meet these criteria.

[Assistant] SELECT COUNT(DISTINCT token_symbol), SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Can you show the total market cap and token count for *each* chain that meets these volume criteria, ordered by total market cap descending?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) AS token_count, SUM(market_cap) AS total_market_cap FROM token_dexpool_info WHERE volume_24h > 500000 GROUP BY chain ORDER BY total_market_cap 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 token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )


[User] Give me the number of patient insurance policies for each plan where the policy is currently active. Return plan_id and policy_count.

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

[User] Now, only include plans where the count is greater than 5 and sort by policy_count descending.

[Assistant]
SELECT
  plan_id,
  COUNT(*) AS policy_count
FROM healthcare.patient_insurance
WHERE (expiration_date IS NULL OR expiration_date >= CURRENT_DATE)
GROUP BY plan_id
HAVING COUNT(*) > 5
ORDER BY policy_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 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] List all premium payments made by Bank Transfer where the amount_paid is greater than 5000. Show payment_id, policy_id, customer_id, amount_paid, and payment_date, ordered by amount_paid descending.

[Assistant]
SELECT payment_id,
       policy_id,
       customer_id,
       amount_paid,
       payment_date
FROM insurance.premium_payments
WHERE payment_method = 'Bank Transfer'
  AND amount_paid > 5000
ORDER BY amount_paid 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.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.agents (
    agent_id character varying(64) NOT NULL, -- unique identifier for the agent
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    agency_name character varying(150),
    license_number character varying(100) NOT NULL UNIQUE, -- state insurance license number
    license_state character varying(50) NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(30),
    hire_date date,
    termination_date date,
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Terminated, On Leave
    commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, -- percentage commission
    manager_id character varying(64), -- identifier for the agent's manager (FK to agents or employees)
    PRIMARY KEY (agent_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)


[User] For each guest, list reservation_id, guest_id, check_in_date, and the next reservation_id and its check_in_date.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     );

[User] Only include guests who have at least two reservations.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

[User] Also, only show next reservations that occur within 30 days of the current reservation.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
   AND r2.check_in_date <= r1.check_in_date + INTERVAL '30 days'
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

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.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )