[User] Show the payment_id and amount_paid for all premium payments where the status is 'pending'.

[Assistant]
SELECT payment_id, amount_paid
FROM insurance.premium_payments
WHERE status = 'pending';

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.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, 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] List all appointment IDs and their corresponding location IDs for appointments that have status 'cancelled'.

[Assistant] SELECT appointment_id, location_id FROM healthcare.appointments WHERE status = 'cancelled';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )


[User] List the names of services and the total number of times each service has been ordered. Only include services that have been ordered at least once.

[Assistant] SELECT T1.service_name, count(T2.order_id) AS order_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.service_orders AS T2 ON T1.service_id = T2.service_id GROUP BY T1.service_name;

[User] Now, filter this list to only show services from the 'Food & Beverage' or 'Activities' categories, and sort by the order count in descending order.

[Assistant] SELECT T1.service_name, count(T2.order_id) AS order_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.service_orders AS T2 ON T1.service_id = T2.service_id WHERE T1.category IN ('Food & Beverage', 'Activities') GROUP BY T1.service_name ORDER BY order_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 hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.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, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Find pairs of distinct routes that share the same destination location but start from different origins. Include the route ID and route number for both routes and the shared destination 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.destination_location_id AS shared_destination_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.destination_location_id = r2.destination_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.origin_location_id != r2.origin_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] For each developer, can you find the next developer in the same country using a self join, returning developer_ids and names?

[Assistant]
SELECT d1.developer_id   AS current_dev,
       d1.name           AS current_name,
       d2.developer_id   AS next_dev,
       d2.name           AS next_name,
       d2.founded_year - d1.founded_year AS years_diff
FROM developers d1
JOIN developers d2
  ON d1.country = d2.country
  AND d2.founded_year > d1.founded_year;

[User] Exclude developers who don't have a next developer, and ensure we only pick the closest next by founded_year.

[Assistant]
SELECT d1.developer_id   AS current_dev,
       d1.name           AS current_name,
       d2.developer_id   AS next_dev,
       d2.name           AS next_name,
       d2.founded_year - d1.founded_year AS years_diff
FROM developers d1
JOIN LATERAL (
  SELECT d2.developer_id, d2.name, d2.founded_year
  FROM developers d2
  WHERE d2.country = d1.country
    AND d2.founded_year > d1.founded_year
  ORDER BY d2.founded_year ASC
  LIMIT 1
) d2 ON true;

[User] Finally, only include pairs where the difference in founded years is at most 5 years.

[Assistant]
SELECT d1.developer_id   AS current_dev,
       d1.name           AS current_name,
       d2.developer_id   AS next_dev,
       d2.name           AS next_name,
       d2.founded_year - d1.founded_year AS years_diff
FROM developers d1
JOIN LATERAL (
  SELECT d2.developer_id, d2.name, d2.founded_year
  FROM developers d2
  WHERE d2.country = d1.country
    AND d2.founded_year > d1.founded_year
  ORDER BY d2.founded_year ASC
  LIMIT 1
) d2 ON true
WHERE (d2.founded_year - d1.founded_year) <= 5
ORDER BY d1.developer_id, years_diff ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )


[User] How many conversations are group chats?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )


[User] List the first name, last name, and date of birth for all citizens born before January 1, 1995.

[Assistant] SELECT first_name, last_name, date_of_birth FROM government_services.citizens WHERE date_of_birth < '1995-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 government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)


[User] Find managers who have at least one agent reporting to them whose status is 'inactive'. List the manager's full name and the full name of the inactive agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Could you also include the inactive agent's termination date in the results?

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Filter the results to only include cases where the manager is currently 'active'.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive' AND T2.status = 'active'

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.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )


[User] Give me the total number of reservations and the sum of total_amount by month for the year 2023.

[Assistant]
SELECT DATE_TRUNC('month', check_in_date) AS month,
       COUNT(*)                         AS reservation_count,
       SUM(total_amount)               AS total_revenue
FROM hospitality_technology.reservations
WHERE EXTRACT(YEAR FROM check_in_date) = 2023
GROUP BY DATE_TRUNC('month', check_in_date)
ORDER BY month;

[User] Actually, I only want reservations with status 'CheckedOut' or 'Completed'.

[Assistant]
SELECT DATE_TRUNC('month', check_in_date) AS month,
       COUNT(*)                         AS reservation_count,
       SUM(total_amount)               AS total_revenue
FROM hospitality_technology.reservations
WHERE EXTRACT(YEAR FROM check_in_date) = 2023
  AND status IN ('CheckedOut', 'Completed')
GROUP BY DATE_TRUNC('month', check_in_date)
ORDER BY month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )


[User] List all completed appointments in the last week, showing patient_id, doctor_id and appointment_time.

[Assistant] SELECT patient_id, doctor_id, appointment_time FROM healthcare.appointments WHERE status = 'Completed' AND appointment_time >= (current_date - interval '7 days');

[User] Actually, I need to see only appointments that lasted more than 15 minutes.

[Assistant] SELECT patient_id, doctor_id, appointment_time FROM healthcare.appointments WHERE status = 'Completed' AND appointment_time >= (current_date - interval '7 days') AND duration_minutes > 15;

[User] Can you also sort them by appointment_time in descending order?

[Assistant] SELECT patient_id, doctor_id, appointment_time FROM healthcare.appointments WHERE status = 'Completed' AND appointment_time >= (current_date - interval '7 days') AND duration_minutes > 15 ORDER BY appointment_time DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)


[User] Show the total transaction amount for each customer, including their full name and risk profile. Join customers to accounts and then to transactions.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile;

[User] Filter this report to only include transactions from the last 90 days.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
WHERE
  T1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile;

[User] Also, only include customers whose total transaction amount in this period exceeds 1000.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
WHERE
  T1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile
HAVING
  SUM(T1.amount) > 1000;

[User] Sort the results by total transaction amount in descending order and limit to the top 10 customers.

[Assistant]
SELECT
  T2.first_name,
  T2.last_name,
  T2.risk_profile,
  SUM(T1.amount) AS total_transaction_amount
FROM financial_services.transactions AS T1
INNER JOIN financial_services.accounts AS T3
  ON T1.account_id = T3.account_id
INNER JOIN financial_services.customers AS T2
  ON T3.customer_id = T2.customer_id
WHERE
  T1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY
  T2.customer_id,
  T2.first_name,
  T2.last_name,
  T2.risk_profile
HAVING
  SUM(T1.amount) > 1000
ORDER BY
  total_transaction_amount DESC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.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.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees (
    employee_id 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] Show the policy number, start date, and the first and last name of the agent for all policies that started in 2024.

[Assistant]
SELECT p.policy_number, p.start_date, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.policies p
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE p.start_date >= '2024-01-01' AND p.start_date < '2025-01-01';

[User] Also include the status of each policy and only show those where the policy's premium_amount is over 3000.

[Assistant]
SELECT p.policy_number, p.start_date, a.first_name AS agent_first_name, a.last_name AS agent_last_name, p.status, p.premium_amount
FROM insurance.policies p
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE p.start_date >= '2024-01-01' AND p.start_date < '2025-01-01' AND p.premium_amount > 3000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, 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] What is the maintenance schedule for the platforms at the station with ID 'ST234' for the next month?

[Assistant] I'm sorry, but I don't have access to the maintenance schedule for the platforms at any station. The data I have only includes basic station information such as station ID, name, location, and number of platforms. For maintenance schedules, you may need to contact the station management or relevant authorities.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id text PRIMARY KEY, station_name text, city text, state_province text, country_code text, address text, timezone text, number_of_platforms int, created_at timestamp, last_updated_at timestamp )


[User] I need to get the earliest and latest fuel log entries for each vehicle, including their timestamps and the cost difference between those entries.

[Assistant]
WITH earliest AS (
  SELECT vehicle_id,
         fuel_log_id   AS earliest_log_id,
         log_timestamp AS earliest_ts,
         total_cost    AS earliest_cost,
         odometer_reading AS earliest_odo
  FROM transportation.fuel_logs fl1
  WHERE log_timestamp = (
    SELECT MIN(log_timestamp)
    FROM transportation.fuel_logs fl2
    WHERE fl2.vehicle_id = fl1.vehicle_id
  )
), latest AS (
  SELECT vehicle_id,
         fuel_log_id   AS latest_log_id,
         log_timestamp AS latest_ts,
         total_cost    AS latest_cost,
         odometer_reading AS latest_odo
  FROM transportation.fuel_logs fl1
  WHERE log_timestamp = (
    SELECT MAX(log_timestamp)
    FROM transportation.fuel_logs fl2
    WHERE fl2.vehicle_id = fl1.vehicle_id
  )
)
SELECT e.vehicle_id,
       e.earliest_log_id,
       e.earliest_ts,
       l.latest_log_id,
       l.latest_ts,
       (l.latest_cost - e.earliest_cost) AS cost_difference
FROM earliest e
JOIN latest l
  ON e.vehicle_id = l.vehicle_id;

[User] Can you refine it to only show vehicles where the odometer reading increased by more than 1000 miles between those entries?

[Assistant]
WITH earliest AS (
  SELECT vehicle_id,
         fuel_log_id   AS earliest_log_id,
         log_timestamp AS earliest_ts,
         total_cost    AS earliest_cost,
         odometer_reading AS earliest_odo
  FROM transportation.fuel_logs fl1
  WHERE log_timestamp = (
    SELECT MIN(log_timestamp)
    FROM transportation.fuel_logs fl2
    WHERE fl2.vehicle_id = fl1.vehicle_id
  )
), latest AS (
  SELECT vehicle_id,
         fuel_log_id   AS latest_log_id,
         log_timestamp AS latest_ts,
         total_cost    AS latest_cost,
         odometer_reading AS latest_odo
  FROM transportation.fuel_logs fl1
  WHERE log_timestamp = (
    SELECT MAX(log_timestamp)
    FROM transportation.fuel_logs fl2
    WHERE fl2.vehicle_id = fl1.vehicle_id
  )
)
SELECT e.vehicle_id,
       e.earliest_log_id,
       e.earliest_ts,
       l.latest_log_id,
       l.latest_ts,
       (l.latest_cost - e.earliest_cost) AS cost_difference
FROM earliest e
JOIN latest l
  ON e.vehicle_id = l.vehicle_id
WHERE (l.latest_odo - e.earliest_odo) > 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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 me all trips that were completed with a passenger count greater than 15, including their route and vehicle details.

[Assistant] SELECT t.trip_id, t.route_id, t.vehicle_id, t.driver_id, t.scheduled_departure, t.actual_departure, t.scheduled_arrival, t.actual_arrival, t.origin_location_id, t.destination_location_id, t.passenger_count FROM transportation.trips t WHERE t.status = 'completed' AND t.passenger_count > 15;

[User] Can you also include the difference between scheduled and actual departure time in minutes for these trips, and order them by this difference in descending order?

[Assistant] SELECT t.trip_id, t.route_id, t.vehicle_id, t.driver_id, t.scheduled_departure, t.actual_departure, EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 AS departure_delay_minutes, t.scheduled_arrival, t.actual_arrival, t.origin_location_id, t.destination_location_id, t.passenger_count FROM transportation.trips t WHERE t.status = 'completed' AND t.passenger_count > 15 ORDER BY departure_delay_minutes DESC;

[User] Now filter these results to only show trips where the departure delay was more than 30 minutes.

[Assistant] SELECT t.trip_id, t.route_id, t.vehicle_id, t.driver_id, t.scheduled_departure, t.actual_departure, EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 AS departure_delay_minutes, t.scheduled_arrival, t.actual_arrival, t.origin_location_id, t.destination_location_id, t.passenger_count FROM transportation.trips t WHERE t.status = 'completed' AND t.passenger_count > 15 AND EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure))/60 > 30 ORDER BY departure_delay_minutes 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.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 )


[User] Show me all securities (security_id, ticker_symbol, security_name) that are traded on the NASDAQ exchange and have a daily trading volume exceeding 1 million shares, along with the account details (account_id, account_number, balance) of customers who hold these securities in their accounts.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance FROM financial_services.securities s JOIN financial_services.market_data md ON s.security_id = md.security_id JOIN financial_services.accounts a ON s.currency = a.currency WHERE s.exchange = 'NASDAQ' AND md.volume > 1000000 AND a.status = 'Open' GROUP BY s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance;

[User] Now modify the query to only include accounts with a balance greater than $50,000 and sort them by balance in descending order.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance FROM financial_services.securities s JOIN financial_services.market_data md ON s.security_id = md.security_id JOIN financial_services.accounts a ON s.currency = a.currency WHERE s.exchange = 'NASDAQ' AND md.volume > 1000000 AND a.status = 'Open' AND a.balance > 50000 GROUP BY s.security_id, s.ticker_symbol, s.security_name, a.account_id, a.account_number, a.balance ORDER BY a.balance DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.securities ( security_id text, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.market_data ( data_point_id bigint, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )


[User] Show me all lawyers' full names, their bar number, and if they are partners, the full name of another partner from their firm.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1;

[User] Only include lawyers who have an email address specified.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '';

[User] Actually, restrict it to lawyers hired in or after 2023.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '' AND l1.hire_date >= '2023-01-01';

[User] Sort the results by the lawyer's last name in descending order.

[Assistant]
SELECT l1.first_name || ' ' || l1.last_name AS lawyer_full_name, l1.bar_number,
       CASE WHEN l1.is_partner = TRUE THEN (
           SELECT l2.first_name || ' ' || l2.last_name
           FROM legal_services.lawyers l2
           WHERE l2.firm_id = l1.firm_id AND l2.is_partner = TRUE AND l2.lawyer_id <> l1.lawyer_id
           LIMIT 1
       ) ELSE NULL END AS another_partner_full_name
FROM legal_services.lawyers l1
WHERE l1.email IS NOT NULL AND l1.email <> '' AND l1.hire_date >= '2023-01-01'
ORDER BY l1.last_name DESC;

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


[User] Show the first name, last name, and email of customers who have filed a claim, along with the status and estimated loss of each claim.

[Assistant] SELECT T1.first_name, T1.last_name, T1.email, T2.status, T2.estimated_loss FROM insurance.customers AS T1 INNER JOIN insurance.claims AS T2 ON T1.customer_id = T2.customer_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 insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] For each chain, which token had the highest number of smart money addresses buying it this week? Show the token symbol and narrative too.

[Assistant] SELECT chain, token_symbol, narrative, MAX(address_amount) AS max_buyers FROM smart_money_token_inflow WHERE type = 1 AND DATE_TRUNC('week', CURRENT_DATE) = DATE_TRUNC('week', CURRENT_DATE) GROUP BY chain, token_symbol, narrative;

[User] I got an error, I think the filter for the week may be wrong. Please revise the query so that it only counts buys from the current week.

[Assistant] SELECT chain, token_symbol, narrative, address_amount AS buyers FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(week FROM CURRENT_DATE) = EXTRACT(week FROM CURRENT_DATE) AND EXTRACT(year FROM CURRENT_DATE) = EXTRACT(year FROM CURRENT_DATE) ORDER BY chain, buyers 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 smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )


[User] List the usernames and full names of users who created their account in 2024 and are verified.

[Assistant] SELECT username, full_name FROM social_media.users WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01' AND is_verified = true;

[User] Also include their email address and location.

[Assistant] SELECT username, full_name, email, location FROM social_media.users WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01' AND is_verified = true;

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


[User] What are the maintenance costs for a specific aircraft model like the Airbus A320?

[Assistant] I'm sorry, but I don't have access to data regarding maintenance costs for specific aircraft models such as the Airbus A320. The information in the database is limited to details like model name, manufacturer, passenger capacity, and technical specifications. For maintenance cost information, you may need to consult with the manufacturer or a maintenance service provider.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id character varying(64) NOT NULL, model_name character varying(128) NOT NULL, manufacturer character varying(128) NOT NULL, passenger_capacity integer, max_range_km integer, engine_type character varying(100), wingspan_m numeric(6,2), status character varying(50) NOT NULL, first_flight_date date, PRIMARY KEY (model_id) )


[User] List all guests who have communication consent enabled along with their email addresses.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email
FROM guests
WHERE communication_consent = TRUE;

[User] Now only include those guests who also have a loyalty_member_id.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email,
       loyalty_member_id
FROM guests
WHERE communication_consent = TRUE
  AND loyalty_member_id IS NOT NULL;

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


[User] Show me all reservations with more than 2 adults that are confirmed (status = 'Confirmed'), including their check-in dates and total amounts, along with the guest's first and last name.

[Assistant] SELECT r.reservation_id, r.check_in_date, r.total_amount, g.first_name, g.last_name FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id WHERE r.num_adults > 2 AND r.status = 'Confirmed';

[User] Now, join this with the room_types table to include the room type name and base rate for each reservation.

[Assistant] SELECT r.reservation_id, r.check_in_date, r.total_amount, g.first_name, g.last_name, rt.type_name, rt.base_rate FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.status = 'Confirmed';

[User] The query should also show the difference between the total amount and the base rate for each reservation.

[Assistant] SELECT r.reservation_id, r.check_in_date, r.total_amount, g.first_name, g.last_name, rt.type_name, rt.base_rate, (r.total_amount - rt.base_rate) AS rate_difference FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.status = 'Confirmed';

[User] Actually, I only need reservations where the total amount is at least 50% higher than the base rate, and order them by check-in date in descending order.

[Assistant] SELECT r.reservation_id, r.check_in_date, r.total_amount, g.first_name, g.last_name, rt.type_name, rt.base_rate, (r.total_amount - rt.base_rate) AS rate_difference FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.status = 'Confirmed' AND r.total_amount >= rt.base_rate * 1.5 ORDER BY r.check_in_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 hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.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.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )


[User] List all review IDs, comments, and overall ratings for reviews submitted for property 'P123'.

[Assistant] SELECT review_id, comment, rating_overall FROM hospitality_technology.reviews WHERE property_id = 'P123';

[User] Filter this list to only include reviews with an overall rating of 3 or less and order by review date descending.

[Assistant] SELECT review_id, comment, rating_overall FROM hospitality_technology.reviews WHERE property_id = 'P123' AND rating_overall <= 3 ORDER BY review_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 hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )


[User] Count how many posts have media attachments.

[Assistant] SELECT count(*) FROM social_media.posts WHERE media_url IS NOT NULL

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, 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 bool )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )


[User] For each route, list the route_number, origin city, destination city, and the total fare collected from completed bookings.

[Assistant]
SELECT
    r.route_number,
    lo.city     AS origin_city,
    ld.city     AS destination_city,
    SUM(b.fare) AS total_fare
FROM transportation.routes r
JOIN transportation.locations lo ON r.origin_location_id = lo.location_id
JOIN transportation.locations ld ON r.destination_location_id = ld.location_id
JOIN transportation.trips t ON t.route_id = r.route_id
JOIN transportation.bookings b ON b.trip_id = t.trip_id
WHERE b.status = 'Completed'
GROUP BY r.route_number, lo.city, ld.city;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text, 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.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.passengers (
    passenger_id 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)
)
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] Show the latest version number of each document_name for every case.

[Assistant]
SELECT case_id,
       document_name,
       MAX(version) AS latest_version
FROM legal_services.documents
GROUP BY case_id, document_name;

[User] Actually, I also need the upload_timestamp of that latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

[User] Also include the uploaded_by_lawyer_id for each latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp,
       d.uploaded_by_lawyer_id
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )


[User] List the total number of 'login' and 'logout' actions per user.

[Assistant] SELECT user_id, SUM(CASE WHEN action = 'login' THEN 1 ELSE 0 END) AS login_count, SUM(CASE WHEN action = 'logout' THEN 1 ELSE 0 END) AS logout_count FROM trading_platform.logs GROUP BY user_id;

[User] Only include users who have at least one login and one logout action.

[Assistant] SELECT user_id, SUM(CASE WHEN action = 'login' THEN 1 ELSE 0 END) AS login_count, SUM(CASE WHEN action = 'logout' THEN 1 ELSE 0 END) AS logout_count FROM trading_platform.logs GROUP BY user_id HAVING SUM(CASE WHEN action = 'login' THEN 1 ELSE 0 END) > 0 AND SUM(CASE WHEN action = 'logout' THEN 1 ELSE 0 END) > 0;

[User] Also, show the timestamp of their first login and their last logout.

[Assistant] SELECT fl.user_id, fl.first_login, lo.last_logout FROM (SELECT user_id, MIN(logged_at) AS first_login FROM trading_platform.logs WHERE action = 'login' GROUP BY user_id) fl JOIN (SELECT user_id, MAX(logged_at) AS last_logout FROM trading_platform.logs WHERE action = 'logout' GROUP BY user_id) lo ON fl.user_id = lo.user_id;

[User] Sort the results by the number of logout actions descending and limit to the top 5 users.

[Assistant] SELECT c.user_id, c.logout_count, fl.first_login, lo.last_logout FROM (SELECT user_id, COUNT(*) AS logout_count FROM trading_platform.logs WHERE action = 'logout' GROUP BY user_id) c JOIN (SELECT user_id, MIN(logged_at) AS first_login FROM trading_platform.logs WHERE action = 'login' GROUP BY user_id) fl ON c.user_id = fl.user_id JOIN (SELECT user_id, MAX(logged_at) AS last_logout FROM trading_platform.logs WHERE action = 'logout' GROUP BY user_id) lo ON c.user_id = lo.user_id ORDER BY c.logout_count DESC LIMIT 5;

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


[User] Get the appointment details including appointment_id, the full name of the citizen, the service name, and scheduled_start_time for all appointments booked via 'Phone', ordered by scheduled_start_time descending.

[Assistant]
SELECT a.appointment_id,
       c.first_name || ' ' || c.last_name AS citizen_name,
       s.service_name,
       a.scheduled_start_time
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE a.booking_method = 'Phone'
ORDER BY a.scheduled_start_time 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 government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.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, 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 character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] List each citizen's first and last name along with the number of applications they have submitted, only include those with at least 3 applications.

[Assistant]
SELECT c.first_name, c.last_name, COUNT(a.application_id) AS application_count
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
GROUP BY c.first_name, c.last_name
HAVING COUNT(a.application_id) >= 3;

[User] Now also show the average standard fee of the services those applications are associated with.

[Assistant]
SELECT c.first_name, c.last_name, COUNT(a.application_id) AS application_count, AVG(s.standard_fee) AS avg_service_fee
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
GROUP BY c.first_name, c.last_name
HAVING COUNT(a.application_id) >= 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.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.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.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 )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )


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

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


[User] How many notifications are there where the sender user ID is not recorded?

[Assistant] SELECT COUNT(*) FROM social_media.notifications WHERE sender_user_id IS NULL

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] Find tokens that appear in both the smart money token performance and the smart money token inflow tables. List the token symbol, chain, the PNL from the performance table, and the total USD value from all corresponding inflow records.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.pnl, SUM(T2.usd_value) AS total_usd_inflow FROM smart_money_token_performance AS T1 JOIN smart_money_token_inflow AS T2 ON T1.token_symbol = T2.token_symbol AND T1.chain = T2.chain GROUP BY T1.token_symbol, T1.chain, T1.pnl

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )


[User] For each group chat, list its ID, name, creation time, and the creation time of the next group chat created after it, ordered by creation time.

[Assistant] SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ORDER BY created_at;

[User] Only show pairs where the next group chat was created within 48 hours of the current one, and also include the time difference in hours.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 ORDER BY created_at;

[User] Further refine: Only include group chats whose names contain 'Discuss'.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 AND group_name LIKE '%Discuss%' ORDER BY created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )


[User] What are the personal contact details of the staff member associated with staff_id 'STAFF789' who worked on a specific maintenance record?

[Assistant] I'm sorry, but I can't provide personal contact details of staff members as this information is not stored in the maintenance_records table and is outside the scope of the available data.

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


[User] List each username with how many users they follow and how many users follow them.

[Assistant]
SELECT u.username,
       COALESCE(following.following_count, 0) AS following_count,
       COALESCE(followers.followers_count, 0) AS followers_count
FROM social_media.users u
LEFT JOIN (
  SELECT follower_user_id, COUNT(*) AS following_count
  FROM social_media.follows
  GROUP BY follower_user_id
) AS following
  ON u.user_id = following.follower_user_id
LEFT JOIN (
  SELECT following_user_id, COUNT(*) AS followers_count
  FROM social_media.follows
  GROUP BY following_user_id
) AS followers
  ON u.user_id = followers.following_user_id;

[User] Also include only those users who follow more people than follow them.

[Assistant]
SELECT u.username,
       COALESCE(following.following_count, 0) AS following_count,
       COALESCE(followers.followers_count, 0) AS followers_count
FROM social_media.users u
LEFT JOIN (
  SELECT follower_user_id, COUNT(*) AS following_count
  FROM social_media.follows
  GROUP BY follower_user_id
) AS following
  ON u.user_id = following.follower_user_id
LEFT JOIN (
  SELECT following_user_id, COUNT(*) AS followers_count
  FROM social_media.follows
  GROUP BY following_user_id
) AS followers
  ON u.user_id = followers.following_user_id
WHERE COALESCE(following.following_count, 0) > COALESCE(followers.followers_count, 0);

[User] Sort the results by the difference between following_count and followers_count in descending order, and alias this difference as difference_count.

[Assistant]
SELECT u.username,
       COALESCE(following.following_count, 0) AS following_count,
       COALESCE(followers.followers_count, 0) AS followers_count,
       (COALESCE(following.following_count, 0) - COALESCE(followers.followers_count, 0)) AS difference_count
FROM social_media.users u
LEFT JOIN (
  SELECT follower_user_id, COUNT(*) AS following_count
  FROM social_media.follows
  GROUP BY follower_user_id
) AS following
  ON u.user_id = following.follower_user_id
LEFT JOIN (
  SELECT following_user_id, COUNT(*) AS followers_count
  FROM social_media.follows
  GROUP BY following_user_id
) AS followers
  ON u.user_id = followers.following_user_id
WHERE (COALESCE(following.following_count, 0) - COALESCE(followers.followers_count, 0)) > 0
ORDER BY difference_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, 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 bool )
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 text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )


[User] How many messages in total have been sent that do not contain any media attachment?

[Assistant]
SELECT COUNT(*) AS non_media_message_count
FROM social_media.messages
WHERE media_url IS NULL OR media_url = '';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )


[User] Show me all patients who have both a primary insurance plan and at least one completed appointment, along with their insurance policy numbers and the count of appointments.

[Assistant] SELECT p.patient_id, p.first_name, p.last_name, pi.policy_number, COUNT(a.appointment_id) AS appointment_count FROM healthcare.patients p JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true JOIN healthcare.appointments a ON p.patient_id = a.patient_id AND a.status = 'Completed' GROUP BY p.patient_id, p.first_name, p.last_name, pi.policy_number HAVING COUNT(a.appointment_id) >= 1;

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.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
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] For each citizen who has made at least one payment, show the citizen's full name, number of payments, and total amount paid, grouped by currency.

[Assistant]
SELECT
  c.first_name || ' ' || c.last_name AS full_name,
  p.currency,
  COUNT(*) AS payment_count,
  SUM(p.amount) AS total_amount
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
GROUP BY full_name, p.currency;

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.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )


[User] For each user, list all pairs of read and unread notifications, showing the recipient_user_id, the unread notification_id and type, and the read notification_id and type.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL;

[User] Actually, only include pairs where the unread notification_type is 'message'.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL
  AND n_unread.notification_type = 'message';

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.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )