[User] For each guest, calculate their total spending on delivered service orders and the total number of those orders.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
WHERE so.status = 'delivered'
GROUP BY g.guest_id, full_name;

[User] I need the breakdown by month for the current year. Show guest ID, month, total spent, and total orders.

[Assistant]
SELECT so.guest_id,
       DATE_TRUNC('month', so.delivery_timestamp) AS month,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered'
  AND so.delivery_timestamp >= '2024-01-01'
  AND so.delivery_timestamp < '2025-01-01'
GROUP BY so.guest_id, month
ORDER BY month;

[User] Also include the guest’s email and only show months where total spent is greater than 500.

[Assistant]
SELECT sub.guest_id,
       g.email,
       sub.month,
       sub.total_spent,
       sub.total_orders
FROM (
  SELECT so.guest_id,
         DATE_TRUNC('month', so.delivery_timestamp) AS month,
         SUM(so.total_price) AS total_spent,
         COUNT(*) AS total_orders
  FROM hospitality_technology.service_orders so
  WHERE so.status = 'delivered'
    AND so.delivery_timestamp >= '2024-01-01'
    AND so.delivery_timestamp < '2025-01-01'
  GROUP BY so.guest_id, month
) sub
JOIN hospitality_technology.guests g
  ON sub.guest_id = g.guest_id
WHERE sub.total_spent > 500
ORDER BY sub.month;

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 text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] I want to find all claim IDs that have both an 'Accident Report' and a 'Police Report' document.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report';

[User] Now, only include those pairs if both documents were uploaded after '2024-06-01'.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01';

[User] Additionally, ensure that both files are larger than 500 KB.

[Assistant]
SELECT DISTINCT a.claim_id
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01'
  AND a.file_size_bytes > 512000
  AND b.file_size_bytes > 512000;

[User] Finally, show me the file_name and uploaded_by for both document types in the results.

[Assistant]
SELECT
    a.claim_id,
    a.file_name       AS accident_file_name,
    a.uploaded_by     AS accident_uploaded_by,
    b.file_name       AS police_file_name,
    b.uploaded_by     AS police_uploaded_by
FROM insurance.claim_documents a
JOIN insurance.claim_documents b
  ON a.claim_id = b.claim_id
WHERE a.document_type = 'Accident Report'
  AND b.document_type = 'Police Report'
  AND a.uploaded_at > '2024-06-01'
  AND b.uploaded_at > '2024-06-01'
  AND a.file_size_bytes > 512000
  AND b.file_size_bytes > 512000;

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


[User] Show each citizen's first and last notification IDs based on sent_at.

[Assistant]
WITH bounds AS (
  SELECT citizen_id,
         MIN(sent_at) AS first_sent,
         MAX(sent_at) AS last_sent
  FROM government_services.notifications
  GROUP BY citizen_id
)
SELECT n1.citizen_id,
       n1.notification_id AS first_notification_id,
       n2.notification_id AS last_notification_id
FROM bounds b
JOIN government_services.notifications n1
  ON n1.citizen_id = b.citizen_id
 AND n1.sent_at = b.first_sent
JOIN government_services.notifications n2
  ON n2.citizen_id = b.citizen_id
 AND n2.sent_at = b.last_sent;

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.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Show me the top 5 most recently minted NFTs on the Ethereum blockchain with their contract_address, token_id, name, and rarity_score from nft_metadata.

[Assistant]
SELECT contract_address, token_id, name, rarity_score
FROM nft_metadata
WHERE blockchain = 'Ethereum'
ORDER BY mint_block_number DESC
LIMIT 5;

[User] Also include the collection name, floor_price, and token_count from nft_collections for each NFT's collection.

[Assistant]
SELECT m.contract_address AS nft_contract,
       m.token_id,
       m.name,
       m.rarity_score,
       c.name       AS collection_name,
       c.floor_price,
       c.token_count
FROM nft_metadata m
JOIN nft_collections c
  ON m.blockchain = c.blockchain
 AND m.contract_address = c.contract_address
WHERE m.blockchain = 'Ethereum'
ORDER BY m.mint_block_number 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 erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE nft_holder_historical (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- The quantity held in the wallet
    pk integer NOT NULL  -- Partition key for the table(floor(block_number / 7200))
)
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer 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.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_balances (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar NOT NULL, -- Token tick
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Provide a list of all vehicles and the total quantity of fuel refueled for each vehicle.

[Assistant] SELECT T1.license_plate, sum(T2.quantity) FROM transportation.vehicles AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id = T2.vehicle_id GROUP BY T1.license_plate

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, 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 int, 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 )


[User] Summarize the accounts table by account type and currency, showing the average balance for each combination.

[Assistant] SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency ORDER BY account_type, currency;

[User] Only include combinations where the average balance is greater than 5000.

[Assistant] SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency HAVING AVG(balance) > 5000 ORDER BY average_balance 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 financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)


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

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

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

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

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

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

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

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

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


[User] List the first and last names of employees and the number of services offered by their agency.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Include only employees whose agency offers more than 3 services.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(s.service_id) > 3;

[User] Add the agency name to the result.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_id) > 3;

[User] Now, only show services that are currently active in the count.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_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 government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    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, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] What are the specific tools or equipment used during the maintenance with record_id 'REC456'?

[Assistant] I'm sorry, but I can't provide information about the specific tools or equipment used during a maintenance record. The data in the maintenance_records table does not include details about tools or equipment used.

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 PRIMARY KEY, 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] List the first name, last name, and hire date of all lawyers who are partners.

[Assistant] SELECT first_name ,  last_name ,  hire_date FROM legal_services.lawyers WHERE is_partner  =  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 legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)


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

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

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


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

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

[User] Can you also include the mechanic name and filter to only show services that cost more than $100?

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

[User] Now order these results by service date with the most recent first and limit to 10 records.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)


[User] What is the reason behind the cost variation for maintenance of asset_id 'ASSET456' over the past year?

[Assistant] I'm sorry, but I can't provide information on the reasons behind cost variations for maintenance. The data in the maintenance_records table includes only the cost amount and other basic details of each maintenance record, but it does not contain explanations or factors influencing cost changes.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, asset_type character varying(32) NOT NULL, maintenance_type character varying(128) NOT NULL, staff_id character varying(64), start_datetime timestamp NOT NULL, end_datetime timestamp, description text NOT NULL, cost numeric(12, 2), status character varying(32) NOT NULL DEFAULT 'Completed', PRIMARY KEY (record_id), FOREIGN KEY (staff_id) REFERENCES train_station_management.staff(staff_id) )


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

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

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

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

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


[User] How many addresses on the Ethereum chain have an ROI between 2 and 4?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

[User] Could you also show their average profit?

[Assistant] SELECT AVG(profit) AS avg_profit FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

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 text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )


[User] Show me the usernames along with the names of group chats they are participating in and the dates they joined each group.

[Assistant]
SELECT u.username, c.group_name, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE;

[User] Only display records where the user joined after January 1, 2024.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )


[User] Show all premium payments made via 'bank transfer' along with the policy_id and customer_id.

[Assistant] SELECT payment_id, policy_id, customer_id, amount_paid, payment_date FROM insurance.premium_payments WHERE payment_method = 'bank transfer';

[User] Can you include the full name and email of each customer making those payments?

[Assistant]
SELECT pp.payment_id, pp.policy_id, pp.customer_id, pp.amount_paid, pp.payment_date, c.first_name || ' ' || c.last_name AS full_name, c.email
FROM insurance.premium_payments pp
JOIN insurance.customers c ON pp.customer_id = c.customer_id
WHERE pp.payment_method = 'bank transfer';

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 text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Find all medical records where the vitals JSON field contains a blood pressure reading with systolic higher than 140, and show the patient_id, record_date, and vitals.

[Assistant] SELECT patient_id, record_date, vitals FROM healthcare.medical_records WHERE (vitals->>'blood_pressure_systolic')::integer > 140;

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


[User] Get the usernames of users who have created any public posts, and count how many public posts each user has made. Order the results by the post count in descending order.

[Assistant] SELECT u.username, COUNT(p.post_id) AS public_post_count FROM social_media.users u JOIN posts p ON u.user_id = p.user_id WHERE p.visibility = 'public' GROUP BY u.username ORDER BY public_post_count DESC;

[User] Actually, only include users who have posted more than 5 public posts.

[Assistant] SELECT u.username, COUNT(p.post_id) AS public_post_count FROM social_media.users u JOIN posts p ON u.user_id = p.user_id WHERE p.visibility = 'public' GROUP BY u.username HAVING COUNT(p.post_id) > 5 ORDER BY public_post_count DESC;

[User] Limit the result to the top 10 users by public post count.

[Assistant] SELECT u.username, COUNT(p.post_id) AS public_post_count FROM social_media.users u JOIN posts p ON u.user_id = p.user_id WHERE p.visibility = 'public' GROUP BY u.username HAVING COUNT(p.post_id) > 5 ORDER BY public_post_count DESC LIMIT 10;

[User] Can you also include their email address?

[Assistant] SELECT u.username, u.email, COUNT(p.post_id) AS public_post_count FROM social_media.users u JOIN posts p ON u.user_id = p.user_id WHERE p.visibility = 'public' GROUP BY u.username, u.email HAVING COUNT(p.post_id) > 5 ORDER BY public_post_count 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 social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)


[User] List all users who have never followed anyone, showing their username, full name, email, and account creation date.

[Assistant]
SELECT u.username,
       u.full_name,
       u.email,
       u.created_at
FROM social_media.users AS u
LEFT JOIN social_media.follows AS f
  ON u.user_id = f.follower_user_id
WHERE f.follow_id IS 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 social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


[User] I want to see pairs of items from the same game that share the same rarity but are of different types. Show each pair's names and types.

[Assistant]
SELECT a.game_id,
       a.item_name AS item1_name,
       a.item_type AS item1_type,
       b.item_name AS item2_name,
       b.item_type AS item2_type
FROM gaming_technology.in_game_items a
JOIN gaming_technology.in_game_items b
  ON a.game_id = b.game_id
 AND a.rarity = b.rarity
 AND a.item_type <> b.item_type
 AND a.item_id < b.item_id;

[User] Also include cost_currency and cost_amount for each item in the output.

[Assistant]
SELECT a.game_id,
       a.item_name AS item1_name,
       a.item_type AS item1_type,
       a.cost_currency AS item1_currency,
       a.cost_amount   AS item1_cost,
       b.item_name AS item2_name,
       b.item_type AS item2_type,
       b.cost_currency AS item2_currency,
       b.cost_amount   AS item2_cost
FROM gaming_technology.in_game_items a
JOIN gaming_technology.in_game_items b
  ON a.game_id = b.game_id
 AND a.rarity = b.rarity
 AND a.item_type <> b.item_type
 AND a.item_id < b.item_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.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 time entries from the last 90 days, including the entry description, hours spent, the name of the case, and the name of the client.

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

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


[User] For each city and state, show the number of service locations available along with their accessibility status.

[Assistant] SELECT city, state, is_accessible, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY city, state, is_accessible;

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.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] List all active SUI coins with status 'exists' in metadata, showing coin_type, symbol, name, balance, and description.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists';

[User] Limit to coins where balance > 1000000 and order by balance descending.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
ORDER BY CAST(sc.balance AS numeric) DESC;

[User] Also include the number of distinct owners per coin_type.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance DESC;

[User] Only show the top 3 coins by total_balance.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance 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 erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


[User] Show a list of all DApps together with the total number of unique assets linked to each via the metadata table.

[Assistant]
SELECT d.dapp_id, d.name, d.url, COUNT(DISTINCT m.asset_id) AS unique_asset_count
FROM trading_platform.dapps d
LEFT JOIN trading_platform.metadata m ON m.asset_id IS NOT NULL
GROUP BY d.dapp_id, d.name, d.url;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )


[User] Show me all documents along with the document name and type, together with both the upload_timestamp and the lawyer ID who uploaded them.

[Assistant] SELECT document_id, document_name, document_type, upload_timestamp, uploaded_by_lawyer_id FROM legal_services.documents;

[User] Can you filter the list to only include documents uploaded after March 1st, 2024?

[Assistant] SELECT document_id, document_name, document_type, upload_timestamp, uploaded_by_lawyer_id FROM legal_services.documents WHERE upload_timestamp > '2024-03-01';

[User] Additionally, show only those documents where the document_type contains the word 'Report'.

[Assistant] SELECT document_id, document_name, document_type, upload_timestamp, uploaded_by_lawyer_id FROM legal_services.documents WHERE upload_timestamp > '2024-03-01' AND document_type ILIKE '%Report%';

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 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 )


[User] List all lawyers who have never had a time entry that was billed, showing lawyer_id, first_name, and last_name.

[Assistant]
SELECT l.lawyer_id, l.first_name, l.last_name
FROM legal_services.lawyers l
LEFT JOIN legal_services.time_entries te
  ON l.lawyer_id = te.lawyer_id
 AND te.is_billed = true
WHERE te.entry_id IS NULL;

[User] Actually, I only want lawyers who have at least one time entry overall but none of those entries are billed.

[Assistant]
SELECT l.lawyer_id, l.first_name, l.last_name
FROM legal_services.lawyers l
JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id
GROUP BY l.lawyer_id, l.first_name, l.last_name
HAVING COUNT(te.entry_id) > 0
   AND SUM(CASE WHEN te.is_billed = true THEN 1 ELSE 0 END) = 0;

[User] Now also include the count of unbilled entries and total unbilled hours for each lawyer.

[Assistant]
SELECT l.lawyer_id,
       l.first_name,
       l.last_name,
       COUNT(te.entry_id) FILTER (WHERE te.is_billed = false) AS unbilled_entries,
       SUM(te.hours_spent) FILTER (WHERE te.is_billed = false) AS total_unbilled_hours
FROM legal_services.lawyers l
JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id
GROUP BY l.lawyer_id, l.first_name, l.last_name
HAVING COUNT(te.entry_id) > 0
   AND SUM(CASE WHEN te.is_billed = true THEN 1 ELSE 0 END) = 0;

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, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
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] Provide a count of servers per game status.

[Assistant] SELECT status, COUNT(*) AS server_count FROM gaming_technology.servers GROUP BY status;

[User] Filter the list to only show statuses that have more than 2 servers.

[Assistant] SELECT status, COUNT(*) AS server_count FROM gaming_technology.servers GROUP BY status 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 gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, 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.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
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 )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )


[User] For all NFT collections on the Ethereum blockchain, show me the collection name and the current floor price. Sort by floor price descending.

[Assistant] SELECT name, floor_price FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Include also the collection symbol and the number of tokens in each collection.

[Assistant] SELECT name, symbol, floor_price, token_count FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Can you also show the owner of each collection in the result?

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Now only include collections whose floor price is greater than 1 ETH.

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' AND CAST(floor_price AS FLOAT) > 1 AND floor_price_symbol = 'ETH' ORDER BY CAST(floor_price AS FLOAT) DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_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 ( 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 nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer 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_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_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_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] Give me the total billed amount for each invoice in 2024.

[Assistant] SELECT invoice_id, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND EXTRACT(YEAR FROM date_worked) = 2024 GROUP BY invoice_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 legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )


[User] Show the full names and contact emails of all citizens who have applied for services with a standard fee greater than 100.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.services s ON c.citizen_id IS NOT NULL -- Replace with actual application linking table if exists
WHERE s.standard_fee > 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )


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

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

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

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

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

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

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

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

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


[User] List all user IDs and the number of posts each has made where the post includes a media file (media_url is not null), along with whether their profile is private.

[Assistant]
SELECT p.user_id, COUNT(*) AS media_post_count, us.private_profile
FROM social_media.posts p
JOIN social_media.user_settings us ON p.user_id = us.user_id
WHERE p.media_url IS NOT NULL
GROUP BY p.user_id, us.private_profile;

[User] Show only users with at least 3 such posts and order by media_post_count descending.

[Assistant]
SELECT p.user_id, COUNT(*) AS media_post_count, us.private_profile
FROM social_media.posts p
JOIN social_media.user_settings us ON p.user_id = us.user_id
WHERE p.media_url IS NOT NULL
GROUP BY p.user_id, us.private_profile
HAVING COUNT(*) >= 3
ORDER BY media_post_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 social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] Show me the username and email of all users who own at least one wallet.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id = T2.user_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )
CREATE TABLE blockchain.users ( user_id.text, username.text, email.text, password_hash.text )


[User] For each doctor, count how many diagnoses they have recorded in total. Display doctor ID and the total count.

[Assistant] SELECT doctor_id, COUNT(*) AS total_diagnoses FROM healthcare.diagnoses GROUP BY doctor_id;

[User] Modify the query to also show the number of unique patients they have diagnosed, and filter the results to only include doctors who have diagnosed more than 10 distinct patients.

[Assistant] SELECT doctor_id, COUNT(*) AS total_diagnoses, COUNT(DISTINCT patient_id) AS unique_patients FROM healthcare.diagnoses GROUP BY doctor_id HAVING COUNT(DISTINCT patient_id) > 10;

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


[User] Show me a list of comments and the names of hashtags associated with the posts those comments are on.

[Assistant] SELECT T1.comment_id, T3.tag_name FROM comments AS T1 JOIN post_hashtags AS T2 ON T1.post_id = T2.post_id JOIN hashtags AS T3 ON T2.hashtag_id = T3.hashtag_id;

[User] Can you also include the content of the comment and filter the results to only show comments on posts tagged with 'photography'?

[Assistant] SELECT T1.comment_id, T1.content, T3.tag_name FROM comments AS T1 JOIN post_hashtags AS T2 ON T1.post_id = T2.post_id JOIN hashtags AS T3 ON T2.hashtag_id = T3.hashtag_id WHERE T3.tag_name = 'photography';

[User] Please only list comments that are top-level, meaning they are not replies to other comments.

[Assistant] SELECT T1.comment_id, T1.content, T3.tag_name FROM comments AS T1 JOIN post_hashtags AS T2 ON T1.post_id = T2.post_id JOIN hashtags AS T3 ON T2.hashtag_id = T3.hashtag_id WHERE T3.tag_name = 'photography' AND T1.parent_comment_id IS 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 social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )


[User] List all log entries associated with users who have participated in any trade, showing the log details and the trade ID.

[Assistant] SELECT T1.log_id, T1.action, T1.details, T1.logged_at, T2.trade_id, T2.buyer_id, T2.seller_id FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id;

[User] Only show logs and trades that occurred in the last week.

[Assistant] SELECT T1.log_id, T1.action, T1.details, T1.logged_at, T2.trade_id, T2.buyer_id, T2.seller_id FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id WHERE T1.logged_at >= datetime('now', '-7 days') AND T2.traded_at >= datetime('now', '-7 days');

[User] Can you instead provide a count of such log entries per user who traded, for the last week?

[Assistant] SELECT T1.user_id, COUNT(DISTINCT T1.log_id) AS log_count FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id WHERE T1.logged_at >= datetime('now', '-7 days') AND T2.traded_at >= datetime('now', '-7 days') GROUP BY T1.user_id;

[User] Also include the total number of trades for each user in the same period and sort by trade count descending.

[Assistant] SELECT T1.user_id, COUNT(DISTINCT T1.log_id) AS log_count, COUNT(DISTINCT T2.trade_id) AS trade_count FROM logs AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id WHERE T1.logged_at >= datetime('now', '-7 days') AND T2.traded_at >= datetime('now', '-7 days') GROUP BY T1.user_id ORDER BY trade_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.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )


[User] Count the number of logs for each action type.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )


[User] For each patient, calculate the total duration of all their completed appointments. Show the patient ID and the total duration in minutes, sorted by total duration descending.

[Assistant] SELECT patient_id, SUM(duration_minutes) AS total_completed_duration FROM healthcare.appointments WHERE status = 'Completed' GROUP BY patient_id ORDER BY total_completed_duration 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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)


[User] Show me all claims with police reports that were filed in the last 3 months, along with the policy details and customer information.

[Assistant] SELECT c.claim_id, c.policy_id, c.customer_id, c.incident_date, c.reported_date, c.description, c.estimated_loss, c.status, c.settlement_amount, c.settlement_date, c.police_report_number, p.product_id, p.product_name, p.product_type, b.first_name, b.last_name, b.relationship FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id JOIN insurance.policy_beneficiaries b ON c.customer_id = b.customer_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Now filter to only show claims where the estimated loss is above $10,000.

[Assistant] SELECT c.claim_id, c.policy_id, c.customer_id, c.incident_date, c.reported_date, c.description, c.estimated_loss, c.status, c.settlement_amount, c.settlement_date, c.police_report_number, p.product_id, p.product_name, p.product_type, b.first_name, b.last_name, b.relationship FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id JOIN insurance.policy_beneficiaries b ON c.customer_id = b.customer_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000;

[User] I also want to see the count of such claims per product type.

[Assistant] SELECT p.product_type, COUNT(c.claim_id) AS claim_count FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY p.product_type;

[User] Finally, show me the average estimated loss for these claims by product type.

[Assistant] SELECT p.product_type, AVG(c.estimated_loss) AS avg_estimated_loss FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY p.product_type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] For each trip that has bookings, show the trip ID and the total number of bookings associated with it.

[Assistant] SELECT T.trip_id, COUNT(B.booking_id) AS booking_count FROM transportation.trips AS T JOIN transportation.bookings AS B ON T.trip_id = B.trip_id GROUP BY T.trip_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


[User] Show me all policies that expired in the last 60 days, along with their product IDs and premium amounts.

[Assistant] SELECT policy_id, product_id, premium_amount FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE;

[User] Now include only policies that had a deductible of $1000 or more.

[Assistant] SELECT policy_id, product_id, premium_amount, deductible FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE AND deductible >= 1000;

[User] I also want to see the count of such expired policies per product ID.

[Assistant] SELECT product_id, COUNT(*) as policy_count FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE AND deductible >= 1000 GROUP BY product_id ORDER BY policy_count DESC;

[User] Finally, show me the average premium amount for these expired high-deductible policies grouped by product ID.

[Assistant] SELECT product_id, AVG(premium_amount) as avg_premium FROM insurance.policies WHERE status = 'expired' AND end_date >= CURRENT_DATE - INTERVAL '60 days' AND end_date <= CURRENT_DATE AND deductible >= 1000 GROUP BY product_id ORDER BY avg_premium DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )


[User] Count the total number of comments each user has made.

[Assistant] SELECT user_id, COUNT(*) AS comment_count FROM comments GROUP BY user_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )


[User] Show me the earliest created smart contract for each creator address.

[Assistant] SELECT sc1.contract_id, sc1.creator_address, sc1.timestamp FROM blockchain.smart_contracts sc1 WHERE sc1.timestamp = (SELECT MIN(sc2.timestamp) FROM blockchain.smart_contracts sc2 WHERE sc2.creator_address = sc1.creator_address);

[User] Now include the total number of contracts each creator has made alongside this information.

[Assistant] SELECT sc1.contract_id, sc1.creator_address, sc1.timestamp, (SELECT COUNT(*) FROM blockchain.smart_contracts sc2 WHERE sc2.creator_address = sc1.creator_address) AS total_contracts FROM blockchain.smart_contracts sc1 WHERE sc1.timestamp = (SELECT MIN(sc3.timestamp) FROM blockchain.smart_contracts sc3 WHERE sc3.creator_address = sc1.creator_address);

[User] Filter this to only show creators who have made at least 10 contracts.

[Assistant] SELECT sc1.contract_id, sc1.creator_address, sc1.timestamp, (SELECT COUNT(*) FROM blockchain.smart_contracts sc2 WHERE sc2.creator_address = sc1.creator_address) AS total_contracts FROM blockchain.smart_contracts sc1 WHERE sc1.timestamp = (SELECT MIN(sc3.timestamp) FROM blockchain.smart_contracts sc3 WHERE sc3.creator_address = sc1.creator_address) AND (SELECT COUNT(*) FROM blockchain.smart_contracts sc4 WHERE sc4.creator_address = sc1.creator_address) >= 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 blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )


[User] For each claim handler, count the number of documents uploaded for the claims they handled. Return claim_handler_id and document_count.

[Assistant]
SELECT c.claim_handler_id,
       COUNT(d.document_id) AS document_count
FROM insurance.claims AS c
JOIN insurance.claim_documents AS d
  ON c.claim_id = d.claim_id
GROUP BY c.claim_handler_id;

[User] Now restrict to handlers who have uploaded more than 10 documents.

[Assistant]
SELECT c.claim_handler_id,
       COUNT(d.document_id) AS document_count
FROM insurance.claims AS c
JOIN insurance.claim_documents AS d
  ON c.claim_id = d.claim_id
GROUP BY c.claim_handler_id
HAVING COUNT(d.document_id) > 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 insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
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) )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )


[User] List the names of employees and the names of the cities where their agency operates service locations.

[Assistant]
SELECT e.first_name, e.last_name, sl.city
FROM government_services.employees e
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id;

[User] Only show employees who work in locations that are accessible.

[Assistant]
SELECT e.first_name, e.last_name, sl.city
FROM government_services.employees e
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id
WHERE sl.is_accessible = true;

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