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.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.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 )
##Table Structure
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
##Table Structure
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 character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
##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] List the usernames and registration dates for users who registered before the earliest deployed contract.

[Assistant] SELECT T1.username, T1.created_at FROM web3.users AS T1 JOIN (SELECT MIN(deployed_at) AS earliest_deploy FROM web3.contracts) AS T2 ON T1.created_at < T2.earliest_deploy;

[User] List every diagnosis description paired with every insurance plan's website.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2;

[User] Only include chronic diagnoses and plans whose website ends with '.org'.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2 WHERE T1.is_chronic = true AND T2.website LIKE '%.org';

[User] What is the average ROI and average realized_ratio for each chain?

[Assistant]
SELECT chain,
       AVG(roi) AS avg_roi,
       AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
GROUP BY chain;

[User] Now filter to only include chains where average ROI is above 0.5.

[Assistant]
WITH stats AS (
  SELECT chain,
         AVG(roi) AS avg_roi,
         AVG(realized_ratio) AS avg_realized_ratio
  FROM smart_money_token_performance
  GROUP BY chain
)
SELECT chain, avg_roi, avg_realized_ratio
FROM stats
WHERE avg_roi > 0.5;

[User] Show me the total fuel quantity and cost for each route, grouped by route number, only for trips that have associated fuel logs.

[Assistant]
SELECT r.route_number, SUM(f.quantity) AS total_quantity, SUM(f.total_cost) AS total_cost
FROM transportation.fuel_logs f
JOIN transportation.routes r ON f.trip_id IS NOT NULL AND f.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs
)
JOIN transportation.bookings b ON f.trip_id = b.trip_id
WHERE r.route_id = b.trip_id
GROUP BY r.route_number;

[User] List all trades for asset 'BTC' where the trade quantity is greater than 5.

[Assistant] SELECT trade_id, order_id, buyer_id, seller_id, quantity, price, traded_at FROM trading_platform.trades WHERE asset_id = 'BTC' AND quantity > 5;

[User] List all post IDs that have more than one hashtag associated with them.

[Assistant] SELECT post_id FROM social_media.post_hashtags GROUP BY post_id HAVING COUNT(hashtag_id) > 1;

[User] For each of these posts that have multiple hashtags, show the post ID and all associated hashtag IDs.

[Assistant] SELECT DISTINCT t1.post_id, t1.hashtag_id FROM social_media.post_hashtags AS t1 JOIN social_media.post_hashtags AS t2 ON t1.post_id = t2.post_id WHERE t1.post_hashtag_id != t2.post_hashtag_id;

[User] List the names of law firms whose managing partner has uploaded at least one document, and show the managing partner ID along with the firm's phone number.

[Assistant] SELECT DISTINCT T1.firm_name, T1.managing_partner_id, T1.phone FROM legal_services.law_firms AS T1 JOIN legal_services.documents AS T2 ON T1.managing_partner_id = T2.uploaded_by_lawyer_id;

[User] How many medications does each manufacturer have?

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer;

[User] Only include manufacturers with more than 10 medications.

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer
HAVING COUNT(*) > 10;

[User] For each access level, count the number of employees. Return access_level and the corresponding employee_count.

[Assistant] SELECT access_level, COUNT(*) AS employee_count FROM government_services.employees GROUP BY access_level;


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.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
##Table Structure
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
##Table Structure
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##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 )

[User] List all payments made using a credit card, including guest_id, amount, payment_method, and payment_timestamp.

[Assistant] SELECT guest_id, amount, payment_method, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'CreditCard';

[User] Could you also include the last four digits of the card used for each payment?

[Assistant] SELECT guest_id, amount, payment_method, card_last_four, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'CreditCard';

[User] For each address, show the total amount contained in UTXOs that have been spent.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address;

[User] Only include addresses where this total spent amount is greater than 500 and order the results by the total amount descending.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address HAVING SUM(amount) > 500 ORDER BY SUM(amount) DESC;

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

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

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

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

[User] List all UTXO IDs, addresses, and amounts for unspent UTXOs with an amount between 200 and 800.

[Assistant] SELECT utxo_id, address, amount FROM trading_platform.utxos WHERE spent = false AND amount BETWEEN 200 AND 800;

[User] Count the number of unique users who are being followed.

[Assistant] SELECT COUNT(DISTINCT following_user_id) FROM social_media.follows

[User] List each agent along with their manager's contact_email. Include agent_id, first_name, last_name, manager_id, and manager's contact_email.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.manager_id,
       m.contact_email AS manager_contact_email
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id;

[User] Actually, only include records where the manager is currently active.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.manager_id,
       m.contact_email AS manager_contact_email
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE m.status = 'active';

[User] Find all transactions where the from_address is the same as the to_address, indicating self-transactions, and show the transaction_id, value, and gas_used.

[Assistant] SELECT transaction_id, value, gas_used FROM web3.transactions WHERE from_address = to_address;

[User] For each user, list their username, the number of wallets they have, and the total gas used across all transactions they initiated.

[Assistant]
SELECT u.username,
       COUNT(w.wallet_id) AS wallet_count,
       COALESCE(SUM(t.gas_used), 0) AS total_gas_used
FROM web3.users u
LEFT JOIN web3.wallets w
  ON u.user_id = w.user_id
LEFT JOIN web3.transactions t
  ON t.from_address = w.address
GROUP BY u.username;

[User] Show the license numbers and full names of all doctors who were registered before January 1, 2020 and work at 'hospital_789'.

[Assistant] SELECT license_number, first_name, last_name FROM healthcare.doctors WHERE created_at < '2020-01-01' AND hospital_affiliation_id = 'hospital_789';


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.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.logs ( log_id.text, 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 )
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, 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 int, manager_id text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
##Table Structure
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##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)
)
##Table Structure
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )

[User] Provide a list of all log entries recorded since the start of 2024, including the user ID, action, and the exact time the log occurred.

[Assistant] SELECT user_id, action, logged_at FROM logs WHERE logged_at >= '2024-01-01';

[User] Find all staff members who are managers and list their direct reports. Show the manager's first name, last name, and the direct report's first name, last name, and position.

[Assistant] SELECT m.first_name AS manager_first_name, m.last_name AS manager_last_name, s.first_name AS report_first_name, s.last_name AS report_last_name, s.position AS report_position FROM hospitality_technology.staff s JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id WHERE m.position = 'Manager';

[User] How many users have their profile pictures set and also have written a bio?

[Assistant]
SELECT COUNT(*) AS user_count
FROM social_media.users
WHERE profile_picture_url IS NOT NULL AND profile_picture_url <> ''
  AND bio IS NOT NULL AND bio <> '';

[User] How many comments does each post have? Return post_id and comment_count for posts with more than 5 comments.

[Assistant]
SELECT post_id,
       COUNT(*) AS comment_count
FROM social_media.comments
GROUP BY post_id
HAVING COUNT(*) > 5;

[User] List all pairs of transactions within the same block where the from_address of one transaction is the to_address of another transaction. Show both transaction_ids, the block_number, from_address, and to_address.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.block_number, t1.from_address, t1.to_address
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.block_number = t2.block_number
  AND t1.from_address = t2.to_address
  AND t1.to_address = t2.from_address;

[User] How many hashtags are currently stored in the hashtags table?

[Assistant]
SELECT COUNT(*) AS total_hashtags
FROM social_media.hashtags;

[User] For each notification, list its notification_id, message_subject, and the message_subject of the notification it relates to (assuming related_entity_type = 'notification').

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id;

[User] Only include notifications with status = 'Sent'.

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id
WHERE n.status = 'Sent';

[User] How many lawyers who are partners were hired in each year? Show the hire year and the count.

[Assistant] SELECT strftime('%Y', hire_date) AS hire_year ,  count(lawyer_id) FROM legal_services.lawyers WHERE is_partner  =  true GROUP BY hire_year

[User] List the application_id and the number of notifications with status 'Pending' for each application.

[Assistant]
SELECT application_id, COUNT(*) AS pending_notification_count
FROM government_services.notifications
WHERE status = 'Pending'
GROUP BY application_id;

[User] Show all addresses that made their last trade in 2024, including their chain and profit.

[Assistant] SELECT address, chain, profit FROM smart_money_profit WHERE last_trade_time LIKE '2024%';


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 character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
##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.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
##Table Structure
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
##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 )
##Table Structure
CREATE TABLE legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )

[User] Find all customers who have at least two active policies with overlapping coverage periods. List the customer ID and the policy numbers of any two such overlapping active policies.

[Assistant]
SELECT
  p1.customer_id,
  p1.policy_number AS policy_number_1,
  p2.policy_number AS policy_number_2
FROM insurance.policies AS p1
JOIN insurance.policies AS p2
  ON p1.customer_id = p2.customer_id
  AND p1.policy_id < p2.policy_id
WHERE
  p1.status = 'Active'
  AND p2.status = 'Active'
  AND p1.start_date <= p2.end_date
  AND p1.end_date >= p2.start_date;

[User] Find all pairs of drivers where one driver's license_expiry_date is earlier than another's. Return each pair's driver_ids, full names, and respective expiry dates.

[Assistant] SELECT d1.driver_id AS driver1_id, d1.first_name || ' ' || d1.last_name AS driver1_name, d1.license_expiry_date AS expiry1, d2.driver_id AS driver2_id, d2.first_name || ' ' || d2.last_name AS driver2_name, d2.license_expiry_date AS expiry2 FROM transportation.drivers d1 JOIN transportation.drivers d2 ON d1.license_expiry_date < d2.license_expiry_date;

[User] Which citizens have received notifications for applications processed by employees from the 'Legal' department? List the citizen ID, full name, and notification ID.

[Assistant]
SELECT n.citizen_id, CONCAT(e.first_name, ' ', e.last_name) AS full_name, n.notification_id
FROM government_services.notifications n
JOIN government_services.payments p ON n.application_id = p.application_id AND n.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.service_id IN (
  SELECT s.service_id
  FROM government_services.services s
  JOIN government_services.agencies a ON s.agency_id = a.agency_id
)
WHERE e.department = 'Legal';

[User] For each origin and destination location pair, provide the total number of trips along with the average actual_arrival time.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id;

[User] Can you also filter this to only include pairs where the trip count is greater than 3?

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;

[User] Instead of the epoch average, show the average difference (in minutes) between scheduled_arrival and actual_arrival for these pairs.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival - scheduled_arrival)/60.0) AS avg_delay_minutes FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;

[User] List all trips with their trip_id, vehicle_id, and the corresponding origin_location_id and destination_location_id, but only where the origin and destination are not the same.

[Assistant] SELECT trip_id, vehicle_id, origin_location_id, destination_location_id FROM transportation.trips WHERE origin_location_id <> destination_location_id;

[User] List all pairs of patients who registered on the same day. Show patient1_id, patient1_name, patient2_id, patient2_name, and the shared registration date.

[Assistant] SELECT p1.patient_id AS patient1_id, p1.first_name || ' ' || p1.last_name AS patient1_name, p2.patient_id AS patient2_id, p2.first_name || ' ' || p2.last_name AS patient2_name, p1.created_at::date AS registration_date FROM healthcare.patients p1 JOIN healthcare.patients p2 ON p1.created_at::date = p2.created_at::date AND p1.patient_id < p2.patient_id;

[User] List the name of each law firm along with the first and last name of its managing partner.

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

[User] Can you give me a count of players for each player status?

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players GROUP BY status;

[User] Now, only show me the statuses that have fewer than 100 players.

[Assistant] SELECT status, COUNT(player_id) FROM gaming_technology.players GROUP BY status HAVING COUNT(player_id) < 100;


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.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 )
##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.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
##Table Structure
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 )
##Table Structure
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) )
##Table Structure
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )

[User] Find all pairs of overlapping reservations for the same room. Show the two reservation IDs, room_id, and both reservations' check-in and check-out dates.

[Assistant] SELECT r1.reservation_id AS reservation1_id, r2.reservation_id AS reservation2_id, r1.room_id, r1.check_in_date AS reservation1_check_in, r1.check_out_date AS reservation1_check_out, r2.check_in_date AS reservation2_check_in, r2.check_out_date AS reservation2_check_out FROM hospitality_technology.reservations r1 JOIN hospitality_technology.reservations r2 ON r1.room_id = r2.room_id AND r1.reservation_id < r2.reservation_id AND r1.check_in_date < r2.check_out_date AND r2.check_in_date < r1.check_out_date;

[User] List each service_type and the number of maintenance logs performed for that type, only including service_types with more than 10 records.

[Assistant]
SELECT service_type,
       COUNT(*) AS log_count
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING COUNT(*) > 10;

[User] Now include the average cost of each service_type and order the results by average cost descending.

[Assistant]
SELECT service_type,
       COUNT(*)    AS log_count,
       AVG(cost)   AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING COUNT(*) > 10
ORDER BY avg_cost DESC;

[User] List the full names of patients who have had at least one appointment scheduled with a doctor, along with the medication names they have been prescribed. Please include only patients who have both an appointment and at least one corresponding medication.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, m.medication_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medications m ON m.medication_id IN (
    SELECT medication_id FROM healthcare.medications
) -- Placeholder, since no direct prescription table or mapping is given
WHERE a.status = 'scheduled';

[User] Actually, could you also include the appointment time in the results?

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, a.appointment_time, m.medication_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medications m ON m.medication_id IN (
    SELECT medication_id FROM healthcare.medications
)
WHERE a.status = 'scheduled';

[User] The medication names are not matching with the appointments, I think there is no direct link. Can you just give me, for each patient who has at least one scheduled appointment, all their appointment times and their last names, without including medication info?

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, a.appointment_time
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
WHERE a.status = 'scheduled';

[User] Find claims where the estimated loss is greater than the average estimated loss for claims with a status of 'Closed'. Show the claim ID, incident date, estimated loss, and status.

[Assistant] SELECT claim_id, incident_date, estimated_loss, status FROM insurance.claims WHERE estimated_loss > (SELECT AVG(estimated_loss) FROM insurance.claims WHERE status = 'Closed')

[User] Show me the total payment amount and number of payments for each service.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id;

[User] Only include services where more than 3 payments have been made.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id HAVING COUNT(*) > 3;

[User] Show the names, symbols, and types of all assets whose symbol starts with the letter 'B'.

[Assistant]
SELECT name, symbol, type
FROM trading_platform.assets
WHERE symbol LIKE 'B%';

[User] List the tag names and creation dates for all hashtags created on June 12, 2024.

[Assistant] SELECT tag_name, created_at FROM social_media.hashtags WHERE created_at::date = '2024-06-12';

[User] Please also include the hashtag IDs and order by tag name alphabetically.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at::date = '2024-06-12' ORDER BY tag_name ASC;

[User] List all details for medications whose description contains the word 'pain'.

[Assistant] SELECT * FROM healthcare.medications WHERE description LIKE '%pain%';


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)
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )

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

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

[User] Show me the total estimated loss per claim status, and for each status, include the most recent claim's incident date.

[Assistant]
SELECT status, SUM(estimated_loss) AS total_estimated_loss, MAX(incident_date) AS most_recent_incident_date
FROM insurance.claims
GROUP BY status;


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.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) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )

[User] List the names of agencies and their established dates, but only for agencies that offer at least one service.

[Assistant] SELECT DISTINCT T1.agency_name ,  T1.established_date FROM government_services.agencies AS T1 JOIN government_services.services AS T2 ON T1.agency_id  =  T2.agency_id

[User] Get the total number of participants per conversation along with the number of participants who have private profiles.

[Assistant] SELECT cp.conversation_id, COUNT(cp.user_id) AS total_participants, SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) AS private_profile_count FROM social_media.conversation_participants cp LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id GROUP BY cp.conversation_id;

[User] Exclude conversations with fewer than 3 private profile participants.

[Assistant] SELECT cp.conversation_id, COUNT(cp.user_id) AS total_participants, SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) AS private_profile_count FROM social_media.conversation_participants cp LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id GROUP BY cp.conversation_id HAVING SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) >= 3;

[User] What are the top 3 narratives with the highest total USD buy value?

[Assistant]
SELECT narrative,
       SUM(usd_value) AS total_buy_usd
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY narrative
ORDER BY total_buy_usd DESC
LIMIT 3;

[User] Please include the count of distinct token symbols for each narrative as token_count.

[Assistant]
SELECT narrative,
       SUM(usd_value) AS total_buy_usd,
       COUNT(DISTINCT token_symbol) AS token_count
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY narrative
ORDER BY total_buy_usd DESC
LIMIT 3;

[User] Show me all cases with a status of 'Pending', displaying their case name and court jurisdiction.

[Assistant] SELECT case_name, court_jurisdiction FROM legal_services.cases WHERE status = 'Pending';

[User] Actually, I only want the pending cases in the 'State Court' jurisdiction.

[Assistant] SELECT case_name, court_jurisdiction FROM legal_services.cases WHERE status = 'Pending' AND court_jurisdiction = 'State Court';

[User] Show the case number as well, and sort the results by case_name.

[Assistant] SELECT case_name, case_number, court_jurisdiction FROM legal_services.cases WHERE status = 'Pending' AND court_jurisdiction = 'State Court' ORDER BY case_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 government_services.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )
CREATE TABLE government_services.notifications ( notification_id.text, 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 )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, 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.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )

[User] Show the full names and contact emails of all citizens who have made payments for applications assigned to employees with the job title 'Supervisor'.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
WHERE e.job_title = 'Supervisor';

[User] Retrieve the patient_id, first_name, last_name, and email for all patients who do not have an emergency contact phone number.

[Assistant]
SELECT patient_id, first_name, last_name, email
FROM healthcare.patients
WHERE emergency_contact_phone IS NULL;

[User] Get each property's name, manager_staff_id, and the number of rooms with status 'OutOfOrder', including properties with zero OutOfOrder rooms.

[Assistant]
SELECT p.property_name, p.manager_staff_id, COUNT(r.room_id) AS out_of_order_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r
  ON p.property_id = r.property_id AND r.status = 'OutOfOrder'
GROUP BY p.property_name, p.manager_staff_id;

[User] List all assets with their name, symbol, and type where the asset type is 'token'.

[Assistant] SELECT name, symbol, type FROM trading_platform.assets WHERE type = 'token';


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.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
##Table Structure
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##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 )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
##Table Structure
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##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
##Table Structure
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )

[User] List the user IDs who own more than one wallet and show how many wallets each of them has.

[Assistant] SELECT user_id, COUNT(*) FROM web3.wallets GROUP BY user_id HAVING COUNT(*) > 1;

[User] Find all pairs of origin and destination cities, along with their route_number and distance, where the estimated duration is less than 90 minutes.

[Assistant] SELECT route_number, origin_location_id, destination_location_id, distance_km FROM transportation.routes WHERE estimated_duration_minutes < 90;

[User] Show the user_id, username, and email for users who registered at the same timestamp as another user.

[Assistant] SELECT u1.user_id, u1.username, u1.email FROM web3.users u1 JOIN web3.users u2 ON u1.created_at = u2.created_at AND u1.user_id <> u2.user_id;

[User] List all unique document types available in the system.

[Assistant] SELECT DISTINCT document_type FROM insurance.claim_documents;

[User] What are the distinct MIME types of documents stored in the system?

[Assistant] SELECT DISTINCT mime_type FROM insurance.claim_documents;

[User] Find pairs of documents in the same case where one document is of type 'Contract' and the other is of type 'Evidence'. Return the case_id, the contract document_name as contract_name, and the evidence document_name as evidence_name.

[Assistant]
SELECT c.case_id,
       c.document_name AS contract_name,
       e.document_name AS evidence_name
FROM legal_services.documents c
JOIN legal_services.documents e
  ON c.case_id = e.case_id
WHERE c.document_type = 'Contract'
  AND e.document_type = 'Evidence';

[User] List each claim_handler_id and the number of claims they handled that were reported in 2023.

[Assistant]
SELECT claim_handler_id,
       COUNT(*) AS claims_count
FROM insurance.claims
WHERE reported_date::date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY claim_handler_id;

[User] Could you provide the total number of notifications sent on each day?

[Assistant] SELECT DATE(sent_at), COUNT(*) FROM notifications GROUP BY DATE(sent_at) ORDER BY DATE(sent_at);

[User] Now, show only the days where more than 50 notifications were sent. Also, for those days, calculate the average time it took for notifications sent on that day to be read (only consider notifications that have been read).

[Assistant] SELECT DATE(sent_at), COUNT(*), AVG(EXTRACT(EPOCH FROM (read_at - sent_at))) FROM notifications WHERE read_at IS NOT NULL GROUP BY DATE(sent_at) HAVING COUNT(*) > 50 ORDER BY DATE(sent_at);

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

[Assistant] SCARD station:station_xyz:platforms

[User] What is the total number of likes recorded in the system?

[Assistant] SELECT COUNT(*) FROM social_media.likes;


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.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.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 )
##Table Structure
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
##Table Structure
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
##Table Structure
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 )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
##Table Structure
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 )

[User] Find all wallets that were created by users with IDs starting with 'user_' and show their addresses along with creation timestamps.

[Assistant] SELECT address, created_at FROM web3.wallets WHERE user_id LIKE 'user_%';

[User] List all pairs of locations where both are located in the same timezone but are in different cities. Include both location IDs, names, the timezone, and their respective cities.

[Assistant]
SELECT l1.location_id AS location1_id, l1.name AS location1_name, l2.location_id AS location2_id, l2.name AS location2_name, l1.timezone, l1.city AS city1, l2.city AS city2
FROM transportation.locations l1
JOIN transportation.locations l2 ON l1.timezone = l2.timezone
    AND l1.city <> l2.city
    AND l1.location_id < l2.location_id;

[User] Retrieve the first_name, last_name, and email of all passengers who have never made a booking.

[Assistant]
SELECT
  p.first_name,
  p.last_name,
  p.email
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
WHERE b.booking_id IS NULL;

[User] Which services charge more than the average standard fee of their category? Show the service name, its fee, and the average fee for that category.

[Assistant]
SELECT
  s.service_name,
  s.standard_fee,
  avg_fees.avg_fee
FROM government_services.services s
JOIN (
  SELECT
    category,
    AVG(standard_fee) AS avg_fee
  FROM government_services.services
  GROUP BY category
) avg_fees
  ON s.category = avg_fees.category
WHERE s.standard_fee > avg_fees.avg_fee;

[User] What is the average ROI for tokens with a realized ratio above 50% across all chains?

[Assistant] SELECT AVG(roi) AS average_roi FROM smart_money_token_performance WHERE realized_ratio > 50;

[User] List the first name, last name, and email of all customers who live in New York or California.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE state IN ('NY', 'CA');

[User] How many addresses on the Polygon chain have an ROI above 5?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE chain = 'Polygon' AND roi > 5;

[User] Also show the average profit of these addresses.

[Assistant] SELECT COUNT(*) AS address_count, AVG(profit) AS avg_profit FROM smart_money_profit WHERE chain = 'Polygon' AND roi > 5;

[User] List pairs of distinct routes that originate from the same location but go to different destinations. Show the route ID and route number for both routes and the common origin location ID.

[Assistant]
SELECT
  r1.route_id AS route1_id,
  r1.route_number AS route1_number,
  r2.route_id AS route2_id,
  r2.route_number AS route2_number,
  r1.origin_location_id AS shared_origin_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.destination_location_id != r2.destination_location_id;

[User] Show the earliest and latest timestamp recorded in the logs table.

[Assistant] SELECT MIN(logged_at), MAX(logged_at) FROM trading_platform.logs;

[User] Find all pairs of drivers who have the same license expiry date. For each pair, provide both driver_ids, full names, and the shared expiry date.

[Assistant]
SELECT d1.driver_id AS driver1_id, d1.first_name || ' ' || d1.last_name AS driver1_name,
       d2.driver_id AS driver2_id, d2.first_name || ' ' || d2.last_name AS driver2_name,
       d1.license_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d1.license_expiry_date = d2.license_expiry_date
 AND d1.driver_id < d2.driver_id;

[User] How many distinct users have uploaded claim documents of type 'ACCIDENT_REPORT'?

[Assistant] SELECT COUNT(DISTINCT uploaded_by) FROM insurance.claim_documents WHERE document_type = 'ACCIDENT_REPORT';

[User] Count the number of orders in each status.

[Assistant]
SELECT status, COUNT(*) AS order_count
FROM trading_platform.orders
GROUP BY status;


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(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id varchar NOT NULL, coin_type varchar NOT NULL, status varchar NOT NULL, decimals bigint NOT NULL, description varchar NOT NULL, icon_url varchar NOT NULL, symbol varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

[User] List all wallet addresses holding NFTs for contract address '0xabcdef...'. Show the wallet address and amount held.

[Assistant] SELECT wallet_address, amount, token_id FROM nft_holders WHERE contract_address = '0xabcdef...';

[User] For these holders, include the token ID, NFT name, and rarity score.

[Assistant] SELECT nh.wallet_address, nh.amount, nh.token_id, nm.name, nm.rarity_score FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_address = '0xabcdef...';

[User] Only show NFTs with a rarity score above 80 and wallets holding more than 1 unit. Order by rarity score descending.

[Assistant] SELECT nh.wallet_address, nh.amount, nh.token_id, nm.name, nm.rarity_score FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_address = '0xabcdef...' AND nm.rarity_score > 80 AND CAST(nh.amount AS INTEGER) > 1 ORDER BY nm.rarity_score 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
// db.createCollection('platforms')
// Optional: db.platforms.createIndex({ platform_id: 1 }, { unique: true })
// Optional: db.platforms.createIndex({ station_id: 1 })
{
  _id: ObjectId(),
  platform_id: "plat_123", // String (unique)
  station_id: "station_xyz", // String (references stations.station_id)
  platform_number: "1A", // String
  track_number: "T1", // String
  status: "Operational", // String ('Operational', 'Maintenance', 'Closed')
  length_meters: 250.50, // Decimal128 or Double
  accessible: true // Boolean
}
// db.createCollection('routes')
// Optional: db.routes.createIndex({ route_id: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_id: "route_ne_corr", // String (unique)
  route_name: "Northeast Corridor", // String
  description: "High-speed rail linking Boston and Washington D.C.", // String
  origin_station_id: "station_bos", // String (references stations.station_id)
  destination_station_id: "station_was", // String (references stations.station_id)
  is_active: true // Boolean
}
// db.createCollection('route_stations')
// Optional: db.route_stations.createIndex({ route_station_id: 1 }, { unique: true })
// Optional: db.route_stations.createIndex({ route_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_station_id: "rs_ne_1", // String (unique)
  route_id: "route_ne_corr", // String (references routes.route_id)
  station_id: "station_bos", // String (references stations.station_id)
  sequence_order: 1, // Int32
  distance_from_previous_km: null, // Decimal128 or Double (null for first stop)
  typical_stop_duration_minutes: null // Int32 (null for origin/destination or if no stop)
}
// --- OR --- Embed within the Route document:
// {
//   _id: ObjectId(), route_id: "route_ne_corr", ...,
//   stations: [
//     { station_id: "station_bos", sequence_order: 1, distance_from_previous_km: null, typical_stop_duration_minutes: null },
//     { station_id: "station_pvd", sequence_order: 2, distance_from_previous_km: 70.5, typical_stop_duration_minutes: 5 },
//     ...
//   ]
// }
// db.createCollection('schedules')
// Optional: db.schedules.createIndex({ schedule_id: 1 }, { unique: true })
// Optional: db.schedules.createIndex({ route_id: 1, departure_datetime: 1 })
{
  _id: ObjectId(),
  schedule_id: "sched_1122", // String (unique)
  train_id: "train_789", // String (references trains.train_id)
  route_id: "route_ne_corr", // String (references routes.route_id)
  departure_datetime: ISODate("2024-05-10T08:00:00-04:00"), // Date (with timezone)
  arrival_datetime: ISODate("2024-05-10T15:30:00-04:00"), // Date (with timezone)
  status: "Scheduled", // String ('Scheduled', 'On Time', 'Delayed', 'Cancelled', 'Arrived')
  notes: "Track work expected near Philadelphia" // String
}
// db.createCollection('schedule_stops')
// Optional: db.schedule_stops.createIndex({ stop_id: 1 }, { unique: true })
// Optional: db.schedule_stops.createIndex({ schedule_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  stop_id: "stop_sched1122_1", // String (unique)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  station_id: "station_bos", // String (references stations.station_id)
  platform_id: "plat_bos_3", // String (references platforms.platform_id, nullable)
  sequence_order: 1, // Int32
  scheduled_arrival_time: null, // Date
  scheduled_departure_time: ISODate("2024-05-10T08:00:00-04:00"), // Date
  actual_arrival_time: null, // Date
  actual_departure_time: ISODate("2024-05-10T08:01:00-04:00"), // Date
  status: "On Time" // String
}
// --- OR --- Embed within the Schedule document using an array 'stops'
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}
##Table Structure
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)
)
##Table Structure
CREATE TABLE web3.events ( event_id text PRIMARY KEY, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index int )

[User] Can you help me get the total number of operational platforms across all stations?

[Assistant] db.platforms.countDocuments({ status: 'Operational' });

[User] Show me the top 5 users with the most KYC audits, along with their latest audit status.

[Assistant] SELECT user_id, status, COUNT(*) as audit_count FROM trading_platform.kyc_audit GROUP BY user_id, status ORDER BY audit_count DESC LIMIT 5;

[User] Now modify the query to show only users whose latest KYC status was rejected.

[Assistant] WITH latest_audit AS (SELECT user_id, status, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY reviewed_at DESC) as rn FROM trading_platform.kyc_audit) SELECT user_id, status FROM latest_audit WHERE rn = 1 AND status = 'rejected' LIMIT 5;

[User] Actually, I want to see the count of rejected audits per user instead of just the latest status.

[Assistant] SELECT user_id, COUNT(*) as rejected_count FROM trading_platform.kyc_audit WHERE status = 'rejected' GROUP BY user_id ORDER BY rejected_count DESC LIMIT 5;

[User] Find all events where the data field contains 'amount' and show the event name, contract ID, and transaction ID, along with the log index, sorted by log index in ascending order.

[Assistant] SELECT event_name, contract_id, transaction_id, log_index FROM web3.events WHERE data LIKE '%amount%' ORDER BY log_index ASC;