[User] Find guests who have made at least one payment using a 'CreditCard'. List their full name (first and last name) and email address.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T1.email FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.payments AS T2 ON T1.guest_id = T2.guest_id WHERE T2.payment_method = 'CreditCard';

[User] For these guests, also show the total amount they have paid using a 'CreditCard'.

[Assistant] SELECT T1.first_name, T1.last_name, T1.email, SUM(T2.amount) AS total_credit_card_amount FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.payments AS T2 ON T1.guest_id = T2.guest_id WHERE T2.payment_method = 'CreditCard' GROUP BY T1.guest_id, T1.first_name, T1.last_name, T1.email;

[User] Now, only include guests where the total credit card payment exceeds 5000.

[Assistant] SELECT T1.first_name, T1.last_name, T1.email, SUM(T2.amount) AS total_credit_card_amount FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.payments AS T2 ON T1.guest_id = T2.guest_id WHERE T2.payment_method = 'CreditCard' GROUP BY T1.guest_id, T1.first_name, T1.last_name, T1.email HAVING SUM(T2.amount) > 5000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests (
    guest_id character varying(64) NOT NULL,  -- unique identifier for the guest profile
    first_name character varying(100) NOT NULL, -- guest's first name
    last_name character varying(100) NOT NULL, -- guest's last name
    email character varying(255) UNIQUE, -- guest's email address (unique identifier?)
    phone_number character varying(30), -- guest's phone number
    date_of_birth date, -- guest's date of birth
    address_line1 character varying(255), -- guest's home address
    city character varying(100),
    state_province character varying(100),
    postal_code character varying(20),
    country_code character varying(3),
    preferences text, -- notes on guest preferences (e.g., allergies, room location)
    loyalty_member_id character varying(64) UNIQUE, -- FK to loyalty_members table
    communication_consent boolean DEFAULT true, -- consent for marketing communications
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (guest_id)
)
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)


[User] List all customers who reside in New York and were created in the system before 2023.

[Assistant] SELECT customer_id, first_name, last_name, created_at FROM insurance.customers WHERE state = 'NY' AND created_at < '2023-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 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 )


[User] Show me each guest's full name and the number of unique properties they have made reservations for.

[Assistant]
SELECT g.first_name || ' ' || g.last_name AS full_name,
       COUNT(DISTINCT r.property_id) AS property_count
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r
  ON g.guest_id = r.guest_id
GROUP BY full_name;

[User] Only include guests who have booked at least 2 different properties.

[Assistant]
SELECT g.first_name || ' ' || g.last_name AS full_name,
       COUNT(DISTINCT r.property_id) AS property_count
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r
  ON g.guest_id = r.guest_id
GROUP BY full_name
HAVING COUNT(DISTINCT r.property_id) >= 2;

[User] Also calculate their average total_amount per reservation and sort by that average in descending order.

[Assistant]
SELECT g.first_name || ' ' || g.last_name AS full_name,
       COUNT(DISTINCT r.property_id) AS property_count,
       AVG(r.total_amount)       AS avg_total_per_reservation
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r
  ON g.guest_id = r.guest_id
GROUP BY full_name
HAVING COUNT(DISTINCT r.property_id) >= 2
ORDER BY avg_total_per_reservation DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.payments ( payment_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, bill_id character varying(64), amount numeric(12,2) NOT NULL, currency_code character varying(3) NOT NULL, payment_method character varying(50) NOT NULL, card_type character varying(50), card_last_four character varying(4), transaction_ref character varying(128), payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, status character varying(50) NOT NULL, staff_id_processed character varying(64), notes text, PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) )
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] For each user, show their user_id, KYC status, and the total count of completed orders they've placed.

[Assistant]
SELECT k.user_id, k.status, COUNT(o.order_id) AS completed_order_count
FROM trading_platform.kyc_audit k
JOIN trading_platform.orders o
  ON k.user_id = o.user_id
  AND o.status = 'completed'
GROUP BY k.user_id, k.status;

[User] Only include users whose KYC status is 'approved'.

[Assistant]
SELECT k.user_id, k.status, COUNT(o.order_id) AS completed_order_count
FROM trading_platform.kyc_audit k
JOIN trading_platform.orders o
  ON k.user_id = o.user_id
  AND o.status = 'completed'
WHERE k.status = 'approved'
GROUP BY k.user_id, k.status;

[User] Also calculate the total value of these completed orders as total_value.

[Assistant]
SELECT k.user_id,
       k.status,
       COUNT(o.order_id) AS completed_order_count,
       SUM(o.quantity * o.price) AS total_value
FROM trading_platform.kyc_audit k
JOIN trading_platform.orders o
  ON k.user_id = o.user_id
  AND o.status = 'completed'
WHERE k.status = 'approved'
GROUP BY k.user_id, k.status;

[User] Finally, order the results by total_value descending and limit to 5.

[Assistant]
SELECT k.user_id,
       k.status,
       COUNT(o.order_id) AS completed_order_count,
       SUM(o.quantity * o.price) AS total_value
FROM trading_platform.kyc_audit k
JOIN trading_platform.orders o
  ON k.user_id = o.user_id
  AND o.status = 'completed'
WHERE k.status = 'approved'
GROUP BY k.user_id, k.status
ORDER BY total_value 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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] List all active SUI coins with their symbol, name, and total balance across all owners.

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

[User] Filter coins with description containing 'staking' and sort by total_balance descending.

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

[User] Limit the result to the top 3 coins.

[Assistant]
SELECT sub.coin_type, sub.symbol, sub.name, sub.total_balance
FROM (
  SELECT scm.coin_type, scm.symbol, scm.name, SUM(CAST(sc.balance AS DECIMAL)) AS total_balance
  FROM sui_coins_metadata scm
  JOIN sui_coins sc ON sc.coin_type = scm.coin_type
  WHERE sc.status = 'active' AND scm.status = 'exists' AND LOWER(scm.description) LIKE '%staking%'
  GROUP BY scm.coin_type, scm.symbol, scm.name
) sub
ORDER BY sub.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 token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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 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 erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_balances (
    block_number bigint 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_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block 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_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche (
    block_number bigint 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] Show me all pairs of cases led by the same lawyer, including both case names and the lead lawyer ID.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_id < c2.case_id;

[User] Actually, only include pairs where the case types are also the same.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_id;

[User] Also, show me the earliest opening date between the two cases for each pair.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2,
       LEAST(c1.date_opened, c2.date_opened) AS earliest_open_date
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_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.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )


[User] Get the number of documents for each case, showing case_id and document count, ordered by count descending.

[Assistant]
SELECT case_id,
       COUNT(*) AS document_count
FROM legal_services.documents
GROUP BY case_id
ORDER BY document_count DESC;

[User] Actually, only count documents of type 'Evidence'.

[Assistant]
SELECT case_id,
       COUNT(*) AS evidence_count
FROM legal_services.documents
WHERE document_type = 'Evidence'
GROUP BY case_id
ORDER BY evidence_count DESC;

[User] Also, include the case_name from the cases table.

[Assistant]
SELECT d.case_id,
       c.case_name,
       COUNT(*) AS evidence_count
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
WHERE d.document_type = 'Evidence'
GROUP BY d.case_id, c.case_name
ORDER BY evidence_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 legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.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.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )


[User] List the employee's first and last name along with the appointment ID and scheduled start time for all appointments associated with the citizen who has the national ID number 'A123456789'.

[Assistant]
SELECT e.first_name, e.last_name, a.appointment_id, a.scheduled_start_time
FROM government_services.appointments a
JOIN government_services.employees e ON a.employee_id = e.employee_id
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
WHERE c.national_id_number = 'A123456789';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
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.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] List all rooms, including their room number, the name of the property they belong to, and their room type name, specifically for rooms with 'Maintenance' status.

[Assistant] SELECT T1.room_number, T2.property_name, T3.type_name FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance'

[User] Also include the floor number and filter to only show rooms located on floors 5 or higher. Sort the results by property name and then by floor.

[Assistant] SELECT T1.room_number, T2.property_name, T3.type_name, T1.floor FROM rooms AS T1 JOIN properties AS T2 ON T1.property_id = T2.property_id JOIN room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.status = 'Maintenance' AND T1.floor >= 5 ORDER BY T2.property_name, T1.floor

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.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)


[User] List the service_id, service_name, and agency_id for all active services that have an online application URL provided.

[Assistant]
SELECT service_id,
       service_name,
       agency_id
FROM government_services.services
WHERE is_active = TRUE
  AND online_application_url IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Show the number of reservations and the sum total_amount for each property.

[Assistant]
SELECT p.property_id, p.property_name, COUNT(r.reservation_id) AS reservation_count, SUM(r.total_amount) AS total_revenue
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.reservations r ON p.property_id = r.property_id
GROUP BY p.property_id, p.property_name;

[User] Return only those properties with at least 50 reservations.

[Assistant]
SELECT p.property_id, p.property_name, COUNT(r.reservation_id) AS reservation_count, SUM(r.total_amount) AS total_revenue
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.reservations r ON p.property_id = r.property_id
GROUP BY p.property_id, p.property_name
HAVING COUNT(r.reservation_id) >= 50;

[User] Additionally, only include properties in cities that start with the letter 'S' and order by total revenue descending.

[Assistant]
SELECT p.property_id, p.property_name, COUNT(r.reservation_id) AS reservation_count, SUM(r.total_amount) AS total_revenue
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.reservations r ON p.property_id = r.property_id
WHERE p.city LIKE 'S%'
GROUP BY p.property_id, p.property_name
HAVING COUNT(r.reservation_id) >= 50
ORDER BY total_revenue DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )


[User] For each user, show the most recently created wallet address and the wallet creation timestamp.

[Assistant]
SELECT w1.user_id, w1.address, w1.created_at
FROM web3.wallets w1
JOIN (
  SELECT user_id, MAX(created_at) AS max_created_at
  FROM web3.wallets
  GROUP BY user_id
) w2 ON w1.user_id = w2.user_id AND w1.created_at = w2.max_created_at;

[User] Can you also include the wallet_id of the most recent wallet for each user in the result?

[Assistant]
SELECT w1.user_id, w1.wallet_id, w1.address, w1.created_at
FROM web3.wallets w1
JOIN (
  SELECT user_id, MAX(created_at) AS max_created_at
  FROM web3.wallets
  GROUP BY user_id
) w2 ON w1.user_id = w2.user_id AND w1.created_at = w2.max_created_at;

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


[User] Which service locations do not have a contact phone specified? Show the location_id and location_name.

[Assistant]
SELECT location_id, location_name
FROM government_services.service_locations
WHERE contact_phone IS NULL OR contact_phone = '';

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.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )


[User] What is the average ROI for smart money addresses on the Ethereum chain with a realized ratio above 70%?

[Assistant] SELECT AVG(roi) FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )


[User] List NFT collections deployed after block number 10000000 with more than 500 tokens, showing contract_address, name, and token_count.

[Assistant]
SELECT contract_address, name, token_count
FROM nft_collections
WHERE deploy_block_number > 10000000
  AND token_count > 500;

[User] Join with nft_metadata to calculate the average rarity_score per collection.

[Assistant]
SELECT nc.contract_address,
       nc.name,
       nc.token_count,
       AVG(nm.rarity_score) AS avg_rarity
FROM nft_collections nc
LEFT JOIN nft_metadata nm
  ON nc.contract_address = nm.contract_address
WHERE nc.deploy_block_number > 10000000
  AND nc.token_count > 500
GROUP BY nc.contract_address, nc.name, nc.token_count;

[User] Filter collections with average rarity_score above 80 and include floor_price.

[Assistant]
SELECT nc.contract_address,
       nc.name,
       nc.token_count,
       AVG(nm.rarity_score) AS avg_rarity,
       nc.floor_price
FROM nft_collections nc
LEFT JOIN nft_metadata nm
  ON nc.contract_address = nm.contract_address
WHERE nc.deploy_block_number > 10000000
  AND nc.token_count > 500
GROUP BY nc.contract_address, nc.name, nc.token_count, nc.floor_price
HAVING AVG(nm.rarity_score) > 80;

[User] Order the results by floor_price descending and limit to the top 5 collections.

[Assistant]
SELECT nc.contract_address,
       nc.name,
       nc.token_count,
       AVG(nm.rarity_score) AS avg_rarity,
       nc.floor_price
FROM nft_collections nc
LEFT JOIN nft_metadata nm
  ON nc.contract_address = nm.contract_address
WHERE nc.deploy_block_number > 10000000
  AND nc.token_count > 500
GROUP BY nc.contract_address, nc.name, nc.token_count, nc.floor_price
HAVING AVG(nm.rarity_score) > 80
ORDER BY CAST(nc.floor_price AS numeric) DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE mud_holesky_redstone ( address.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_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] List all doctors who were created in the year 2022. Show their doctor ID, first name, and last name.

[Assistant] SELECT doctor_id, first_name, last_name FROM healthcare.doctors WHERE EXTRACT(YEAR FROM created_at) = 2022

[User] From that list, only show doctors whose specialty is 'Neurology'.

[Assistant] SELECT doctor_id, first_name, last_name FROM healthcare.doctors WHERE EXTRACT(YEAR FROM created_at) = 2022 AND specialty = 'Neurology'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )


[User] I need to find all pairs of medications that share the same manufacturer. For each pair, show the first medication's ID and name, the second medication's ID and name, and the manufacturer.

[Assistant]
SELECT m1.medication_id AS med1_id,
       m1.medication_name AS med1_name,
       m2.medication_id AS med2_id,
       m2.medication_name AS med2_name,
       m1.manufacturer
FROM healthcare.medications m1
JOIN healthcare.medications m2
  ON m1.manufacturer = m2.manufacturer
 AND m1.medication_id < m2.medication_id;

[User] Actually, only include pairs where the two medications have different generic_name values.

[Assistant]
SELECT m1.medication_id AS med1_id,
       m1.medication_name AS med1_name,
       m2.medication_id AS med2_id,
       m2.medication_name AS med2_name,
       m1.manufacturer
FROM healthcare.medications m1
JOIN healthcare.medications m2
  ON m1.manufacturer = m2.manufacturer
 AND m1.medication_id < m2.medication_id
WHERE m1.generic_name <> m2.generic_name;

[User] Also, exclude any pairs where the manufacturer field is NULL for either medication.

[Assistant]
SELECT m1.medication_id AS med1_id,
       m1.medication_name AS med1_name,
       m2.medication_id AS med2_id,
       m2.medication_name AS med2_name,
       m1.manufacturer
FROM healthcare.medications m1
JOIN healthcare.medications m2
  ON m1.manufacturer = m2.manufacturer
 AND m1.medication_id < m2.medication_id
WHERE m1.generic_name <> m2.generic_name
  AND m1.manufacturer IS NOT NULL
  AND m2.manufacturer IS NOT NULL;

[User] Finally, limit the result to manufacturers that have at least three medications in the table.

[Assistant]
SELECT m1.medication_id AS med1_id,
       m1.medication_name AS med1_name,
       m2.medication_id AS med2_id,
       m2.medication_name AS med2_name,
       m1.manufacturer
FROM healthcare.medications m1
JOIN healthcare.medications m2
  ON m1.manufacturer = m2.manufacturer
 AND m1.medication_id < m2.medication_id
WHERE m1.generic_name <> m2.generic_name
  AND m1.manufacturer IS NOT NULL
  AND m2.manufacturer IS NOT NULL
  AND m1.manufacturer IN (
      SELECT manufacturer
      FROM healthcare.medications
      WHERE manufacturer IS NOT NULL
      GROUP BY manufacturer
      HAVING COUNT(*) >= 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 healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )


[User] List all insurance plans along with their provider, plan type, and the contact phone number. Also, for each plan, show how many doctors have their hospital affiliation ID matching the plan ID.

[Assistant] SELECT ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone, COUNT(d.doctor_id) FROM healthcare.insurance_plans ip LEFT JOIN healthcare.doctors d ON ip.plan_id = d.hospital_affiliation_id GROUP BY ip.plan_id, ip.plan_name, ip.insurance_provider, ip.plan_type, ip.contact_phone

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.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )


[User] List all guests who have a loyalty member ID, showing their full name (first and last name), email, and loyalty ID.

[Assistant] SELECT first_name, last_name, email, loyalty_member_id FROM hospitality_technology.guests WHERE loyalty_member_id IS NOT NULL;

[User] Can you also include the date they registered as a guest?

[Assistant] SELECT first_name, last_name, email, loyalty_member_id, created_at FROM hospitality_technology.guests WHERE loyalty_member_id IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)


[User] List the name of each agency and the total number of service locations it operates in New York State.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS location_count
FROM government_services.agencies a
LEFT JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.state = 'NY'
GROUP BY a.agency_name;

[User] Actually, only include those service locations that are accessible.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS location_count
FROM government_services.agencies a
LEFT JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.state = 'NY' AND sl.is_accessible = TRUE
GROUP BY a.agency_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, 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 )
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 count of notifications sent for each channel for applications submitted after January 1, 2024.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at > '2024-01-01'
GROUP BY n.channel;

[User] Now, only include channels that have sent more than 10 notifications.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at > '2024-01-01'
GROUP BY n.channel
HAVING COUNT(*) > 10;

[User] Exclude notifications with the status 'Failed'.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at > '2024-01-01' AND n.status != 'Failed'
GROUP BY n.channel
HAVING COUNT(*) > 10;

[User] Show for 2023 instead of 2024.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at >= '2023-01-01' AND a.submitted_at < '2024-01-01' AND n.status != 'Failed'
GROUP BY n.channel
HAVING COUNT(*) > 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 government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.notifications ( notification_id text, 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] What is the fuel efficiency of the train car with car_id 'TC456'?

[Assistant] I'm sorry, but I don't have access to information about the fuel efficiency of specific train cars. The data available in the train_cars table only includes details such as car_id, train_id, car_number, car_type, class, capacity, and features. If you have another question or need assistance with something else, I'm happy to help.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.train_cars ( car_id.text, train_id.text, car_number.text, car_type.text, class.text, capacity.integer, features.text )


[User] Find all nodes that were last seen in the last 30 days and have port numbers between 8000 and 9000.

[Assistant] SELECT node_id, ip_address, port FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '30 days' AND port BETWEEN 8000 AND 9000

[User] Can you also show the count of transactions sent from wallet addresses that share the same IP as these nodes?

[Assistant] This query isn't possible with the current schema as there's no relationship between nodes IP addresses and wallet addresses.

[User] Then just show me nodes that share the same IP address along with how many nodes share each IP.

[Assistant] SELECT ip_address, COUNT(*) as node_count FROM blockchain.nodes GROUP BY ip_address HAVING COUNT(*) > 1

[User] Now filter this to only show IP addresses with more than 3 nodes and include the earliest and latest last_seen timestamps.

[Assistant] SELECT ip_address, COUNT(*) as node_count, MIN(last_seen) as earliest_seen, MAX(last_seen) as latest_seen FROM blockchain.nodes GROUP BY ip_address HAVING COUNT(*) > 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 blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.nodes ( node_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )
CREATE TABLE blockchain.smart_contracts ( contract_id text, creator_address text, code text, timestamp timestamp )


[User] Show me all terminated drivers who had worked for the company for more than 5 years before termination.

[Assistant] SELECT driver_id, first_name, last_name, hire_date FROM transportation.drivers WHERE status = 'Terminated' AND (hire_date < (CURRENT_DATE - INTERVAL '5 years'));

[User] Can you include their license numbers and calculate how many years they worked before termination?

[Assistant] SELECT driver_id, first_name, last_name, license_number, hire_date, EXTRACT(YEAR FROM AGE(CURRENT_DATE, hire_date)) AS years_worked FROM transportation.drivers WHERE status = 'Terminated' AND (hire_date < (CURRENT_DATE - INTERVAL '5 years'));

[User] Now order the results by years worked in descending order, showing those who worked the longest first.

[Assistant] SELECT driver_id, first_name, last_name, license_number, hire_date, EXTRACT(YEAR FROM AGE(CURRENT_DATE, hire_date)) AS years_worked FROM transportation.drivers WHERE status = 'Terminated' AND (hire_date < (CURRENT_DATE - INTERVAL '5 years')) ORDER BY years_worked DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)


[User] What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

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

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


[User] List all users who have bought assets, along with their wallet addresses.

[Assistant] SELECT DISTINCT T1.user_id, T1.address FROM wallets AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id;

[User] Filter this list to include only trades made in the last 30 days.

[Assistant] SELECT DISTINCT T1.user_id, T1.address FROM wallets AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id WHERE T2.traded_at >= datetime('now', '-30 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 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] Show me all room types with a base rate over $200 and max occupancy of at least 4, along with their property IDs and amenities.

[Assistant] SELECT room_type_id, property_id, type_name, base_rate, max_occupancy, amenities FROM hospitality_technology.room_types WHERE base_rate > 200 AND max_occupancy >= 4;

[User] Now, join this with the guests table to show only room types from properties where the guest's country code is 'USA'.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.type_name, rt.base_rate, rt.max_occupancy, rt.amenities FROM hospitality_technology.room_types rt JOIN hospitality_technology.guests g ON rt.property_id = g.property_id WHERE rt.base_rate > 200 AND rt.max_occupancy >= 4 AND g.country_code = 'USA';

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.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )


[User] Count the number of unique locations specified in the users table.

[Assistant] SELECT count(DISTINCT location) FROM social_media.users WHERE location IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
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 PRIMARY KEY, 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.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )


[User] List pairs of maintenance logs for the same vehicle where the service date is the same, showing the log IDs and service types.

[Assistant] SELECT T1.log_id AS log_id_1, T1.service_type AS service_type_1, T2.log_id AS log_id_2, T2.service_type AS service_type_2, T1.vehicle_id, T1.service_date FROM transportation.maintenance_logs AS T1 JOIN transportation.maintenance_logs AS T2 ON T1.vehicle_id = T2.vehicle_id AND T1.service_date = T2.service_date AND T1.log_id < T2.log_id;

[User] Filter this list to only include pairs where at least one of the logs has a cost greater than 500.

[Assistant] SELECT T1.log_id AS log_id_1, T1.service_type AS service_type_1, T2.log_id AS log_id_2, T2.service_type AS service_type_2, T1.vehicle_id, T1.service_date FROM transportation.maintenance_logs AS T1 JOIN transportation.maintenance_logs AS T2 ON T1.vehicle_id = T2.vehicle_id AND T1.service_date = T2.service_date AND T1.log_id < T2.log_id WHERE T1.cost > 500 OR T2.cost > 500;

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


[User] For each service location, find its nearest accessible location by geographic distance.

[Assistant]
SELECT sl.location_id,
       sl.location_name,
       nearest.location_id   AS nearest_location_id,
       nearest.location_name AS nearest_location_name
FROM government_services.service_locations sl
JOIN LATERAL (
  SELECT sl2.location_id,
         sl2.location_name
  FROM government_services.service_locations sl2
  WHERE sl2.is_accessible = TRUE
    AND sl2.location_id <> sl.location_id
  ORDER BY ((sl.latitude - sl2.latitude)^2 + (sl.longitude - sl2.longitude)^2) ASC
  LIMIT 1
) AS nearest ON 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.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] Give me a breakdown of the number of reviews per day for the last 14 days, including the review_date and review count.

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] Show me the total traded volume and the average price per security for trades executed last month.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
GROUP BY s.ticker_symbol;

[User] Filter to only include those trades with status 'SETTLED' and execution_venue 'NYSE'.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
  AND t.status = 'SETTLED'
  AND t.execution_venue = 'NYSE'
GROUP BY s.ticker_symbol;

[User] Now exclude any securities where the summed quantity is less than 1000.

[Assistant]
SELECT s.ticker_symbol,
       SUM(t.quantity) AS total_volume,
       AVG(t.price_per_unit) AS avg_price
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
  AND t.trade_timestamp < date_trunc('month', CURRENT_DATE)
  AND t.status = 'SETTLED'
  AND t.execution_venue = 'NYSE'
GROUP BY s.ticker_symbol
HAVING SUM(t.quantity) >= 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.market_data ( data_point_id bigint, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )


[User] List all available services in the 'Housekeeping' department that cost less than 20.

[Assistant]
SELECT service_id, service_name, price
FROM hospitality_technology.services
WHERE department = 'Housekeeping' AND is_available = true AND price < 20;

[User] Sort the results by service_name in ascending order.

[Assistant]
SELECT service_id, service_name, price
FROM hospitality_technology.services
WHERE department = 'Housekeeping' AND is_available = true AND price < 20
ORDER BY service_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )


[User] Show all transactions over 10,000 USD that are not marked as 'REVERSED'.

[Assistant]
SELECT transaction_id, account_id, amount, currency, status, transaction_date
FROM financial_services.transactions
WHERE amount > 10000 AND currency = 'USD' AND status != 'REVERSED';

[User] Include the related_account_id and the transaction_type in the result, and order by amount descending.

[Assistant]
SELECT transaction_id, account_id, related_account_id, transaction_type, amount, currency, status, transaction_date
FROM financial_services.transactions
WHERE amount > 10000 AND currency = 'USD' AND status != 'REVERSED'
ORDER BY amount DESC;

[User] Add a filter to only include transactions that happened in the last 60 days.

[Assistant]
SELECT transaction_id, account_id, related_account_id, transaction_type, amount, currency, status, transaction_date
FROM financial_services.transactions
WHERE amount > 10000 AND currency = 'USD' AND status != 'REVERSED' AND transaction_date >= NOW() - INTERVAL '60 days'
ORDER BY amount 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.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] List payment records in USD including guest names and processing staff names.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD';

[User] Only include payments with status 'Succeeded' made within the last 30 days.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD'
  AND p.status = 'Succeeded'
  AND p.payment_timestamp >= NOW() - INTERVAL '30 days';

[User] Sort by payment timestamp descending and limit to 50 records.

[Assistant]
SELECT p.payment_id,
       p.amount,
       p.currency_code,
       g.guest_name,
       s.staff_name
FROM hospitality_technology.payments p
JOIN hospitality_technology.guests g ON p.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON p.staff_id_processed = s.staff_id
WHERE p.currency_code = 'USD'
  AND p.status = 'Succeeded'
  AND p.payment_timestamp >= NOW() - INTERVAL '30 days'
ORDER BY p.payment_timestamp DESC
LIMIT 50;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )