System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )

[User] What is the total session duration and total score across all sessions for each server status?

[Assistant]
SELECT
  s.status,
  SUM(gs.duration_seconds) AS total_duration_seconds,
  SUM(gs.score) AS total_score
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.status;

[User] Only include statuses that have a total session duration greater than 1000000 seconds and handle potential null scores by treating them as 0.

[Assistant]
SELECT
  s.status,
  SUM(gs.duration_seconds) AS total_duration_seconds,
  SUM(COALESCE(gs.score, 0)) AS total_score
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.status
HAVING
  SUM(gs.duration_seconds) > 1000000;

[User] Order the results by total session duration in descending order.

[Assistant]
SELECT
  s.status,
  SUM(gs.duration_seconds) AS total_duration_seconds,
  SUM(COALESCE(gs.score, 0)) AS total_score
FROM gaming_technology.game_sessions AS gs
JOIN gaming_technology.servers AS s
  ON gs.server_id = s.server_id
GROUP BY
  s.status
HAVING
  SUM(gs.duration_seconds) > 1000000
ORDER BY
  total_duration_seconds DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)

[User] Find all addresses that have both sent and received tokens. For each, show the address, the total value sent, and the total value received.

[Assistant]
SELECT s.address, s.total_sent, r.total_received
FROM (
  SELECT from_address AS address, SUM(value) AS total_sent
  FROM web3.token_transfers
  GROUP BY from_address
) s
JOIN (
  SELECT to_address   AS address, SUM(value) AS total_received
  FROM web3.token_transfers
  GROUP BY to_address
) r
  ON s.address = r.address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Show me the medication_id, medication_name, and manufacturer for all medications where the generic_name contains the word 'azole'.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name ILIKE '%azole%';

[User] Can you also include the ndc_code and only show medications where the manufacturer field is not null?

[Assistant] SELECT medication_id, medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE generic_name ILIKE '%azole%' AND manufacturer IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] I need a list showing the name of each law firm and the full name of every lawyer employed by that firm.

[Assistant] SELECT T1.firm_name, T2.first_name, T2.last_name FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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_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_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, 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_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 token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )

[User] For each NFT collection deployed on Ethereum, count the number of distinct wallets that have ever held any token from that collection.

[Assistant]
SELECT
  nc.contract_address,
  nc.name,
  COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM nft_collections nc
JOIN nft_holder_historical nh
  ON nc.contract_address = nh.contract_address
WHERE nc.blockchain = 'Ethereum'
GROUP BY nc.contract_address, nc.name;

[User] Include each collection's token_count and floor_price from nft_collections.

[Assistant]
SELECT
  nc.contract_address,
  nc.name,
  nc.token_count,
  nc.floor_price,
  COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM nft_collections nc
JOIN nft_holder_historical nh
  ON nc.contract_address = nh.contract_address
WHERE nc.blockchain = 'Ethereum'
GROUP BY
  nc.contract_address,
  nc.name,
  nc.token_count,
  nc.floor_price;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] List all document IDs, file names, and uploaded timestamps for documents that were uploaded on a weekend.

[Assistant] SELECT document_id, file_name, uploaded_at FROM insurance.claim_documents WHERE EXTRACT(DOW FROM uploaded_at) IN (0, 6);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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 )

[User] List all room types that have a King bed and include their maximum occupancy and amenities.

[Assistant] SELECT type_name, max_occupancy, amenities FROM hospitality_technology.room_types WHERE bed_type = 'King';

[User] Please sort them by maximum occupancy in ascending order.

[Assistant] SELECT type_name, max_occupancy, amenities FROM hospitality_technology.room_types WHERE bed_type = 'King' ORDER BY max_occupancy ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
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] Show me all trades (trade_id, security_id, total_amount) where the trade_type is 'Buy' and the execution_venue is 'NYSE', along with the loan details (loan_type, principal_amount) for accounts that have both trades and loans.

[Assistant] SELECT t.trade_id, t.security_id, t.total_amount, l.loan_type, l.principal_amount FROM financial_services.trades t JOIN financial_services.loans l ON t.account_id = l.account_id WHERE t.trade_type = 'Buy' AND t.execution_venue = 'NYSE';

[User] Now modify the query to only include trades with a total_amount greater than $10,000 and loans with a principal_amount greater than $50,000, sorted by total_amount in descending order.

[Assistant] SELECT t.trade_id, t.security_id, t.total_amount, l.loan_type, l.principal_amount FROM financial_services.trades t JOIN financial_services.loans l ON t.account_id = l.account_id WHERE t.trade_type = 'Buy' AND t.execution_venue = 'NYSE' AND t.total_amount > 10000 AND l.principal_amount > 50000 ORDER BY t.total_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )

[User] Retrieve the citizen_id, full name, and registration_date of all citizens born before 1980-01-01 who are not verified.

[Assistant]
SELECT citizen_id,
       first_name || ' ' || last_name AS full_name,
       registration_date
FROM government_services.citizens
WHERE date_of_birth < '1980-01-01'
  AND is_verified = FALSE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.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.assets ( asset_id text, name text, symbol text, type text )
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.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] For each user, show their username and the number of unique IP addresses from the peers table where the port is less than 2000.

[Assistant]
SELECT u.username, COUNT(DISTINCT p.ip_address) AS unique_ip_count
FROM trading_platform.users u
JOIN trading_platform.peers p ON u.user_id = p.peer_id
WHERE p.port < 2000
GROUP BY u.username;

[User] This query isn't working because peer_id and user_id don't always match. Could you just show the total number of unique IPs with port < 2000 in the peers table, excluding user data?

[Assistant]
SELECT COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000;

[User] Now, for each port number below 2000, show the count of unique IP addresses using that port.

[Assistant]
SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000
GROUP BY port;

[User] Actually, only show ports where more than one unique IP address exists.

[Assistant]
SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000
GROUP BY port
HAVING COUNT(DISTINCT ip_address) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'inspections'. Document structure: { _id: <ObjectId (or inspection_id)>, inspection_id: String, build_id: String (reference), component_id: String (reference, optional), step_id: String (reference, optional), inspection_type: String, inspector_employee_id: String (reference), inspection_timestamp: ISODate, result: String, remarks: String }. Required: inspection_id, build_id, inspection_type, inspector_employee_id, inspection_timestamp, result. Indexes on build_id, component_id, step_id, inspector_employee_id, result.

[User] Can you help me retrieve all inspection records for a specific build ID, including the inspection type, result, and the timestamp of the inspection, along with the associated component ID if available?

[Assistant] db.inspections.find({ build_id: 'specific_build_id' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 })

[User] Can you modify the query to include only inspections that occurred after a specific date, say January 1, 2022?

[Assistant] db.inspections.find({ build_id: 'specific_build_id', inspection_timestamp: { $gt: ISODate('2022-01-01T00:00:00Z') } }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 })

[User] What if I want to further filter the results to show only inspections with a 'Pass' result?

[Assistant] db.inspections.find({ build_id: 'specific_build_id', inspection_timestamp: { $gt: ISODate('2022-01-01T00:00:00Z') }, result: 'Pass' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 })

[User] Can you also sort the results by inspection timestamp in descending order?

[Assistant] db.inspections.find({ build_id: 'specific_build_id', inspection_timestamp: { $gt: ISODate('2022-01-01T00:00:00Z') }, result: 'Pass' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 }).sort({ inspection_timestamp: -1 })


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] Show each passenger's first_name, last_name, and the total number of bookings they have made.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
LEFT JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Filter to only include passengers who have made more than 3 bookings.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
LEFT JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 3;

[User] Also include the average fare for these passengers and order by booking_count descending.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
LEFT JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 3
ORDER BY booking_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] How many beneficiaries exist for each relationship type in the policy_beneficiaries table? Return relationship and beneficiary_count, ordered by count descending.

[Assistant]
SELECT relationship, COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship
ORDER BY beneficiary_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] List all customers along with any employees who have the same last name. For each pair, display customer_id, customer full name, employee_id, employee full name, and their respective emails.

[Assistant]
SELECT c.customer_id,
       c.first_name || ' ' || c.last_name AS customer_full_name,
       c.email AS customer_email,
       e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_full_name,
       e.email AS employee_email
FROM financial_services.customers c
JOIN financial_services.employees e ON c.last_name = e.last_name;

[User] Only show results for customers and employees who have non-null emails.

[Assistant]
SELECT c.customer_id,
       c.first_name || ' ' || c.last_name AS customer_full_name,
       c.email AS customer_email,
       e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_full_name,
       e.email AS employee_email
FROM financial_services.customers c
JOIN financial_services.employees e ON c.last_name = e.last_name
WHERE c.email IS NOT NULL AND e.email IS NOT NULL;

[User] Can you also add the city for the customer and the department for the employee?

[Assistant]
SELECT c.customer_id,
       c.first_name || ' ' || c.last_name AS customer_full_name,
       c.city AS customer_city,
       c.email AS customer_email,
       e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_full_name,
       e.department AS employee_department,
       e.email AS employee_email
FROM financial_services.customers c
JOIN financial_services.employees e ON c.last_name = e.last_name
WHERE c.email IS NOT NULL AND e.email IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )

[User] How many fuel logs were created for each unit of measurement? Show the unit and the corresponding count.

[Assistant]
SELECT unit, COUNT(*) as log_count
FROM transportation.fuel_logs
GROUP BY unit;

[User] Please include only units where more than 10 logs exist and order the results by log_count descending.

[Assistant]
SELECT unit, COUNT(*) as log_count
FROM transportation.fuel_logs
GROUP BY unit
HAVING COUNT(*) > 10
ORDER BY log_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
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.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Show the number of UTXOs associated with each unique address in the system.

[Assistant] SELECT address, COUNT(utxo_id) FROM trading_platform.utxos GROUP BY address;


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

[User] I need a report that shows, for each account status and loan type, how many loans there are and the average principal amount.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY a.status, l.loan_type;

[User] Actually, include only loans whose status is 'Active'.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE l.status = 'Active'
GROUP BY a.status, l.loan_type;

[User] Also exclude any loan_type groups that have fewer than 5 loans.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE l.status = 'Active'
GROUP BY a.status, l.loan_type
HAVING COUNT(*) >= 5;

[User] Finally, sort the output by average_principal in descending order.

[Assistant]
SELECT a.status,
       l.loan_type,
       COUNT(*) AS total_loans,
       AVG(l.principal_amount) AS average_principal
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
WHERE l.status = 'Active'
GROUP BY a.status, l.loan_type
HAVING COUNT(*) >= 5
ORDER BY average_principal DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.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,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Which users have registered but never created a wallet? Show their user_id, username, and email.

[Assistant]
SELECT u.user_id, u.username, u.email
FROM trading_platform.users u
LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id
WHERE w.wallet_id IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )

[User] List each client along with another client who shares the same status.

[Assistant] SELECT c1.client_id AS client1_id, c1.first_name AS client1_first_name, c1.last_name AS client1_last_name, c2.client_id AS client2_id, c2.first_name AS client2_first_name, c2.last_name AS client2_last_name, c1.status FROM legal_services.clients c1 JOIN legal_services.clients c2 ON c1.status = c2.status AND c1.client_id <> c2.client_id;

[User] Actually, I only want pairs where the status is 'prospect'.

[Assistant] SELECT c1.client_id AS client1_id, c1.first_name AS client1_first_name, c1.last_name AS client1_last_name, c2.client_id AS client2_id, c2.first_name AS client2_first_name, c2.last_name AS client2_last_name, c1.status FROM legal_services.clients c1 JOIN legal_services.clients c2 ON c1.status = c2.status AND c1.client_id <> c2.client_id WHERE c1.status = 'prospect';

[User] And only include pairs where both clients have provided a phone number.

[Assistant] SELECT c1.client_id AS client1_id, c1.first_name AS client1_first_name, c1.last_name AS client1_last_name, c2.client_id AS client2_id, c2.first_name AS client2_first_name, c2.last_name AS client2_last_name, c1.status FROM legal_services.clients c1 JOIN legal_services.clients c2 ON c1.status = c2.status AND c1.client_id <> c2.client_id WHERE c1.status = 'prospect' AND c1.phone IS NOT NULL AND c2.phone IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )

[User] List all documents, including their name and upload timestamp, along with the first and last name of the client associated with the case they belong to.

[Assistant] SELECT d.document_name, d.upload_timestamp, c.first_name AS client_first_name, c.last_name AS client_last_name FROM documents AS d JOIN cases AS cs ON d.case_id = cs.case_id JOIN clients AS c ON cs.client_id = c.client_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )

[User] Retrieve the first name, last name, and email for all guests.

[Assistant] SELECT first_name, last_name, email FROM hospitality_technology.guests;

[User] Can you also include their loyalty member ID and whether they have given communication consent?

[Assistant] SELECT first_name, last_name, email, loyalty_member_id, communication_consent FROM hospitality_technology.guests;

[User] Filter this list to only include guests who have a loyalty member ID, have consented to communication, and were created in 2023. Order the results by their last name.

[Assistant] SELECT first_name, last_name, email, loyalty_member_id, communication_consent FROM hospitality_technology.guests WHERE loyalty_member_id IS NOT NULL AND communication_consent = TRUE AND created_at >= '2023-01-01' AND created_at < '2024-01-01' ORDER BY last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )

[User] I need to get a list of all patients who had an appointment in the last 30 days, including patient ID, first and last name, appointment_time, and any associated diagnosis description.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days';

[User] Exclude any appointments with status 'Cancelled'.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days'
  AND a.status <> 'Cancelled';

[User] Also, sort the results by appointment_time descending.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       a.appointment_time,
       d.description
FROM healthcare.appointments a
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
LEFT JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
LEFT JOIN healthcare.diagnoses d
  ON mr.record_id = d.record_id
WHERE a.appointment_time >= current_timestamp - INTERVAL '30 days'
  AND a.status <> 'Cancelled'
ORDER BY a.appointment_time DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] List all appointments, showing the appointment ID, appointment time, patient's insurance plan name, and status.

[Assistant] SELECT a.appointment_id, a.appointment_time, ip.plan_name, a.status FROM healthcare.appointments a LEFT JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = TRUE LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id;

[User] Only show appointments where the status is 'Scheduled'.

[Assistant] SELECT a.appointment_id, a.appointment_time, ip.plan_name, a.status FROM healthcare.appointments a LEFT JOIN healthcare.patient_insurance pi ON a.patient_id = pi.patient_id AND pi.is_primary = TRUE LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id WHERE a.status = 'Scheduled';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_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 (doctor_id) )

[User] List the doctor ID, last name, and the date they were updated, for all doctors updated in the year 2024.

[Assistant] SELECT doctor_id, last_name, updated_at FROM healthcare.doctors WHERE updated_at >= '2024-01-01' AND updated_at < '2025-01-01';

[User] Sort this list by their update date, with the most recently updated doctors appearing first.

[Assistant] SELECT doctor_id, last_name, updated_at FROM healthcare.doctors WHERE updated_at >= '2024-01-01' AND updated_at < '2025-01-01' ORDER BY updated_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)

[User] Show the total hours spent by each lawyer across all their time entries. Display the lawyer's first name, last name, and the total hours.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id GROUP BY l.lawyer_id, l.first_name, l.last_name ORDER BY total_hours DESC;

[User] Modify the previous query to only include time entries that are marked as billable.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_billable_hours FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id WHERE te.is_billable = true GROUP BY l.lawyer_id, l.first_name, l.last_name ORDER BY total_billable_hours DESC;

[User] Now, filter the results to only show lawyers who are partners and have logged more than 100 billable hours in total.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_billable_hours FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id WHERE te.is_billable = true AND l.is_partner = true GROUP BY l.lawyer_id, l.first_name, l.last_name HAVING SUM(te.hours_spent) > 100 ORDER BY total_billable_hours DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )

[User] List the reference number and status for applications where the notes contain the keyword 'urgent'.

[Assistant] SELECT reference_number, status FROM government_services.applications WHERE notes ILIKE '%urgent%';

[User] Among those, show only the applications with a status of 'Pending'.

[Assistant] SELECT reference_number, status FROM government_services.applications WHERE notes ILIKE '%urgent%' AND status = 'Pending';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text )
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE 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.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata ( blockchain.text, contract_address.text, token_id.text, contract_name.text, erc_type.text, amount.bigint, minter.text, owner.text, mint_block_number.bigint, mint_time.bigint, mint_transaction_hash.text, mint_price.text, token_uri.text, metadata.text, name.text, image_uri.text, traits.text, updated_at.bigint, status.text, rarity_score.real, rarity_rank.integer, unique_attribute_count.integer, pk.integer )
CREATE TABLE nft_collections ( blockchain.text, contract_address.text, name.text, symbol.text, deploy_block_number.bigint, deploy_block_time.bigint, erc_type.text, owner.text, traits.text, description.text, slug.text, media_info.text, image_url.text, banner_image_url.text, updated_at.bigint, banner.text, token_count.bigint, floor_price.text, floor_price_symbol.text, floor_price_contract.text, pk.integer )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE mud_holesky_redstone ( address.text, table_id.text, key_bytes.text, key0.text, key1.text, static_data.text, encoded_lengths.text, dynamic_data.text, is_deleted.boolean, block_number.bigint, log_index.bigint )
CREATE TABLE token_balances_bitcoin ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.text, amount.text )
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche ( block_number.bigint, block_timestamp.timestamp, tick.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 NFTs on the 'Ethereum' blockchain with a rarity score above 85. Show their name, contract address, token ID, and rarity score.

[Assistant] SELECT name, contract_address, token_id, rarity_score FROM nft_metadata WHERE blockchain = 'Ethereum' AND rarity_score > 85;

[User] For those NFTs on Ethereum with rarity score above 85, can you add their collection name and only show those that are 'ERC721' type? Also, order them by rarity score descending and limit to 10.

[Assistant] SELECT nm.name, nm.contract_address, nm.token_id, nm.rarity_score, nc.name AS collection_name FROM nft_metadata AS nm JOIN nft_collections AS nc ON nm.contract_address = nc.contract_address WHERE nm.blockchain = 'Ethereum' AND nm.rarity_score > 85 AND nm.erc_type = 'ERC721' ORDER BY nm.rarity_score DESC LIMIT 10;

[User] Actually, instead of ERC721, show me the 'ERC1155' type NFTs from the same list. And sort them by rarity rank ascending instead.

[Assistant] SELECT nm.name, nm.contract_address, nm.token_id, nm.rarity_score, nc.name AS collection_name FROM nft_metadata AS nm JOIN nft_collections AS nc ON nm.contract_address = nc.contract_address WHERE nm.blockchain = 'Ethereum' AND nm.rarity_score > 85 AND nm.erc_type = 'ERC1155' ORDER BY nm.rarity_rank ASC LIMIT 10;

[User] Show me the top 5 'ERC1155' NFTs from that list (Ethereum, rarity score > 85), ordered by rarity rank ascending, but also include the token URI.

[Assistant] SELECT nm.name, nm.contract_address, nm.token_id, nm.rarity_score, nc.name AS collection_name, nm.token_uri FROM nft_metadata AS nm JOIN nft_collections AS nc ON nm.contract_address = nc.contract_address WHERE nm.blockchain = 'Ethereum' AND nm.rarity_score > 85 AND nm.erc_type = 'ERC1155' ORDER BY nm.rarity_rank ASC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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 )

[User] Show me the first name, last name, and job title of employees along with the first name and last name of their managers.

[Assistant]
SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM government_services.employees e
LEFT JOIN government_services.employees m
  ON e.manager_employee_id = m.employee_id;

[User] Can you filter this to only show employees who report to a manager whose job_title is 'Supervisor'?

[Assistant]
SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM government_services.employees e
JOIN government_services.employees m
  ON e.manager_employee_id = m.employee_id
WHERE m.job_title = 'Supervisor';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Node Label: :Route
// Properties:
//   route_id: String (Constraint: UNIQUE)
//   route_name: String
//   description: String
//   is_active: Boolean
// Relationships:
//   (:Route)-[:STARTS_AT]->(:Station)
//   (:Route)-[:ENDS_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (origin:Station {station_id: 'station_bos'}), (dest:Station {station_id: 'station_was'})
// CREATE (r:Route {route_id: 'route_ne_corr', ...})-[:STARTS_AT]->(origin), (r)-[:ENDS_AT]->(dest)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :ScheduledTrip (or just :Trip)
// Properties:
//   schedule_id: String (Constraint: UNIQUE)
//   departure_datetime: DateTime
//   arrival_datetime: DateTime
//   status: String
//   notes: String
// Relationships:
//   (:ScheduledTrip)-[:USES_TRAIN]->(:Train)
//   (:ScheduledTrip)-[:FOLLOWS_ROUTE]->(:Route)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'}), (r:Route {route_id: 'route_ne_corr'})
// CREATE (sched:ScheduledTrip {schedule_id: 'sched_1122', ...})-[:USES_TRAIN]->(t), (sched)-[:FOLLOWS_ROUTE]->(r)
// Relationship: (:ScheduledTrip)-[rel:SCHEDULED_STOP]->(:Station)
// Relationship Properties on :SCHEDULED_STOP:
//   sequence_order: Integer
//   platform_id: String (references Platform node if modeled, or just store ID)
//   scheduled_arrival_time: DateTime
//   scheduled_departure_time: DateTime
//   actual_arrival_time: DateTime
//   actual_departure_time: DateTime
//   status: String
// Example Cypher CREATE:
// MATCH (sched:ScheduledTrip {schedule_id: 'sched_1122'}), (s:Station {station_id: 'station_pvd'})
// CREATE (sched)-[:SCHEDULED_STOP {sequence_order: 2, platform_id: 'plat_pvd_1', ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Ticket
// Properties:
//   ticket_id: String (Constraint: UNIQUE)
//   seat_number: String
//   ticket_type: String
//   price: Float
//   is_checked_in: Boolean
//   qr_code_data: String
// Relationships:
//   (:Ticket)-[:PART_OF_BOOKING]->(:Booking)
//   (:Ticket)-[:ASSIGNED_TO_CAR]->(:TrainCar)
// Example Cypher CREATE:
// MATCH (b:Booking {booking_id: 'book_zyx'}), (c:TrainCar {car_id: 'car_abc'})
// CREATE (t:Ticket {ticket_id: 'tkt_1a2b', ...})-[:PART_OF_BOOKING]->(b), (t)-[:ASSIGNED_TO_CAR]->(c)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)

[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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 )

[User] Get the total number of appointments grouped by status.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status;

[User] Now filter to include only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] List the product_id, product_name, and base_premium for all products that are currently inactive.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE is_active = false;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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] List all document IDs and their corresponding location names for documents that are associated with applications assigned to a service location in the city of 'Los Angeles'.

[Assistant]
SELECT d.document_id, sl.location_name
FROM government_services.documents d
JOIN government_services.service_locations sl
  ON d.application_id = sl.location_id
WHERE sl.city = 'Los Angeles';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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.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 )

[User] List all customers who share an address with another customer. Show both customer IDs, their full names, and the shared address.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name AS first_name_a, a.last_name AS last_name_a,
       b.customer_id AS customer_id_b, b.first_name AS first_name_b, b.last_name AS last_name_b,
       a.address
FROM financial_services.customers a
JOIN financial_services.customers b ON a.address = b.address AND a.customer_id <> b.customer_id;

[User] Only include pairs where both customers are in the same city and state.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name AS first_name_a, a.last_name AS last_name_a,
       b.customer_id AS customer_id_b, b.first_name AS first_name_b, b.last_name AS last_name_b,
       a.address, a.city, a.state
FROM financial_services.customers a
JOIN financial_services.customers b ON a.address = b.address AND a.city = b.city AND a.state = b.state AND a.customer_id <> b.customer_id;

[User] Now, show only unique unordered pairs (i.e., only one (A,B) or (B,A) per pair) and order by address ascending.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name AS first_name_a, a.last_name AS last_name_a,
       b.customer_id AS customer_id_b, b.first_name AS first_name_b, b.last_name AS last_name_b,
       a.address, a.city, a.state
FROM financial_services.customers a
JOIN financial_services.customers b ON a.address = b.address AND a.city = b.city AND a.state = b.state AND a.customer_id < b.customer_id
ORDER BY a.address ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.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.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- 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] For each service location, show the location name, city, and the number of appointments scheduled at that location.

[Assistant]
SELECT sl.location_name, sl.city, COUNT(a.appointment_id) AS appointment_count
FROM government_services.service_locations sl
LEFT JOIN government_services.appointments a ON sl.location_id = a.location_id
GROUP BY sl.location_name, sl.city;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Use Hashes to store station details. Key format: station:<station_id>
// Example:
// HSET station:station_xyz station_id "station_xyz" station_name "Grand Central Terminal" city "New York" state_province "NY" country_code "USA" address "89 E 42nd St..." timezone "America/New_York" number_of_platforms 44 created_at "2023-01-15T10:00:00Z" last_updated_at "2023-10-28T15:30:00Z"

// To quickly find stations by city (optional index):
// SADD stations:city:NewYork station:station_xyz
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1

// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...

// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"

// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for route details. Key format: route:<route_id>
// HSET route:route_ne_corr route_id "route_ne_corr" route_name "Northeast Corridor" ... origin_station_id "station_bos" ... is_active 1
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...

// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...

// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...

// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b

[User] 能否帮我查询特定列车(train_id 为 'train_789')上的所有车辆信息，并关联到该列车所在的路线信息？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule

[User] 能否将查询结果限制在车辆类型为‘Passenger’的车辆上？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result where car_type='Passenger'
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule

[User] 能否再加入车辆的座位容量信息，并按照容量从大到小排序？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result where car_type='Passenger'
SORT car:<car_id> BY capacity DESC
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule

[User] 能否也把路线的起点站和终点站信息加入到结果中？

[Assistant]
SMEMBERS train:train_789:cars
HGETALL car:<car_id> for each car_id in result where car_type='Passenger'
SORT car:<car_id> BY capacity DESC
HGETALL train:train_789
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:<booking_id> for each booking_id in result
HGETALL route:<route_id> for route_id associated with schedule
ZRANGE route:<route_id>:stops 0 0 for origin_station_id
ZRANGE route:<route_id>:stops -1 -1 for destination_station_id
HGETALL station:<origin_station_id>
HGETALL station:<destination_station_id>


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.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.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] List all patients who have had appointments with doctors specializing in 'Oncology', showing patient ID, patient first name, patient last name, doctor ID, doctor first name, and doctor last name.

[Assistant]
SELECT
  p.patient_id,
  p.first_name AS patient_first_name,
  p.last_name AS patient_last_name,
  d.doctor_id,
  d.first_name AS doctor_first_name,
  d.last_name AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.appointments AS a
  ON p.patient_id = a.patient_id
JOIN healthcare.doctors AS d
  ON a.doctor_id = d.doctor_id
WHERE
  d.specialty = 'Oncology';

[User] From this list, only include appointments that occurred in the year 2024.

[Assistant]
SELECT
  p.patient_id,
  p.first_name AS patient_first_name,
  p.last_name AS patient_last_name,
  d.doctor_id,
  d.first_name AS doctor_first_name,
  d.last_name AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.appointments AS a
  ON p.patient_id = a.patient_id
JOIN healthcare.doctors AS d
  ON a.doctor_id = d.doctor_id
WHERE
  d.specialty = 'Oncology' AND a.appointment_time >= '2024-01-01 00:00:00' AND a.appointment_time < '2025-01-01 00:00:00';

[User] Now, only show patients who have had at least 2 such appointments with Oncology doctors in 2024. Display patient ID, patient full name, and the count of these appointments.

[Assistant]
SELECT
  p.patient_id,
  p.first_name,
  p.last_name,
  COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients AS p
JOIN healthcare.appointments AS a
  ON p.patient_id = a.patient_id
JOIN healthcare.doctors AS d
  ON a.doctor_id = d.doctor_id
WHERE
  d.specialty = 'Oncology' AND a.appointment_time >= '2024-01-01 00:00:00' AND a.appointment_time < '2025-01-01 00:00:00'
GROUP BY
  p.patient_id,
  p.first_name,
  p.last_name
HAVING
  COUNT(a.appointment_id) >= 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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.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] Show me the payment amount and the name of the property associated with each payment record.

[Assistant]
SELECT
  p.amount,
  prop.property_name
FROM hospitality_technology.payments AS p
JOIN hospitality_technology.reservations AS r ON p.reservation_id = r.reservation_id -- Assuming reservations links payments and properties
JOIN hospitality_technology.properties AS prop ON r.property_id = prop.property_id;

[User] Now, filter this list to only include payments with a status of 'Succeeded' and sort by payment amount in descending order.

[Assistant]
SELECT
  p.amount,
  prop.property_name
FROM hospitality_technology.payments AS p
JOIN hospitality_technology.reservations AS r ON p.reservation_id = r.reservation_id
JOIN hospitality_technology.properties AS prop ON r.property_id = prop.property_id
WHERE
  p.status = 'Succeeded'
ORDER BY
  p.amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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.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.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id 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 all service orders for spa services in the last month, including the guest name and staff who delivered the service.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month';

[User] Now, include only orders with a total price over $100.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100;

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

[Assistant] SELECT so.order_id, g.first_name, g.last_name, p.property_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id JOIN hospitality_technology.properties p ON so.property_id = p.property_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100;

[User] Actually, I need to see the reservation ID and check-in date for these orders too, and order by total price in descending order.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, p.property_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, r.reservation_id, r.check_in_date, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id JOIN hospitality_technology.properties p ON so.property_id = p.property_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100 ORDER BY so.total_price DESC;