[User] Show the total transaction amount for each customer, including their full name and risk profile. Join customers to accounts and then to transactions.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile;

[User] Filter this report to only include transactions from the last 90 days.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
WHERE
  T1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile;

[User] Also, only include customers whose total transaction amount in this period exceeds 1000.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
WHERE
  T1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile
HAVING
  SUM(T1.amount) > 1000;

[User] Sort the results by total transaction amount in descending order and limit to the top 10 customers.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
WHERE
  T1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile
HAVING
  SUM(T1.amount) > 1000
ORDER BY
  total_transaction_amount 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 financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] Find all patients who have both an email address and an emergency contact listed, and show their names, email, and emergency contact phone numbers.

[Assistant] SELECT first_name, last_name, email, emergency_contact_phone FROM healthcare.patients WHERE email IS NOT NULL AND emergency_contact_phone 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.patients ( patient_id text PRIMARY KEY, 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 )


[User] Show the total number of customers in each state.

[Assistant]
SELECT
  state,
  COUNT(customer_id)
FROM insurance.customers
GROUP BY
  state;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.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.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


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

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

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

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

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

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

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


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

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

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


[User] I want to know the total expenditure of each player on rare items, showing their player_id and total spent.

[Assistant]
SELECT pi.player_id,
       SUM(igi.cost_amount * pi.quantity) AS total_spent
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id
WHERE igi.rarity = 'Rare'
GROUP BY pi.player_id;

[User] Can you include only players who have spent more than 500?

[Assistant]
SELECT pi.player_id,
       SUM(igi.cost_amount * pi.quantity) AS total_spent
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id
WHERE igi.rarity = 'Rare'
GROUP BY pi.player_id
HAVING SUM(igi.cost_amount * pi.quantity) > 500;

[User] Also, show the number of distinct Rare item types each qualifying player has purchased.

[Assistant]
SELECT pi.player_id,
       SUM(igi.cost_amount * pi.quantity) AS total_spent,
       COUNT(DISTINCT igi.item_type) AS distinct_item_types
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id
WHERE igi.rarity = 'Rare'
GROUP BY pi.player_id
HAVING SUM(igi.cost_amount * pi.quantity) > 500;

[User] Now, order the output by total_spent descending and limit to the top 10 players.

[Assistant]
SELECT pi.player_id,
       SUM(igi.cost_amount * pi.quantity) AS total_spent,
       COUNT(DISTINCT igi.item_type) AS distinct_item_types
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id
WHERE igi.rarity = 'Rare'
GROUP BY pi.player_id
HAVING SUM(igi.cost_amount * pi.quantity) > 500
ORDER BY total_spent 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 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.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 all premium payments made in Q1 2023, along with their payment methods and amounts, sorted by payment date.

[Assistant] SELECT payment_method, amount_paid, payment_date FROM insurance.premium_payments WHERE payment_date BETWEEN '2023-01-01' AND '2023-03-31' ORDER BY payment_date;

[User] Now break this down by payment method to show the total amount collected per payment method in that quarter.

[Assistant] SELECT payment_method, SUM(amount_paid) AS total_amount FROM insurance.premium_payments WHERE payment_date BETWEEN '2023-01-01' AND '2023-03-31' GROUP BY payment_method ORDER BY total_amount DESC;

[User] I also want to see the average payment amount for each payment method in Q1 2023.

[Assistant] SELECT payment_method, AVG(amount_paid) AS average_payment FROM insurance.premium_payments WHERE payment_date BETWEEN '2023-01-01' AND '2023-03-31' GROUP BY payment_method ORDER BY average_payment DESC;

[User] Finally, show me only payment methods where the average payment was greater than $300.

[Assistant] SELECT payment_method, AVG(amount_paid) AS average_payment FROM insurance.premium_payments WHERE payment_date BETWEEN '2023-01-01' AND '2023-03-31' GROUP BY payment_method HAVING AVG(amount_paid) > 300 ORDER BY average_payment 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.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )


[User] List all wallet addresses that hold any NFT currently. Show the wallet address and the count of distinct token IDs they hold.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) FROM nft_holders GROUP BY wallet_address;

[User] Filter the list to only include wallets that hold more than 5 unique NFTs.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) FROM nft_holders GROUP BY wallet_address HAVING COUNT(DISTINCT token_id) > 5;

[User] Order the results by the count of unique NFTs held in descending order.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) AS unique_nft_count FROM nft_holders GROUP BY wallet_address HAVING COUNT(DISTINCT token_id) > 5 ORDER BY unique_nft_count DESC;

[User] Limit the output to the top 20 wallets.

[Assistant] SELECT wallet_address, COUNT(DISTINCT token_id) AS unique_nft_count FROM nft_holders GROUP BY wallet_address HAVING COUNT(DISTINCT token_id) > 5 ORDER BY unique_nft_count DESC LIMIT 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar 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_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name 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 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 NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar 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 ( 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 mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) 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_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 )


[User] Show the number of staff members for each property, along with the property name.

[Assistant]
SELECT p.property_name, COUNT(s.staff_id) AS staff_count
FROM hospitality_technology.properties p
JOIN hospitality_technology.staff s ON p.property_id = s.property_id
GROUP BY p.property_name;

[User] Only include properties with more than 20 staff members, and order the result by staff count descending.

[Assistant]
SELECT p.property_name, COUNT(s.staff_id) AS staff_count
FROM hospitality_technology.properties p
JOIN hospitality_technology.staff s ON p.property_id = s.property_id
GROUP BY p.property_name
HAVING COUNT(s.staff_id) > 20
ORDER BY staff_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)


[User] Find transactions that triggered events and whose to_address matches the contract_id of the emitted event. List the transaction ID, the to_address, and the count of such events for that transaction.

[Assistant] SELECT t.transaction_id, t.to_address, COUNT(e.event_id) AS matching_event_count FROM web3.transactions t JOIN web3.events e ON t.transaction_id = e.transaction_id WHERE t.to_address IS NOT NULL AND t.to_address = e.contract_id GROUP BY t.transaction_id, t.to_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.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, 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.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )


[User] I’d like to find all pairs of securities that belong to the same sector.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector
WHERE a.security_id < b.security_id;

[User] Actually, only include pairs where the two securities are listed on different exchanges.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange;

[User] Also, I want the results sorted by sector, then by exchange_a.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange;

[User] One more thing: include both exchanges in the ORDER BY so that within each sector it’s sorted by exchange_a then exchange_b.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange, b.exchange;

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 financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )


[User] Which route numbers connect locations with a distance less than 80 km and more than 5 words in their description? Include the route type in the results.

[Assistant] SELECT route_number, type FROM transportation.routes WHERE distance_km < 80 AND array_length(regexp_split_to_array(description, '\s+'), 1) > 5;

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


[User] Show all medical records with the record_id, record_date, the patient's insurance policy_number, and the doctor's ID, for records linked to a currently active insurance policy.

[Assistant]
SELECT mr.record_id, mr.record_date, pi.policy_number, mr.doctor_id
FROM healthcare.medical_records mr
INNER JOIN healthcare.patient_insurance pi ON mr.patient_id = pi.patient_id
WHERE pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_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 healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] List the first and last name of each citizen along with the city and state of the service location for their agency.

[Assistant]
SELECT c.first_name, c.last_name, sl.city, sl.state
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.application_id IS NOT NULL AND e.agency_id IS NOT NULL
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_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, 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.payments ( payment_id text, 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, 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.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] Show the invoice number, issue date, total amount, and the client's full name for all invoices, including only those invoices that have not been paid fully.

[Assistant] SELECT i.invoice_number, i.issue_date, i.total_amount, c.first_name || ' ' || c.last_name AS client_full_name FROM legal_services.invoices i JOIN legal_services.clients c ON i.client_id = c.client_id WHERE i.amount_paid < i.total_amount;

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, first_name.text, last_name.text, company_name.text, email.text, phone.text, address.text, date_registered.timestamp, status.text )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, 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] Could you list each game_id along with the count of hidden achievements and the count of visible achievements?

[Assistant]
SELECT game_id,
       SUM(CASE WHEN hidden THEN 1 ELSE 0 END) AS hidden_count,
       SUM(CASE WHEN NOT hidden THEN 1 ELSE 0 END) AS visible_count
FROM gaming_technology.achievements
GROUP BY game_id;

[User] Actually, please provide pairs of one hidden and one visible achievement name for each game where both types exist.

[Assistant]
SELECT h.game_id,
       h.name AS hidden_name,
       v.name AS visible_name
FROM gaming_technology.achievements h
JOIN gaming_technology.achievements v
  ON h.game_id = v.game_id
 AND h.hidden = TRUE
 AND v.hidden = FALSE
WHERE EXISTS (
  SELECT 1 FROM gaming_technology.achievements x
   WHERE x.game_id = h.game_id
     AND x.hidden = FALSE
)
AND EXISTS (
  SELECT 1 FROM gaming_technology.achievements y
   WHERE y.game_id = h.game_id
     AND y.hidden = 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 gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] For each citizen who has made at least one payment, show the citizen's full name, number of payments, and total amount paid, grouped by currency.

[Assistant]
SELECT
  c.first_name || ' ' || c.last_name AS full_name,
  p.currency,
  COUNT(*) AS payment_count,
  SUM(p.amount) AS total_amount
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
GROUP BY full_name, p.currency;

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, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )


[User] Show me all active managers along with their property IDs and the number of staff members they supervise, ordered by the number of supervised staff in descending order.

[Assistant] SELECT s.staff_id, s.property_id, s.first_name, s.last_name, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s LEFT JOIN hospitality_technology.staff s2 ON s.staff_id = s2.manager_id WHERE s.position = 'Manager' AND s.is_active = true GROUP BY s.staff_id, s.property_id, s.first_name, s.last_name ORDER BY supervised_staff_count DESC;

[User] Now, include only managers who supervise at least 3 staff members and show their email addresses as well.

[Assistant] SELECT s.staff_id, s.property_id, s.first_name, s.last_name, s.work_email, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s LEFT JOIN hospitality_technology.staff s2 ON s.staff_id = s2.manager_id WHERE s.position = 'Manager' AND s.is_active = true GROUP BY s.staff_id, s.property_id, s.first_name, s.last_name, s.work_email HAVING COUNT(s2.staff_id) >= 3 ORDER BY supervised_staff_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)


[User] List all guests who have communication consent enabled along with their email addresses.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email
FROM guests
WHERE communication_consent = TRUE;

[User] Now only include those guests who also have a loyalty_member_id.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email,
       loyalty_member_id
FROM guests
WHERE communication_consent = TRUE
  AND loyalty_member_id 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 hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )


[User] For each event recorded, list its ID, name, and the status and value of the transaction in which it occurred.

[Assistant] SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_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 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, 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 text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] List the first and last names, email, and loyalty program ID of all passengers who joined after January 1, 2024.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01';

[User] Include only those passengers who are enrolled in any loyalty program (loyalty_program_id is not null), and order the results by last name.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01' AND loyalty_program_id IS NOT NULL
ORDER BY last_name;

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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
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 )


[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] Show me all wallet addresses that belong to user_id 'U1001', along with their private keys.

[Assistant] SELECT address_id, private_key FROM blockchain.wallets WHERE user_id = 'U1001';

[User] Now join this with another table to show the count of transactions for each of these wallet addresses.

[Assistant] Note: The schema only includes the wallets table. Without a transactions table in the schema, this query cannot be executed. Please provide the transactions table structure if you need this analysis.

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 blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )


[User] Show me all insurance plans that have more than 5 patients enrolled, along with the provider name and count of patients, sorted by patient count in descending order.

[Assistant] SELECT i.plan_name, i.insurance_provider, COUNT(p.patient_id) AS patient_count FROM healthcare.insurance_plans i JOIN healthcare.patients p ON i.plan_id = p.primary_insurance_id GROUP BY i.plan_id HAVING COUNT(p.patient_id) > 5 ORDER BY patient_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.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.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)


[User] Show me the top 3 tokens by USD value inflow where smart money was buying (type = 1), along with their token symbol and narrative.

[Assistant] SELECT token_symbol, narrative, usd_value FROM smart_money_token_inflow WHERE type = 1 ORDER BY usd_value DESC LIMIT 3;

[User] Actually, I want to see tokens with a USD value over $100,000.

[Assistant] SELECT token_symbol, narrative, usd_value FROM smart_money_token_inflow WHERE type = 1 AND usd_value > 100000 ORDER BY usd_value DESC LIMIT 3;

[User] Can you filter these results to only include tokens from the Ethereum chain?

[Assistant] SELECT token_symbol, narrative, usd_value FROM smart_money_token_inflow WHERE type = 1 AND usd_value > 100000 AND chain = 'Ethereum' ORDER BY usd_value DESC LIMIT 3;

[User] Now include the 24-hour trading volume for these tokens from the token_dexpool_info table.

[Assistant] SELECT smti.token_symbol, smti.narrative, smti.usd_value, tdi.volume_24h FROM smart_money_token_inflow smti LEFT JOIN token_dexpool_info tdi ON smti.token_symbol = tdi.token_symbol AND smti.chain = tdi.chain WHERE smti.type = 1 AND smti.usd_value > 100000 AND smti.chain = 'Ethereum' ORDER BY smti.usd_value DESC LIMIT 3;

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

 "CREATE TABLE 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));",

  "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_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",


[User] List lawyers who have any unbilled time entries. Show their first name, last name, and the count of their unbilled entries.

[Assistant] SELECT T1.first_name, T1.last_name, COUNT(T2.entry_id) FROM lawyers AS T1 JOIN time_entries AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.is_billed = false GROUP BY T1.lawyer_id, T1.first_name, T1.last_name;

[User] Modify that query to only include entries marked as billable, and instead show the total hours spent rather than the count.

[Assistant] SELECT T1.first_name, T1.last_name, SUM(T2.hours_spent) FROM lawyers AS T1 JOIN time_entries AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.is_billed = false AND T2.is_billable = true GROUP BY T1.lawyer_id, T1.first_name, T1.last_name;

[User] Now, only show lawyers with more than 10 unbilled billable hours in total, and sort the results by the total hours descending.

[Assistant] SELECT T1.first_name, T1.last_name, SUM(T2.hours_spent) FROM lawyers AS T1 JOIN time_entries AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.is_billed = false AND T2.is_billable = true GROUP BY T1.lawyer_id, T1.first_name, T1.last_name HAVING SUM(T2.hours_spent) > 10 ORDER BY SUM(T2.hours_spent) 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 legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.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.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
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 every manufacturer, show the total number of medications they produce, and the number of those that have an NDC code starting with '5'.

[Assistant] SELECT manufacturer, COUNT(*) AS total_medications, COUNT(CASE WHEN ndc_code LIKE '5%' THEN 1 END) AS ndc_starting_with_5 FROM healthcare.medications GROUP BY manufacturer;

[User] Now only include manufacturers who have at least 2 medications in total.

[Assistant] SELECT manufacturer, COUNT(*) AS total_medications, COUNT(CASE WHEN ndc_code LIKE '5%' THEN 1 END) AS ndc_starting_with_5 FROM healthcare.medications GROUP BY manufacturer 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 healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)


[User] List the trip ID, route number, vehicle ID, and the total fuel cost associated with each trip.

[Assistant] SELECT t.trip_id, r.route_number, t.vehicle_id, SUM(fl.total_cost) AS total_fuel_cost FROM transportation.trips t JOIN transportation.routes r ON t.route_id = r.route_id JOIN transportation.fuel_logs fl ON t.trip_id = fl.trip_id GROUP BY t.trip_id, r.route_number, t.vehicle_id;

[User] Only include trips where the total fuel cost is greater than 1000.

[Assistant] SELECT t.trip_id, r.route_number, t.vehicle_id, SUM(fl.total_cost) AS total_fuel_cost FROM transportation.trips t JOIN transportation.routes r ON t.route_id = r.route_id JOIN transportation.fuel_logs fl ON t.trip_id = fl.trip_id GROUP BY t.trip_id, r.route_number, t.vehicle_id HAVING SUM(fl.total_cost) > 1000;

[User] Also, order the results by total fuel cost in descending order.

[Assistant] SELECT t.trip_id, r.route_number, t.vehicle_id, SUM(fl.total_cost) AS total_fuel_cost FROM transportation.trips t JOIN transportation.routes r ON t.route_id = r.route_id JOIN transportation.fuel_logs fl ON t.trip_id = fl.trip_id GROUP BY t.trip_id, r.route_number, t.vehicle_id HAVING SUM(fl.total_cost) > 1000 ORDER BY total_fuel_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.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.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] Show the name, symbol, and type of each asset, along with the total number of orders placed for each asset.

[Assistant]
SELECT a.name, a.symbol, a.type, COUNT(o.order_id) AS order_count
FROM trading_platform.assets a
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id, a.name, a.symbol, a.type;

[User] Only include assets that have at least 10 orders, and order the result by order_count descending.

[Assistant]
SELECT a.name, a.symbol, a.type, COUNT(o.order_id) AS order_count
FROM trading_platform.assets a
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id, a.name, a.symbol, a.type
HAVING COUNT(o.order_id) >= 10
ORDER BY order_count DESC;

[User] Instead of all orders, only consider orders with status 'open'.

[Assistant]
SELECT a.name, a.symbol, a.type, COUNT(o.order_id) AS open_order_count
FROM trading_platform.assets a
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id AND o.status = 'open'
GROUP BY a.asset_id, a.name, a.symbol, a.type
HAVING COUNT(o.order_id) >= 10
ORDER BY open_order_count DESC;

[User] The SQL doesn't work because some assets have no open orders, but I want to include those assets with a count of 0. Please update the query accordingly.

[Assistant]
SELECT a.name, a.symbol, a.type, COUNT(o.order_id) AS open_order_count
FROM trading_platform.assets a
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id AND o.status = 'open'
GROUP BY a.asset_id, a.name, a.symbol, a.type
HAVING COUNT(o.order_id) >= 10 OR COUNT(o.order_id) = 0
ORDER BY open_order_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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] What is the average daily trading volume for each security_id in the market_data table from the last 30 days?

[Assistant] SELECT security_id, AVG(volume) as avg_daily_volume FROM financial_services.market_data WHERE data_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY security_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 financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id text, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )


[User] 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 detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

[Assistant] I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text )


[User] For each asset, I want to know how many orders have the status 'filled', showing the asset symbol.

[Assistant]
SELECT m.value AS asset_symbol,
       COUNT(*) AS filled_order_count
FROM trading_platform.orders o
JOIN trading_platform.metadata m
  ON o.asset_id = m.asset_id
 AND m.key = 'symbol'
WHERE o.status = 'filled'
GROUP BY m.value;

[User] Include assets that have zero filled orders, showing filled_order_count as 0.

[Assistant]
WITH asset_symbols AS (
  SELECT DISTINCT asset_id,
         value AS asset_symbol
  FROM trading_platform.metadata
  WHERE key = 'symbol'
)
SELECT a.asset_symbol,
       COALESCE(f.filled_order_count, 0) AS filled_order_count
FROM asset_symbols a
LEFT JOIN (
  SELECT asset_id,
         COUNT(*) AS filled_order_count
  FROM trading_platform.orders
  WHERE status = 'filled'
  GROUP BY asset_id
) f
  ON a.asset_id = f.asset_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.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)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)


[User] What is the average investment value for projects that completed Series A funding rounds?

[Assistant] SELECT AVG(investment_value) as avg_investment FROM project_fundraising_record WHERE rounds_name = 'Series 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 project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )


[User] Show me all patients who have both primary and non-primary insurance plans, along with their policy numbers and expiration dates.

[Assistant] SELECT p1.patient_id, p1.policy_number AS primary_policy, p1.expiration_date AS primary_expiry, p2.policy_number AS non_primary_policy, p2.expiration_date AS non_primary_expiry FROM healthcare.patient_insurance p1 JOIN healthcare.patient_insurance p2 ON p1.patient_id = p2.patient_id WHERE p1.is_primary = true AND p2.is_primary = false;

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] List all smart money addresses with a profit over $500,000, including their chain and last trade time.

[Assistant] SELECT address, chain, last_trade_time FROM smart_money_profit WHERE profit > 500000;

[User] I only want to see addresses from Ethereum or Binance chains.

[Assistant] SELECT address, chain, last_trade_time FROM smart_money_profit WHERE profit > 500000 AND chain IN ('Ethereum', 'Binance');

[User] Can you also include their rank and order by rank instead?

[Assistant] SELECT address, chain, last_trade_time, rank FROM smart_money_profit WHERE profit > 500000 AND chain IN ('Ethereum', 'Binance') ORDER BY rank;

[User] Actually, just show me the top 3 by rank.

[Assistant] SELECT address, chain, last_trade_time, rank FROM smart_money_profit WHERE profit > 500000 AND chain IN ('Ethereum', 'Binance') ORDER BY rank LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )


[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 is the average, minimum, and maximum interest_rate for each loan_type among active loans?

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type;

[User] Exclude loan types with fewer than 5 active loans.

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING COUNT(*) >= 5;

[User] Sort the result by average_interest_rate descending and only return the top 5 loan types.

[Assistant]
SELECT loan_type,
       AVG(interest_rate) AS avg_interest_rate,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate
FROM financial_services.loans
WHERE status = 'Active'
GROUP BY loan_type
HAVING COUNT(*) >= 5
ORDER BY avg_interest_rate DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans (
    loan_id character varying(64) NOT NULL, -- unique identifier for the loan, could be same as account_id
    account_id character varying(64) NOT NULL UNIQUE, -- link to the general account record
    loan_type character varying(50) NOT NULL, -- e.g., Mortgage, Personal, Auto, Student
    principal_amount numeric(19, 4) NOT NULL, -- original loan amount
    current_principal_balance numeric(19, 4) NOT NULL, -- remaining principal
    interest_rate numeric(6, 4) NOT NULL, -- annual interest rate
    term_months integer NOT NULL, -- loan term in months
    origination_date date NOT NULL, -- date the loan was disbursed
    maturity_date date NOT NULL, -- date the loan is due to be fully repaid
    monthly_payment numeric(12, 4), -- scheduled monthly payment amount
    collateral_description text, -- description of collateral, if secured loan
    status character varying(32) NOT NULL, -- e.g., Active, Paid Off, Defaulted
    PRIMARY KEY (loan_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id)
)


[User] List all narratives with a trend rank better than 50, showing the narrative name and their listed 'Top 3 Coins'.

[Assistant] SELECT narrative, top_3_coins FROM narrative_info WHERE trend_rank < 50

[User] Could you also include the 24-hour trading volume for these narratives and only show those where the volume is greater than 10,000,000 USD?

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000

[User] Please order the results by 24-hour trading volume in descending order.

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h DESC

[User] Finally, limit the output to the top 10 and add the total number of tokens for each narrative.

[Assistant] SELECT narrative, top_3_coins, volume_24h, token_num FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h 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 narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )