[User] Find users who have never followed anyone but have created at least 5 posts. Return user_id and post_count.

[Assistant]
SELECT u.user_id, COUNT(p.post_id) AS post_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
WHERE NOT EXISTS (
  SELECT 1 FROM social_media.follows f WHERE f.follower_user_id = u.user_id
)
GROUP BY u.user_id
HAVING COUNT(p.post_id) >= 5;

[User] I want to see their usernames instead of user_ids.

[Assistant]
SELECT u.username, COUNT(p.post_id) AS post_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
WHERE NOT EXISTS (
  SELECT 1 FROM social_media.follows f WHERE f.follower_user_id = u.user_id
)
GROUP BY u.username
HAVING COUNT(p.post_id) >= 5;

[User] Also include the timestamp of their oldest post as first_post_time.

[Assistant]
SELECT u.username,
       COUNT(p.post_id) AS post_count,
       MIN(p.created_at) AS first_post_time
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
WHERE NOT EXISTS (
  SELECT 1 FROM social_media.follows f WHERE f.follower_user_id = u.user_id
)
GROUP BY u.username
HAVING COUNT(p.post_id) >= 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )


[User] Count the number of law firms founded in each decade. Show the decade (e.g., 1990s, 2000s) and the count.

[Assistant] SELECT CONCAT(FLOOR(EXTRACT(YEAR FROM founded_date) / 10) * 10, 's') AS decade, COUNT(*) AS firm_count FROM law_firms WHERE founded_date IS NOT NULL GROUP BY decade ORDER BY decade;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )


[User] Show me all fuel logs where the location is 'LOC456', including the vehicle ID, fuel type, and quantity.

[Assistant] SELECT fuel_log_id, vehicle_id, fuel_type, quantity FROM transportation.fuel_logs WHERE location_id = 'LOC456';

[User] Can you also include the trip ID and filter to only show logs from the last 3 months?

[Assistant] SELECT fuel_log_id, vehicle_id, trip_id, fuel_type, quantity FROM transportation.fuel_logs WHERE location_id = 'LOC456' AND log_timestamp >= CURRENT_DATE - INTERVAL '3 months';

[User] Now group these results by fuel type and show the total quantity for each type.

[Assistant] SELECT fuel_type, SUM(quantity) AS total_quantity FROM transportation.fuel_logs WHERE location_id = 'LOC456' AND log_timestamp >= CURRENT_DATE - INTERVAL '3 months' GROUP BY fuel_type;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )


[User] List all medical record IDs and the record date for records created by doctors specializing in 'Gastroenterology'.

[Assistant] SELECT mr.record_id, mr.record_date FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id WHERE d.specialty = 'Gastroenterology';

[User] Could you also include the patient's first and last name for these records?

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology';

[User] Now, only show records for male patients.

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male';

[User] Additionally, restrict the results to medical records that have at least one associated diagnosis with status 'Resolved'.

[Assistant] SELECT DISTINCT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id JOIN healthcare.diagnoses diag ON mr.record_id = diag.record_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male' AND diag.status = 'Resolved';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_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, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


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

[Assistant] SELECT E.event_id, E.event_name, E.transaction_id, T.status, T.value FROM web3.events AS E JOIN web3.transactions AS T ON E.transaction_id = T.transaction_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] List all wallet addresses holding NFT contract '0xbbbb...' and token ID '99'.

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

[User] How many unique holders are there?

[Assistant]
SELECT COUNT(DISTINCT wallet_address) AS unique_holders
FROM nft_holders
WHERE contract_address = '0xbbbb...'
  AND token_id = '99';

[User] Only include wallets holding more than one token.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xbbbb...'
  AND token_id = '99'
  AND CAST(amount AS numeric) > 1;

[User] Sort the result by amount descending and limit to top 5.

[Assistant]
SELECT wallet_address, amount
FROM nft_holders
WHERE contract_address = '0xbbbb...'
  AND token_id = '99'
  AND CAST(amount AS numeric) > 1
ORDER BY CAST(amount AS numeric) DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] I need the average close_price per sector for the last month.

[Assistant]
SELECT s.sector, AVG(m.close_price) AS avg_close_price
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Can you also include the maximum volume per sector?

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Now I only want data from source 'Reuters'.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector;

[User] Finally, only include sectors with total volume over 1000000 and order by avg_close_price descending.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector
HAVING SUM(m.volume) > 1000000
ORDER BY avg_close_price DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )


[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal' ORDER BY date_opened ASC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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] 我想查看所有检查记录中检查员的ID和检查结果，同时统计每个检查员的检查次数。

[Assistant]
db.inspections.aggregate([
  {
    $group: {
      _id: '$inspector_employee_id',
      total_inspections: { $count: {} },
      results: { $push: '$result' }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      total_inspections: 1,
      results: 1,
      _id: 0
    }
  }
]);

[User] 如果我想只统计检查结果为'Fail'的次数，应该怎么改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Fail'
    }
  },
  {
    $group: {
      _id: '$inspector_employee_id',
      failed_inspections: { $count: {} }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      failed_inspections: 1,
      _id: 0
    }
  }
]);

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


[User] Can you give me the list of server names and their regions, along with the total number of players currently online in each region?

[Assistant]
SELECT region, SUM(current_players) AS total_current_players, STRING_AGG(server_name, ', ') AS server_names
FROM gaming_technology.servers
WHERE status = 'online'
GROUP BY region;

[User] I want to include the count of servers in each region as well. Can you modify the query?

[Assistant]
SELECT region, COUNT(server_id) AS server_count, SUM(current_players) AS total_current_players, STRING_AGG(server_name, ', ') AS server_names
FROM gaming_technology.servers
WHERE status = 'online'
GROUP BY region;

[User] Add only those regions where the server count is more than 2.

[Assistant]
SELECT region, COUNT(server_id) AS server_count, SUM(current_players) AS total_current_players, STRING_AGG(server_name, ', ') AS server_names
FROM gaming_technology.servers
WHERE status = 'online'
GROUP BY region
HAVING COUNT(server_id) > 2;

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

[Assistant]
SELECT region, COUNT(server_id) AS server_count, SUM(current_players) AS total_current_players, STRING_AGG(server_name, ', ') AS server_names
FROM gaming_technology.servers
WHERE status = 'online'
GROUP BY region
HAVING COUNT(server_id) > 2
ORDER BY total_current_players DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )


[User] List all invoices that were paid within 7 days of their issue date. Show invoice number, issue date, payment date, and total amount.

[Assistant] SELECT invoice_number, issue_date, payment_date, total_amount FROM legal_services.invoices WHERE status = 'Paid' AND payment_date IS NOT NULL AND (payment_date::DATE - issue_date) <= 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )


[User] Show me all users who have placed orders but have no trades, along with their order count and average order quantity.

[Assistant] SELECT u.user_id, u.email, COUNT(o.order_id) AS order_count, AVG(o.quantity) AS avg_order_quantity FROM trading_platform.users u JOIN trading_platform.orders o ON u.user_id = o.user_id LEFT JOIN trading_platform.trades t ON o.order_id = t.order_id WHERE t.trade_id IS NULL GROUP BY u.user_id, u.email

[User] Now modify the query to only include users who have placed more than 3 orders and show their earliest order date.

[Assistant] SELECT u.user_id, u.email, COUNT(o.order_id) AS order_count, AVG(o.quantity) AS avg_order_quantity, MIN(o.created_at) AS earliest_order_date FROM trading_platform.users u JOIN trading_platform.orders o ON u.user_id = o.user_id LEFT JOIN trading_platform.trades t ON o.order_id = t.order_id WHERE t.trade_id IS NULL GROUP BY u.user_id, u.email HAVING COUNT(o.order_id) > 3

[User] Actually, I want to see these results grouped by order_type as well, and only for buy orders.

[Assistant] SELECT u.user_id, u.email, o.order_type, COUNT(o.order_id) AS order_count, AVG(o.quantity) AS avg_order_quantity, MIN(o.created_at) AS earliest_order_date FROM trading_platform.users u JOIN trading_platform.orders o ON u.user_id = o.user_id LEFT JOIN trading_platform.trades t ON o.order_id = t.order_id WHERE t.trade_id IS NULL AND o.order_type = 'buy' GROUP BY u.user_id, u.email, o.order_type HAVING COUNT(o.order_id) > 3

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] List the first and last names of employees and the full name of the citizens for whom they have scheduled appointments.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T3.first_name ,  T3.last_name FROM government_services.employees AS T1 JOIN government_services.appointments AS T2 ON T1.employee_id  =  T2.employee_id JOIN government_services.citizens AS T3 ON T2.citizen_id  =  T3.citizen_id

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, 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 PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, 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 PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Can you show me all prescriptions along with each patient's policy number and insurance plan ID?

[Assistant]
SELECT p.prescription_id, p.patient_id, p.medication_id, pi.policy_number, pi.plan_id
FROM healthcare.prescriptions p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id;

[User] Actually, only show prescriptions for patients whose insurance policy is still active today.

[Assistant]
SELECT p.prescription_id, p.patient_id, p.medication_id, pi.policy_number, pi.plan_id
FROM healthcare.prescriptions p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
WHERE pi.effective_date <= CURRENT_DATE AND (pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_DATE);

[User] Only include those policies marked as primary and order by prescription_date descending.

[Assistant]
SELECT p.prescription_id, p.patient_id, p.medication_id, pi.policy_number, pi.plan_id
FROM healthcare.prescriptions p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
WHERE pi.effective_date <= CURRENT_DATE
  AND (pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_DATE)
  AND pi.is_primary = TRUE
ORDER BY p.prescription_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] Count the total number of distinct specialties listed in the doctors table.

[Assistant] SELECT count(DISTINCT specialty) FROM healthcare.doctors;

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


[User] I need to identify pairs of verified documents submitted by the same citizen. For each pair, display the citizen_id, the earlier document_id with its verification timestamp, and the later document_id with its verification timestamp.

[Assistant]
SELECT
  d1.citizen_id,
  d1.document_id AS earlier_document_id,
  d1.verification_timestamp AS earlier_verification,
  d2.document_id AS later_document_id,
  d2.verification_timestamp AS later_verification
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.citizen_id = d2.citizen_id
  AND d1.verification_timestamp < d2.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )


[User] I want to list all employees who currently manage at least one other employee, showing their full name, email, and the total number of direct reports for each manager.

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, COUNT(r.employee_id) AS direct_report_count
FROM financial_services.employees e
JOIN financial_services.employees r ON e.employee_id = r.manager_id
WHERE e.status = 'Active'
GROUP BY e.employee_id, e.first_name, e.last_name, e.email;

[User] Can you also include the job_title and department of each manager in the result?

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, e.job_title, e.department, COUNT(r.employee_id) AS direct_report_count
FROM financial_services.employees e
JOIN financial_services.employees r ON e.employee_id = r.manager_id
WHERE e.status = 'Active'
GROUP BY e.employee_id, e.first_name, e.last_name, e.email, e.job_title, e.department;

[User] I noticed some managers don't have any reports—that shouldn't be the case. Only show managers who have at least two direct reports.

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, e.job_title, e.department, COUNT(r.employee_id) AS direct_report_count
FROM financial_services.employees e
JOIN financial_services.employees r ON e.employee_id = r.manager_id
WHERE e.status = 'Active'
GROUP BY e.employee_id, e.first_name, e.last_name, e.email, e.job_title, e.department
HAVING COUNT(r.employee_id) >= 2;

[User] Please order the output by the number of direct reports in descending order.

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS manager_full_name, e.email, e.job_title, e.department, COUNT(r.employee_id) AS direct_report_count
FROM financial_services.employees e
JOIN financial_services.employees r ON e.employee_id = r.manager_id
WHERE e.status = 'Active'
GROUP BY e.employee_id, e.first_name, e.last_name, e.email, e.job_title, e.department
HAVING COUNT(r.employee_id) >= 2
ORDER BY direct_report_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] List all users whose usernames start with the letter 'B'.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username LIKE 'B%';

[User] Can you make it case-insensitive, so usernames starting with either upper or lower case 'b' are included?

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username ILIKE 'b%';

[User] Instead of showing all details, just display the usernames in alphabetical order.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC;

[User] Limit the result to only the first 3 usernames.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)


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

[Assistant]
SELECT c.first_name, c.last_name, sl.city, sl.state
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.application_id IS NOT NULL AND e.agency_id IS NOT NULL
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] List all servers that are currently online and have a player count greater than their average player count across all servers in the same region.

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online' AND s.current_players > r.avg_players;

[User] Can you also include the maximum players of each server in the result?

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, s.max_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online' AND s.current_players > r.avg_players;

[User] Now only show servers where current_players is at least 75% of max_players.

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, s.max_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online'
  AND s.current_players > r.avg_players
  AND s.current_players >= 0.75 * s.max_players;

[User] Please also show the average player count for the region in each row.

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, s.max_players, r.avg_players
FROM gaming_technology.servers s
JOIN (SELECT region, AVG(current_players) AS avg_players FROM gaming_technology.servers GROUP BY region) r
  ON s.region = r.region
WHERE s.status = 'online'
  AND s.current_players > r.avg_players
  AND s.current_players >= 0.75 * s.max_players;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )


[User] For each route, list the route number, description, and the combined total maintenance cost for all vehicles that have ever operated on that route.

[Assistant] WITH VehicleTotalMaintenance AS ( SELECT vehicle_id, SUM(cost) AS total_cost FROM transportation.maintenance_logs GROUP BY vehicle_id ), RouteVehicles AS ( SELECT DISTINCT route_id, vehicle_id FROM transportation.trips ) SELECT R.route_number, R.description, SUM(VTM.total_cost) AS total_vehicle_maintenance_cost FROM transportation.routes AS R JOIN RouteVehicles AS RV ON R.route_id = RV.route_id JOIN VehicleTotalMaintenance AS VTM ON RV.vehicle_id = VTM.vehicle_id GROUP BY R.route_id, R.route_number, R.description;

[User] Refine this list to only show routes where the total combined vehicle maintenance cost exceeds 10000.

[Assistant] WITH VehicleTotalMaintenance AS ( SELECT vehicle_id, SUM(cost) AS total_cost FROM transportation.maintenance_logs GROUP BY vehicle_id ), RouteVehicles AS ( SELECT DISTINCT route_id, vehicle_id FROM transportation.trips ) SELECT R.route_number, R.description, SUM(VTM.total_cost) AS total_vehicle_maintenance_cost FROM transportation.routes AS R JOIN RouteVehicles AS RV ON R.route_id = RV.route_id JOIN VehicleTotalMaintenance AS VTM ON RV.vehicle_id = VTM.vehicle_id GROUP BY R.route_id, R.route_number, R.description HAVING SUM(VTM.total_cost) > 10000;

[User] For these routes with high maintenance costs, please also include the total number of completed trips associated with the route.

[Assistant] WITH VehicleTotalMaintenance AS ( SELECT vehicle_id, SUM(cost) AS total_cost FROM transportation.maintenance_logs GROUP BY vehicle_id ), RouteVehicles AS ( SELECT DISTINCT route_id, vehicle_id FROM transportation.trips ), RouteCompletedTrips AS ( SELECT route_id, COUNT(*) AS completed_trip_count FROM transportation.trips WHERE status = 'Completed' GROUP BY route_id ) SELECT R.route_number, R.description, SUM(VTM.total_cost) AS total_vehicle_maintenance_cost, RCT.completed_trip_count FROM transportation.routes AS R JOIN RouteVehicles AS RV ON R.route_id = RV.route_id JOIN VehicleTotalMaintenance AS VTM ON RV.vehicle_id = VTM.vehicle_id LEFT JOIN RouteCompletedTrips AS RCT ON R.route_id = RCT.route_id GROUP BY R.route_id, R.route_number, R.description, RCT.completed_trip_count HAVING SUM(VTM.total_cost) > 10000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )


[User] List all pairs of tokens (show token_id for both) that share the same contract address, excluding pairs where the token_id is the same.

[Assistant] SELECT t1.token_id AS token_id1, t2.token_id AS token_id2, t1.contract_address FROM web3.tokens AS t1 JOIN web3.tokens AS t2 ON t1.contract_address = t2.contract_address WHERE t1.token_id < t2.token_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )


[User] Find the average score for each player who has participated in game sessions.

[Assistant]
SELECT player_id, AVG(score) AS avg_score
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Now show only players who have also unlocked at least one achievement.

[Assistant]
SELECT gs.player_id, AVG(gs.score) AS avg_score
FROM gaming_technology.game_sessions gs
WHERE gs.player_id IN (
    SELECT DISTINCT pa.player_id FROM gaming_technology.player_achievements pa
)
GROUP BY gs.player_id;

[User] Can you also include the total number of achievements each player has unlocked?

[Assistant]
SELECT gs.player_id, AVG(gs.score) AS avg_score, COUNT(pa.achievement_id) AS total_achievements
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.player_achievements pa ON gs.player_id = pa.player_id
GROUP BY gs.player_id;

[User] I received duplicate player rows. Can you fix the SQL so the achievement count is correct for each player?

[Assistant]
SELECT gs.player_id, AVG(gs.score) AS avg_score, (
    SELECT COUNT(DISTINCT pa.achievement_id)
    FROM gaming_technology.player_achievements pa
    WHERE pa.player_id = gs.player_id
) AS total_achievements
FROM gaming_technology.game_sessions gs
WHERE gs.player_id IN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
)
GROUP BY gs.player_id;

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


[User] Show me all diesel fuel logs from the last month with their vehicle details, including make, model and license plate.

[Assistant] SELECT f.fuel_log_id, f.log_timestamp, f.quantity, f.total_cost, v.make, v.model, v.license_plate FROM transportation.fuel_logs f JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id WHERE f.fuel_type = 'diesel' AND f.log_timestamp >= CURRENT_DATE - INTERVAL '1 month'

[User] Can you also include the trip ID and location name where the fueling occurred, and order by the most expensive fuel logs first?

[Assistant] SELECT f.fuel_log_id, f.trip_id, f.log_timestamp, f.quantity, f.total_cost, v.make, v.model, v.license_plate, l.name AS location_name FROM transportation.fuel_logs f JOIN transportation.vehicles v ON f.vehicle_id = v.vehicle_id JOIN transportation.locations l ON f.location_id = l.location_id WHERE f.fuel_type = 'diesel' AND f.log_timestamp >= CURRENT_DATE - INTERVAL '1 month' ORDER BY f.total_cost DESC

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
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 character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] I need a report of patients who have received prescriptions for medications manufactured by 'Pfizer'. Include patient ID, first name, last name, medication_name, and prescription_date.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       m.medication_name,
       pr.prescription_date
FROM healthcare.patients AS p
JOIN healthcare.prescriptions AS pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications AS m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Pfizer';

[User] Actually, only include prescriptions with a dosage containing 'mg' and sort by prescription_date descending.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       m.medication_name,
       pr.prescription_date
FROM healthcare.patients AS p
JOIN healthcare.prescriptions AS pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications AS m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Pfizer'
  AND pr.dosage ILIKE '%mg%'
ORDER BY pr.prescription_date DESC;

[User] Also, include the patient's primary insurance policy number and plan name in the report.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       m.medication_name,
       pr.prescription_date,
       pi.policy_number,
       ip.plan_name
FROM healthcare.patients AS p
JOIN healthcare.prescriptions AS pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications AS m ON pr.medication_id = m.medication_id
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans AS ip ON pi.plan_id = ip.plan_id
WHERE m.manufacturer = 'Pfizer'
  AND pr.dosage ILIKE '%mg%'
ORDER BY pr.prescription_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id 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) )


[User] Show me all room types with a base rate over $200 and max occupancy of at least 4, along with their property IDs and amenities.

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

[User] Now, join this with the service_orders table to show only room types that have at least 5 service orders.

[Assistant] SELECT rt.room_type_id, rt.property_id, rt.amenities FROM hospitality_technology.room_types rt JOIN hospitality_technology.service_orders so ON rt.property_id = so.property_id WHERE rt.base_rate > 200 AND rt.max_occupancy >= 4 GROUP BY rt.room_type_id, rt.property_id, rt.amenities HAVING COUNT(so.order_id) >= 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )


[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;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )


[User] Show me the number of game servers in each region and the average maximum number of players they can accommodate. Exclude any servers that are currently offline.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region;

[User] Please filter the results to only include regions that have more than 5 active servers.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Can you also include the total number of current players across all active servers in each of those regions?

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Order the final results by the total number of current players in descending order.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5 ORDER BY total_current_players DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


[User] Show all doctors created before January 1st, 2023, listing their ID, first name, and last name.

[Assistant]
SELECT
    doctor_id,
    first_name,
    last_name
FROM
    healthcare.doctors
WHERE
    created_at < '2023-01-01';

[User] Could you also include their hospital affiliation ID and email address for this list?

[Assistant]
SELECT
    doctor_id,
    first_name,
    last_name,
    hospital_affiliation_id,
    email
FROM
    healthcare.doctors
WHERE
    created_at < '2023-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.doctors ( doctor_id.text, first_name.text, last_name.text, specialty.text, license_number.text, phone_number.text, email.text, hospital_affiliation_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] For each player, list their username and the total number of unique servers they have played on, only including players who have played on two or more different servers. Also show the titles of all games they've played sessions on.

[Assistant]
SELECT p.username, COUNT(DISTINCT gs.server_id) AS unique_servers, STRING_AGG(DISTINCT g.title, ', ') AS game_titles
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
JOIN gaming_technology.servers s ON gs.server_id = s.server_id
JOIN gaming_technology.games g ON gs.game_id = g.game_id
WHERE gs.server_id IS NOT NULL
GROUP BY p.player_id
HAVING COUNT(DISTINCT gs.server_id) >= 2;

[User] Add another column for the total duration in seconds that each player has spent on these servers.

[Assistant]
SELECT p.username, COUNT(DISTINCT gs.server_id) AS unique_servers, STRING_AGG(DISTINCT g.title, ', ') AS game_titles, SUM(gs.duration_seconds) AS total_duration_seconds
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
JOIN gaming_technology.servers s ON gs.server_id = s.server_id
JOIN gaming_technology.games g ON gs.game_id = g.game_id
WHERE gs.server_id IS NOT NULL
GROUP BY p.player_id
HAVING COUNT(DISTINCT gs.server_id) >= 2;


[User] For each premium payment, list all previous payments made by the same customer. Show customer_id, previous_payment_id, previous_payment_date, current_payment_id, current_payment_date, and amount difference.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS previous_payment_id,
       p1.payment_date AS previous_payment_date,
       p2.payment_id AS current_payment_id,
       p2.payment_date AS current_payment_date,
       p2.amount_paid - p1.amount_paid AS amount_diff
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
  AND p1.payment_date < p2.payment_date;

[User] Actually, only include pairs where the current payment date is in 2024.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS previous_payment_id,
       p1.payment_date AS previous_payment_date,
       p2.payment_id AS current_payment_id,
       p2.payment_date AS current_payment_date,
       p2.amount_paid - p1.amount_paid AS amount_diff
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
  AND p1.payment_date < p2.payment_date
WHERE p2.payment_date BETWEEN '2024-01-01' AND '2024-12-31';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )


[User] Show the route number and description for routes that have bookings associated with them.

[Assistant] SELECT DISTINCT T1.route_number, T1.description FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id;

[User] For these routes, what is the average fare of the associated bookings?

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number;

[User] Also, only include routes where the average fare is greater than 75.

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number HAVING AVG(T2.fare) > 75;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, 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.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] Retrieve the names of all properties that have listed room types, along with the name of each room type available at that property.

[Assistant] SELECT t1.property_name, t2.type_name FROM hospitality_technology.properties AS t1 INNER JOIN hospitality_technology.room_types AS t2 ON t1.property_id = t2.property_id;

[User] Now, filter this list to only include room types with a base rate above 300.

[Assistant] SELECT t1.property_name, t2.type_name FROM hospitality_technology.properties AS t1 INNER JOIN hospitality_technology.room_types AS t2 ON t1.property_id = t2.property_id WHERE t2.base_rate > 300;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.payments ( payment_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, bill_id character varying(64), amount numeric(12,2) NOT NULL, currency_code character varying(3) NOT NULL, payment_method character varying(50) NOT NULL, card_type character varying(50), card_last_four character varying(4), transaction_ref character varying(128), payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, status character varying(50) NOT NULL, staff_id_processed character varying(64), notes text, PRIMARY KEY (payment_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)


[User] Show me the top 5 users who have interacted with DApps, along with the count of distinct DApps they interacted with and their wallet addresses.

[Assistant] SELECT w.user_id, COUNT(DISTINCT d.dapp_id) AS dapp_count, w.address FROM trading_platform.wallets w JOIN trading_platform.dapps d ON 1=1 GROUP BY w.user_id, w.address ORDER BY dapp_count DESC LIMIT 5;

[User] This query doesn't properly show DApp interactions. Please modify it to correctly join with a table that records user-DApp interactions.

[Assistant] I notice there's no interaction table in the provided schema. Without a table recording user-DApp interactions, I cannot generate this query accurately. Would you like to see users who have wallets and DApps separately instead?

[User] You're right. Instead, show me users who have wallets but have never interacted with any DApps, along with their wallet addresses.

[Assistant] SELECT w.user_id, w.address FROM trading_platform.wallets w WHERE NOT EXISTS (SELECT 1 FROM trading_platform.dapps d WHERE 1=1) GROUP BY w.user_id, w.address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
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) )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )