System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id.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] What is the average interest rate for loans of type 'Mortgage'?

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage'

[User] Refine this to only include loans with status 'Active'.

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage' AND status = 'Active'

[User] Show me the total principal amount for each loan type, along with the count of loans and average monthly payment, but only for loans originated in the last 5 years.

[Assistant] SELECT loan_type, SUM(principal_amount) AS total_principal, COUNT(loan_id) AS loan_count, AVG(monthly_payment) AS avg_monthly_payment FROM financial_services.loans WHERE origination_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY loan_type;

[User] Show me all loans with a term longer than 36 months, including their loan_id, account_id, and principal_amount.

[Assistant] SELECT loan_id, account_id, principal_amount FROM financial_services.loans WHERE term_months > 36;

[User] Can you also include their origination_date and current_principal_balance?

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36;

[User] Filter to only show loans that are not yet matured (maturity_date > CURRENT_DATE).

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36 AND maturity_date > CURRENT_DATE;

[User] For each loan type, show the total outstanding principal balance and the number of active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type;

[User] Sort the result by total_outstanding_balance in ascending order.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type ORDER BY total_outstanding_balance ASC;

[User] Only include loan types where there are more than 10 active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type HAVING COUNT(*) > 10 ORDER BY total_outstanding_balance ASC;

[User] Show all loans with a maturity date in the next 60 days, along with their account_id, principal_amount, interest_rate, and maturity_date.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] Only include loans where the status is not 'CLOSED' or 'PAID_OFF'.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] Also, display the loan_type in the result.

[Assistant] SELECT loan_id, account_id, loan_type, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] What is the average interest rate for auto loans (loan_type = 'Auto') with a principal amount between $20,000 and $50,000?

[Assistant] SELECT AVG(interest_rate) AS avg_interest_rate FROM financial_services.loans WHERE loan_type = 'Auto' AND principal_amount BETWEEN 20000 AND 50000;

[User] List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);

[User] Show me all active loans (loan_id, loan_type, principal_amount) where the remaining term is less than 6 months, along with their account_id and monthly_payment.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, monthly_payment FROM financial_services.loans WHERE status = 'Active' AND (maturity_date - CURRENT_DATE) < 180;

[User] Now modify the query to only include home loans (loan_type = 'Home') and sort them by remaining term in ascending order.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, monthly_payment, (maturity_date - CURRENT_DATE) AS remaining_days FROM financial_services.loans WHERE status = 'Active' AND loan_type = 'Home' AND (maturity_date - CURRENT_DATE) < 180 ORDER BY remaining_days ASC;

[User] For each loan, calculate the number of days until maturity. Display loan_id, account_id, maturity_date, and days_to_maturity as the difference between maturity_date and CURRENT_DATE.

[Assistant]
SELECT loan_id,
       account_id,
       maturity_date,
       (maturity_date - CURRENT_DATE) AS days_to_maturity
FROM financial_services.loans;

[User] Actually, only include loans where days_to_maturity is between 30 and 180 days.

[Assistant]
SELECT loan_id,
       account_id,
       maturity_date,
       (maturity_date - CURRENT_DATE) AS days_to_maturity
FROM financial_services.loans
WHERE (maturity_date - CURRENT_DATE) BETWEEN 30 AND 180;

[User] Finally, join to the accounts table to include account_type in the result.

[Assistant]
SELECT l.loan_id,
       l.account_id,
       a.account_type,
       l.maturity_date,
       (l.maturity_date - CURRENT_DATE) AS days_to_maturity
FROM financial_services.loans l
JOIN financial_services.accounts a
  ON l.account_id = a.account_id
WHERE (l.maturity_date - CURRENT_DATE) BETWEEN 30 AND 180;

[User] Show me a summary per loan_type with the minimum interest_rate, maximum interest_rate, and the average current_principal_balance.

[Assistant]
SELECT loan_type,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
GROUP BY loan_type;

[User] Only include loans that were originated on or after 2022-01-01.

[Assistant]
SELECT loan_type,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
WHERE origination_date >= DATE '2022-01-01'
GROUP BY loan_type;

[User] And restrict to loans with a term longer than 24 months.

[Assistant]
SELECT loan_type,
       MIN(interest_rate) AS min_interest_rate,
       MAX(interest_rate) AS max_interest_rate,
       AVG(current_principal_balance) AS avg_balance
FROM financial_services.loans
WHERE origination_date >= DATE '2022-01-01'
  AND term_months > 24
GROUP BY loan_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)

[User] For each claim, count the number of beneficiaries associated with its policy. Show claim_id and beneficiary_count, only for claims with more than 2 beneficiaries.

[Assistant]
SELECT c.claim_id, COUNT(pb.beneficiary_id) AS beneficiary_count
FROM insurance.claims c
JOIN insurance.policy_beneficiaries pb ON c.policy_id = pb.policy_id
GROUP BY c.claim_id
HAVING COUNT(pb.beneficiary_id) > 2;

[User] Now restrict the result to claims reported in 2023.

[Assistant]
SELECT c.claim_id, COUNT(pb.beneficiary_id) AS beneficiary_count
FROM insurance.claims c
JOIN insurance.policy_beneficiaries pb ON c.policy_id = pb.policy_id
WHERE c.reported_date >= '2023-01-01' AND c.reported_date < '2024-01-01'
GROUP BY c.claim_id
HAVING COUNT(pb.beneficiary_id) > 2;

[User] List all premium payments with the amount_paid exactly 1000, showing the payment_id and payment_date.

[Assistant]
SELECT payment_id, payment_date
FROM insurance.premium_payments
WHERE amount_paid = 1000;

[User] What is the average estimated_loss for each claim status?

[Assistant]
SELECT status, AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
GROUP BY status;

[User] Show the number of claims filed for each distinct status, ordered by the count in descending order.

[Assistant]
SELECT status, COUNT(*) AS claim_count
FROM insurance.claims
GROUP BY status
ORDER BY claim_count DESC;

[User] Show all premium payments along with the incident date and estimated loss of any associated claims for the same policy. List payment_id, amount_paid, payment_date, incident_date, and estimated_loss.

[Assistant] SELECT T1.payment_id, T1.amount_paid, T1.payment_date, T2.incident_date, T2.estimated_loss FROM insurance.premium_payments AS T1 LEFT JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id;

[User] Refine the results to only show payments for policies that have an associated claim with an estimated loss exceeding 10000.

[Assistant] SELECT T1.payment_id, T1.amount_paid, T1.payment_date, T2.incident_date, T2.estimated_loss FROM insurance.premium_payments AS T1 JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id WHERE T2.estimated_loss > 10000;

[User] How many agents are currently active in each license state?

[Assistant]
SELECT license_state, COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state;

[User] List each claim_handler_id along with the number of claims they've handled and the total settlement_amount they've paid out.

[Assistant]
SELECT claim_handler_id,
       COUNT(*) AS total_claims,
       SUM(settlement_amount) AS total_settlement
FROM insurance.claims
GROUP BY claim_handler_id;

[User] In addition, include the claim_id of the single claim with the highest settlement_amount for each handler.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

[User] Only include handlers who have managed at least 3 claims and have a non-null claim_handler_id.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

[User] Finally, sort the results by total_settlement in descending order.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  )
ORDER BY ag.total_settlement DESC;

[User] Calculate the average number of days between when an incident occurred and when the claim was reported, but only for claims that were settled in the year 2023.

[Assistant]
SELECT
  AVG(EXTRACT(EPOCH FROM (reported_date - incident_date)) / 86400.0)::numeric(10, 2)
FROM
  insurance.claims
WHERE
  settlement_date IS NOT NULL AND EXTRACT(YEAR FROM settlement_date) = 2023;

[User] List the claim ID, policy ID, reported date, and settlement date for claims that have been processed by a claim handler.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL;

[User] Actually, only show claims where the settlement date is not null as well.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL;

[User] Now, filter to only include claims settled after January 1, 2024.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01';

[User] Also, add a column showing the number of days between the reported date and the settlement date, and sort results by that column in descending order.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date,
       (settlement_date - reported_date::date) AS days_to_settle
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01'
ORDER BY days_to_settle DESC;

[User] What is the average estimated_loss for claims with status 'Filed' or 'Approved'?

[Assistant]
SELECT AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
WHERE status IN ('Filed', 'Approved');


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

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

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

[User] Find all customers whose email address ends with '@gmail.com'. Please show the customer_id, first name, and email.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com';

[User] Also, restrict this to only customers who are currently 'inactive'.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com' AND status = 'inactive';

[User] How many customers have a non-null phone number in your system?

[Assistant] SELECT COUNT(*) FROM insurance.customers WHERE phone_number IS NOT NULL;

[User] Which cities have more than 10 active customers in the state of Texas? Provide the city name and the customer count.

[Assistant]
SELECT city, COUNT(*) AS customer_count
FROM insurance.customers
WHERE state = 'TX' AND status = 'Active'
GROUP BY city
HAVING COUNT(*) > 10;

[User] How many customers were created in 2023?

[Assistant]
SELECT COUNT(*)
FROM insurance.customers
WHERE EXTRACT(YEAR FROM created_at) = 2023;

[User] Show me the full names and email addresses of all customers who registered after January 1st, 2024.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE created_at > '2024-01-01';

[User] I also want to see their city and state in the result.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01';

[User] Sort the output by the created_at timestamp, newest first.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Limit the result to the top 10 most recently registered customers.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC LIMIT 10;

[User] Show me a list of all customers from California along with their full names and phone numbers.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number FROM insurance.customers WHERE state = 'CA';

[User] Can you also include their email addresses in the results?

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA';

[User] Actually, show me only those customers whose status is 'active'.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA' AND status = 'active';

[User] List the first and last names, email, and phone number of all customers whose status is not 'Active'.

[Assistant]
SELECT first_name, last_name, email, phone_number
FROM insurance.customers
WHERE status <> 'Active';

[User] Now, only show those who live in the state of California.

[Assistant]
SELECT first_name, last_name, email, phone_number
FROM insurance.customers
WHERE status <> 'Active' AND state = 'CA';

[User] I got some records where the phone_number is missing. Please exclude customers with a NULL phone number.

[Assistant]
SELECT first_name, last_name, email, phone_number
FROM insurance.customers
WHERE status <> 'Active'
  AND state = 'CA'
  AND phone_number IS NOT NULL;

[User] Finally, sort the results by last_name ascending and limit the output to 20 records.

[Assistant]
SELECT first_name, last_name, email, phone_number
FROM insurance.customers
WHERE status <> 'Active'
  AND state = 'CA'
  AND phone_number IS NOT NULL
ORDER BY last_name ASC
LIMIT 20;

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

[Assistant] SELECT customer_id, first_name, last_name, created_at FROM insurance.customers WHERE state = 'NY' AND created_at < '2023-01-01';

[User] I need a list of customer pairs living in the same city, showing both customers' full names and the city.

[Assistant] SELECT c1.first_name || ' ' || c1.last_name AS customer1_name, c2.first_name || ' ' || c2.last_name AS customer2_name, c1.city FROM insurance.customers c1 JOIN insurance.customers c2 ON c1.city = c2.city AND c1.customer_id < c2.customer_id;

[User] Actually, only include pairs where the state is 'CA'.

[Assistant] SELECT c1.first_name || ' ' || c1.last_name AS customer1_name, c2.first_name || ' ' || c2.last_name AS customer2_name, c1.city FROM insurance.customers c1 JOIN insurance.customers c2 ON c1.city = c2.city AND c1.customer_id < c2.customer_id WHERE c1.state = 'CA' AND c2.state = 'CA';

[User] Also, make sure both customers are currently active.

[Assistant] SELECT c1.first_name || ' ' || c1.last_name AS customer1_name, c2.first_name || ' ' || c2.last_name AS customer2_name, c1.city FROM insurance.customers c1 JOIN insurance.customers c2 ON c1.city = c2.city AND c1.customer_id < c2.customer_id WHERE c1.state = 'CA' AND c2.state = 'CA' AND c1.status = 'Active' AND c2.status = 'Active';

[User] Finally, sort the results by city name ascending.

[Assistant] SELECT c1.first_name || ' ' || c1.last_name AS customer1_name, c2.first_name || ' ' || c2.last_name AS customer2_name, c1.city FROM insurance.customers c1 JOIN insurance.customers c2 ON c1.city = c2.city AND c1.customer_id < c2.customer_id WHERE c1.state = 'CA' AND c2.state = 'CA' AND c1.status = 'Active' AND c2.status = 'Active' ORDER BY c1.city ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] List all rooms that are currently marked as 'OutOfOrder' or 'Maintenance'. Show their room number and current status.

[Assistant] SELECT room_number, status FROM hospitality_technology.rooms WHERE status IN ('OutOfOrder', 'Maintenance');

[User] Add the property ID and floor number for these rooms, and sort the results by property ID then floor.

[Assistant] SELECT property_id, floor, room_number, status FROM hospitality_technology.rooms WHERE status IN ('OutOfOrder', 'Maintenance') ORDER BY property_id, floor;

[User] List all service orders, including the service name and quantity, along with the full name of the staff member who placed the order.

[Assistant] SELECT so.order_id, s.service_name, so.quantity, st.first_name, st.last_name FROM hospitality_technology.service_orders AS so JOIN hospitality_technology.services AS s ON so.service_id = s.service_id JOIN hospitality_technology.staff AS st ON so.staff_id_ordered = st.staff_id;

[User] Filter this list to only include orders placed by staff members with position 'Concierge'.

[Assistant] SELECT so.order_id, s.service_name, so.quantity, st.first_name, st.last_name FROM hospitality_technology.service_orders AS so JOIN hospitality_technology.services AS s ON so.service_id = s.service_id JOIN hospitality_technology.staff AS st ON so.staff_id_ordered = st.staff_id WHERE st.position = 'Concierge';

[User] Show me the list of all room numbers and their corresponding guest full names for current reservations (status is 'Occupied' or 'CheckedIn').

[Assistant]
SELECT r.room_number, g.first_name || ' ' || g.last_name AS guest_full_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
WHERE res.status IN ('Occupied', 'CheckedIn');

[User] Add the property name to the result and sort the list by property name, then by room number.

[Assistant]
SELECT p.property_name, r.room_number, g.first_name || ' ' || g.last_name AS guest_full_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE res.status IN ('Occupied', 'CheckedIn')
ORDER BY p.property_name, r.room_number;

[User] For properties located in the city 'Los Angeles', list all rooms that are on floor 3. Include the property name and room number.

[Assistant] SELECT p.property_name, r.room_number FROM hospitality_technology.properties p JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.city = 'Los Angeles' AND r.floor = 3;

[User] Further filter this list to only include rooms that are designated as smoking rooms.

[Assistant] SELECT p.property_name, r.room_number FROM hospitality_technology.properties p JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.city = 'Los Angeles' AND r.floor = 3 AND r.is_smoking = true;

[User] Sort the results by property name and then by room number, and limit to the first 20 entries.

[Assistant] SELECT p.property_name, r.room_number FROM hospitality_technology.properties p JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.city = 'Los Angeles' AND r.floor = 3 AND r.is_smoking = true ORDER BY p.property_name, r.room_number LIMIT 20;

[User] For each reservation in the last three months, show the reservation ID, check-in date, number of adults, and the corresponding room type name.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.created_at >= NOW() - INTERVAL '3 months';

[User] Also include the name of the property for each reservation.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '3 months';

[User] Sort the results by number of adults descending, and then by check-in date ascending.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '3 months'
ORDER BY r.num_adults DESC, r.check_in_date ASC;

[User] List the names and email addresses of guests who have made a reservation in the last 60 days.

[Assistant]
SELECT DISTINCT g.first_name, g.last_name, g.email
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
WHERE r.created_at >= NOW() - INTERVAL '60 days';

[User] Only show guests who have stayed at a property with a star rating of at least 4.

[Assistant]
SELECT DISTINCT g.first_name, g.last_name, g.email
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '60 days' AND p.star_rating >= 4;

[User] For each property, show the property_name, the total number of available services, and the average price of those services.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS total_available_services,
       AVG(s.price) AS avg_service_price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
WHERE s.is_available = TRUE
GROUP BY p.property_name;

[User] Now exclude properties that have zero available services and only include those with an average price greater than 50.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS total_available_services,
       AVG(s.price) AS avg_service_price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
WHERE s.is_available = TRUE
GROUP BY p.property_name
HAVING COUNT(s.service_id) > 0
   AND AVG(s.price) > 50;

[User] Also, restrict the services to only those in the 'Wellness' and 'Spa' departments.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS total_available_services,
       AVG(s.price) AS avg_service_price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
WHERE s.is_available = TRUE
  AND s.department IN ('Wellness', 'Spa')
GROUP BY p.property_name
HAVING COUNT(s.service_id) > 0
   AND AVG(s.price) > 50;

[User] List all service orders showing the order ID, service ID, quantity, and total price.

[Assistant] SELECT order_id, service_id, quantity, total_price FROM hospitality_technology.service_orders LIMIT 100;

[User] Only show orders with a status of 'Delivered' and sort by total price descending.

[Assistant] SELECT order_id, service_id, quantity, total_price FROM hospitality_technology.service_orders WHERE status = 'Delivered' ORDER BY total_price DESC;

[User] Show me the first name, last name, and position of all staff members, along with the name of the property they work at.

[Assistant] SELECT T1.first_name, T1.last_name, T1.position, T2.property_name FROM hospitality_technology.staff AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id;

[User] Only include staff who are currently active.

[Assistant] SELECT T1.first_name, T1.last_name, T1.position, T2.property_name FROM hospitality_technology.staff AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_active = true;

[User] Sort the results by property name and then by staff last name.

[Assistant] SELECT T1.first_name, T1.last_name, T1.position, T2.property_name FROM hospitality_technology.staff AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_active = true ORDER BY T2.property_name, T1.last_name;

[User] Show the property name, star rating, and number of rooms for each property.

[Assistant]
SELECT p.property_name, p.star_rating, COUNT(r.room_id) AS room_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r ON p.property_id = r.property_id
GROUP BY p.property_id, p.property_name, p.star_rating;

[User] Only include properties that have more than 30 rooms.

[Assistant]
SELECT p.property_name, p.star_rating, COUNT(r.room_id) AS room_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r ON p.property_id = r.property_id
GROUP BY p.property_id, p.property_name, p.star_rating
HAVING COUNT(r.room_id) > 30;

[User] Add a column showing the total number of unique room types at each property.

[Assistant]
SELECT p.property_name, p.star_rating, COUNT(r.room_id) AS room_count, COUNT(DISTINCT rt.room_type_id) AS unique_room_type_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r ON p.property_id = r.property_id
LEFT JOIN hospitality_technology.room_types rt ON p.property_id = rt.property_id
GROUP BY p.property_id, p.property_name, p.star_rating
HAVING COUNT(r.room_id) > 30;


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 train_station_management.platforms (
    platform_id character varying(64) NOT NULL, -- Unique identifier for the platform
    station_id character varying(64) NOT NULL, -- Foreign key referencing stations
    platform_number character varying(10) NOT NULL, -- Platform identifier (e.g., '1A', '5')
    track_number character varying(10), -- Associated track number, if different
    status character varying(32) NOT NULL DEFAULT 'Operational', -- e.g., Operational, Maintenance, Closed
    length_meters numeric(8,2), -- Length of the platform in meters
    accessible boolean NOT NULL DEFAULT false, -- Is the platform accessible (e.g., wheelchair)?
    PRIMARY KEY (platform_id),
    FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.trains (
    train_id character varying(64) NOT NULL, -- Unique identifier for the train set
    train_number character varying(32) NOT NULL, -- Operational number of the train (e.g., 'Acela 2151')
    model character varying(128), -- Model of the train (e.g., 'Siemens Velaro')
    manufacturer character varying(128), -- Manufacturer of the train
    year_manufactured integer, -- Year the train was built
    capacity integer NOT NULL, -- Total passenger capacity
    status character varying(32) NOT NULL DEFAULT 'Active', -- e.g., Active, Maintenance, Retired
    last_maintenance_date date, -- Date of last scheduled maintenance
    next_maintenance_date date, -- Date of next scheduled maintenance
    PRIMARY KEY (train_id),
    UNIQUE (train_number)
)
CREATE TABLE train_station_management.staff (
    staff_id character varying(64) NOT NULL, -- Unique identifier for the staff member
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    role character varying(64) NOT NULL, -- e.g., Station Master, Ticket Agent, Conductor, Engineer, Maintenance Crew
    primary_station_id character varying(64), -- Base station for the staff member (nullable for mobile staff)
    employee_number character varying(32) UNIQUE NOT NULL, -- Unique employee identifier
    hire_date date NOT NULL,
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    is_active boolean NOT NULL DEFAULT true, -- Is the staff member currently employed?
    PRIMARY KEY (staff_id),
    FOREIGN KEY (primary_station_id) REFERENCES train_station_management.stations(station_id)
)

[User] Can you provide the total number of active trains in the database?

[Assistant]
SELECT COUNT(*)
FROM train_station_management.trains
WHERE status = 'Active';

[User] Can you help me find all staff members assigned to a specific station with station_id 'STATION_002', along with their roles and the platform details at that station?

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.role, p.platform_id, p.platform_number, p.status, p.accessible
FROM train_station_management.staff s
JOIN train_station_management.platforms p ON s.primary_station_id = p.station_id
WHERE s.primary_station_id = 'STATION_002' AND s.is_active = true;

[User] Can you filter the results to show only staff with the role of 'Conductor' and platforms that are operational?

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.role, p.platform_id, p.platform_number, p.status, p.accessible
FROM train_station_management.staff s
JOIN train_station_management.platforms p ON s.primary_station_id = p.station_id
WHERE s.primary_station_id = 'STATION_002' AND s.is_active = true AND s.role = 'Conductor' AND p.status = 'Operational';

[User] Can you also sort the results by staff last name and platform number?

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.role, p.platform_id, p.platform_number, p.status, p.accessible
FROM train_station_management.staff s
JOIN train_station_management.platforms p ON s.primary_station_id = p.station_id
WHERE s.primary_station_id = 'STATION_002' AND s.is_active = true AND s.role = 'Conductor' AND p.status = 'Operational'
ORDER BY s.last_name, p.platform_number;

[User] Can you help me retrieve the details of all platforms at a specific station with station_id 'STATION_001', including the platform status and whether they are accessible?

[Assistant]
SELECT platform_id, platform_number, track_number, status, length_meters, accessible
FROM train_station_management.platforms
WHERE station_id = 'STATION_001';

[User] Can you also include the total number of platforms at this station in the result?

[Assistant]
SELECT platform_id, platform_number, track_number, status, length_meters, accessible,
       (SELECT COUNT(*) FROM train_station_management.platforms WHERE station_id = 'STATION_001') AS total_platforms
FROM train_station_management.platforms
WHERE station_id = 'STATION_001';

[User] Can you modify the query to filter only operational platforms and sort them by platform number?

[Assistant]
SELECT platform_id, platform_number, track_number, status, length_meters, accessible,
       (SELECT COUNT(*) FROM train_station_management.platforms WHERE station_id = 'STATION_001') AS total_platforms
FROM train_station_management.platforms
WHERE station_id = 'STATION_001' AND status = 'Operational'
ORDER BY platform_number;

[User] What is the schedule of trains arriving at platform 1A at station XYZ on December 25th, 2023?

[Assistant] I'm sorry, but I can't provide information about train schedules or specific arrival times as this data is not included in the platform management table. For train schedules, please refer to the train timetable or contact the station's customer service.

[User] What is the current number of passengers waiting at platform 2B at station ABC?

[Assistant] I'm sorry, but I can't provide information on the current number of passengers at a specific platform. The data in the platforms table only includes details like platform number, track number, status, length, and accessibility. For real-time passenger counts, you may need to refer to station monitoring systems or staff reports.

[User] Can you help me retrieve the details of all schedules for a specific train with train_id 'train_789', including the route and stops information?

[Assistant]
HGETALL train:train_789
SMEMBERS schedule:sched_*:train:train_789
HGETALL schedule:sched_*
HGETALL route:route_*
ZRANGE schedule:sched_*:stops 0 -1
HGETALL schedule_stop:stop_*

[User] Can you filter the schedules to only include those with a status of 'Scheduled'?

[Assistant]
HGETALL train:train_789
SMEMBERS schedule:sched_*:train:train_789
HGETALL schedule:sched_*
HGET schedule:sched_* status
IF status == 'Scheduled' THEN
HGETALL route:route_*
ZRANGE schedule:sched_*:stops 0 -1
HGETALL schedule_stop:stop_*
ENDIF

[User] Can you also include the departure datetime for each schedule in the result?

[Assistant]
HGETALL train:train_789
SMEMBERS schedule:sched_*:train:train_789
HGETALL schedule:sched_*
HGET schedule:sched_* status
HGET schedule:sched_* departure_datetime
IF status == 'Scheduled' THEN
HGETALL route:route_*
ZRANGE schedule:sched_*:stops 0 -1
HGETALL schedule_stop:stop_*
ENDIF

[User] I need to find all bookings for a specific schedule with schedule_id 'sched_1122' and include the passenger and ticket details.

[Assistant]
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:book_*
HGETALL passenger:pass_*
SMEMBERS booking:book_*:tickets
HGETALL ticket:tkt_*

[User] Can you filter the tickets to show only those that are not checked in?

[Assistant]
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:book_*
HGETALL passenger:pass_*
SMEMBERS booking:book_*:tickets
HGET ticket:tkt_* is_checked_in
IF is_checked_in == 0 THEN
HGETALL ticket:tkt_*
ENDIF

[User] Can you also include the car details for each ticket?

[Assistant]
SMEMBERS schedule:sched_1122:bookings
HGETALL booking:book_*
HGETALL passenger:pass_*
SMEMBERS booking:book_*:tickets
HGET ticket:tkt_* is_checked_in
IF is_checked_in == 0 THEN
HGETALL ticket:tkt_*
HGET ticket:tkt_* car_id
HGETALL car:car_*
ENDIF

[User] Can you provide the total number of cars associated with a specific train with train_id 'train_789'?

[Assistant] SCARD train:train_789:cars


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )

[User] Can you show me all pairs of customers living in the same city but with different last names? Show both customer IDs, both full names, and their city.

[Assistant] SELECT a.customer_id AS customer_id_a, CONCAT(a.first_name, ' ', a.last_name) AS full_name_a, b.customer_id AS customer_id_b, CONCAT(b.first_name, ' ', b.last_name) AS full_name_b, a.city FROM financial_services.customers a JOIN financial_services.customers b ON a.city = b.city AND a.last_name <> b.last_name AND a.customer_id < b.customer_id;

[User] Add a filter to only include pairs where both customers are in the same state as well.

[Assistant] SELECT a.customer_id AS customer_id_a, CONCAT(a.first_name, ' ', a.last_name) AS full_name_a, b.customer_id AS customer_id_b, CONCAT(b.first_name, ' ', b.last_name) AS full_name_b, a.city, a.state FROM financial_services.customers a JOIN financial_services.customers b ON a.city = b.city AND a.state = b.state AND a.last_name <> b.last_name AND a.customer_id < b.customer_id;

[User] Please further restrict results to only pairs where both customers have a status of 'Active'.

[Assistant] SELECT a.customer_id AS customer_id_a, CONCAT(a.first_name, ' ', a.last_name) AS full_name_a, b.customer_id AS customer_id_b, CONCAT(b.first_name, ' ', b.last_name) AS full_name_b, a.city, a.state FROM financial_services.customers a JOIN financial_services.customers b ON a.city = b.city AND a.state = b.state AND a.last_name <> b.last_name AND a.status = 'Active' AND b.status = 'Active' AND a.customer_id < b.customer_id;

[User] List all customers in California ('CA'). Show their full name, city, and date of birth.

[Assistant] SELECT first_name, last_name, city, date_of_birth FROM financial_services.customers WHERE state = 'CA'

[User] Also include customers from New York ('NY').

[Assistant] SELECT first_name, last_name, city, date_of_birth FROM financial_services.customers WHERE state = 'CA' OR state = 'NY'

[User] Sort the results by state ascending, then by date of birth ascending.

[Assistant] SELECT first_name, last_name, city, date_of_birth FROM financial_services.customers WHERE state = 'CA' OR state = 'NY' ORDER BY state ASC, date_of_birth ASC

[User] Find all distinct pairs of customers having the same first_name but living in different cities. Display a.customer_id, a.first_name, a.city AS city_a, b.customer_id, b.city AS city_b.

[Assistant]
SELECT a.customer_id AS customer_id_a,
       a.first_name,
       a.city      AS city_a,
       b.customer_id AS customer_id_b,
       b.city      AS city_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.first_name = b.first_name
 AND a.city <> b.city
 AND a.customer_id < b.customer_id;

[User] Only include pairs where both customers have status 'Active'.

[Assistant]
SELECT a.customer_id AS customer_id_a,
       a.first_name,
       a.city      AS city_a,
       b.customer_id AS customer_id_b,
       b.city      AS city_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.first_name = b.first_name
 AND a.city <> b.city
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active';

[User] Sort the output by first_name ascending and then by customer_id_a ascending.

[Assistant]
SELECT a.customer_id AS customer_id_a,
       a.first_name,
       a.city      AS city_a,
       b.customer_id AS customer_id_b,
       b.city      AS city_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.first_name = b.first_name
 AND a.city <> b.city
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
ORDER BY a.first_name ASC,
         customer_id_a ASC;

[User] Show me all customers (customer_id, first_name, last_name, email) who were born after 1985 (date_of_birth > '1985-12-31') and have an email address ending with '@yahoo.com', along with their city and state information.

[Assistant] SELECT customer_id, first_name, last_name, email, city, state FROM financial_services.customers WHERE date_of_birth > '1985-12-31' AND email LIKE '%@yahoo.com';

[User] What is the average age of customers by risk_profile for those in status 'Active'?

[Assistant]
SELECT risk_profile,
       AVG(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS avg_age
FROM financial_services.customers
WHERE status = 'Active'
GROUP BY risk_profile;

[User] Exclude risk_profiles with fewer than 10 active customers.

[Assistant]
SELECT risk_profile,
       AVG(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS avg_age
FROM financial_services.customers
WHERE status = 'Active'
GROUP BY risk_profile
HAVING COUNT(*) >= 10;

[User] Also include the minimum and maximum age in the result.

[Assistant]
SELECT risk_profile,
       AVG(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS avg_age,
       MIN(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS min_age,
       MAX(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS max_age
FROM financial_services.customers
WHERE status = 'Active'
GROUP BY risk_profile
HAVING COUNT(*) >= 10;

[User] Can you give me a breakdown of the number of customers in each country and their average age? I want the result to also show the total number of unique states per country.

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers GROUP BY country;

[User] That's helpful. Please add the minimum and maximum age for each country as well.

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, MIN(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS min_age, MAX(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS max_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers GROUP BY country;

[User] Only include countries where the total number of customers is greater than 50. Can you sort the result by customer_count descending?

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, MIN(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS min_age, MAX(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS max_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers GROUP BY country HAVING COUNT(*) > 50 ORDER BY customer_count DESC;

[User] I notice some countries are missing because their names are null. Please exclude rows with null country values.

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, MIN(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS min_age, MAX(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS max_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers WHERE country IS NOT NULL GROUP BY country HAVING COUNT(*) > 50 ORDER BY customer_count DESC;

[User] I want to see pairs of customers living in the same state but having different risk profiles. Show their customer_ids, states, and risk_profiles.

[Assistant] SELECT a.customer_id AS customer_a, a.state, a.risk_profile AS risk_profile_a, b.customer_id AS customer_b, b.risk_profile AS risk_profile_b FROM financial_services.customers a JOIN financial_services.customers b ON a.state = b.state AND a.risk_profile <> b.risk_profile;

[User] Exclude any pairs where either customer has a null phone_number.

[Assistant] SELECT a.customer_id AS customer_a, a.state, a.risk_profile AS risk_profile_a, b.customer_id AS customer_b, b.risk_profile AS risk_profile_b FROM financial_services.customers a JOIN financial_services.customers b ON a.state = b.state AND a.risk_profile <> b.risk_profile WHERE a.phone_number IS NOT NULL AND b.phone_number IS NOT NULL;

[User] Ensure each pair appears only once, without reversed duplicates.

[Assistant] SELECT a.customer_id AS customer_a, a.state, a.risk_profile AS risk_profile_a, b.customer_id AS customer_b, b.risk_profile AS risk_profile_b FROM financial_services.customers a JOIN financial_services.customers b ON a.state = b.state AND a.risk_profile <> b.risk_profile WHERE a.phone_number IS NOT NULL AND b.phone_number IS NOT NULL AND a.customer_id < b.customer_id;

[User] Finally, only include states that have more than 3 customers in total.

[Assistant] SELECT a.customer_id AS customer_a, a.state, a.risk_profile AS risk_profile_a, b.customer_id AS customer_b, b.risk_profile AS risk_profile_b FROM financial_services.customers a JOIN financial_services.customers b ON a.state = b.state AND a.risk_profile <> b.risk_profile WHERE a.phone_number IS NOT NULL AND b.phone_number IS NOT NULL AND a.customer_id < b.customer_id AND a.state IN (SELECT state FROM financial_services.customers GROUP BY state HAVING COUNT(*) > 3);

[User] Show all active customers who live in the same zip_code.

[Assistant]
SELECT a.customer_id AS cust1,
       b.customer_id AS cust2,
       a.zip_code
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.zip_code = b.zip_code
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active';

[User] Please ensure we don't list duplicate pairs and order by zip_code and cust1.

[Assistant]
SELECT a.customer_id AS cust1,
       b.customer_id AS cust2,
       a.zip_code
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.zip_code = b.zip_code
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
ORDER BY a.zip_code, a.customer_id;

[User] Include the city and state in the result as well.

[Assistant]
SELECT a.customer_id AS cust1,
       b.customer_id AS cust2,
       a.zip_code,
       a.city,
       a.state
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.zip_code = b.zip_code
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
ORDER BY a.zip_code, a.customer_id;

[User] How many customers are there in each risk_profile and what is their average age?

[Assistant] SELECT risk_profile, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM AGE(current_date, date_of_birth))) AS average_age FROM financial_services.customers GROUP BY risk_profile;

[User] Exclude risk_profiles with fewer than 10 customers.

[Assistant] SELECT risk_profile, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM AGE(current_date, date_of_birth))) AS average_age FROM financial_services.customers GROUP BY risk_profile HAVING COUNT(*) >= 10;

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

[Assistant] SELECT risk_profile, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM AGE(current_date, date_of_birth))) AS average_age FROM financial_services.customers GROUP BY risk_profile HAVING COUNT(*) >= 10 ORDER BY average_age ASC;

[User] Show pairs of customers who share the same email domain but have different last names. Include their IDs, full names, and email domain.

[Assistant] SELECT a.customer_id AS customer_a_id, a.first_name AS customer_a_first_name, a.last_name AS customer_a_last_name, b.customer_id AS customer_b_id, b.first_name AS customer_b_first_name, b.last_name AS customer_b_last_name, SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) AS email_domain FROM financial_services.customers a JOIN financial_services.customers b ON SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) = SUBSTRING(b.email FROM POSITION('@' IN b.email) + 1) AND a.last_name != b.last_name AND a.customer_id < b.customer_id WHERE a.email IS NOT NULL AND b.email IS NOT NULL;

[User] Only include email domains that are shared by at least 2 customers in total.

[Assistant] WITH DomainCounts AS (SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS email_domain, COUNT(*) AS domain_count FROM financial_services.customers WHERE email IS NOT NULL GROUP BY 1 HAVING COUNT(*) > 1) SELECT a.customer_id AS customer_a_id, a.first_name AS customer_a_first_name, a.last_name AS customer_a_last_name, b.customer_id AS customer_b_id, b.first_name AS customer_b_first_name, b.last_name AS customer_b_last_name, SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) AS email_domain FROM financial_services.customers a JOIN financial_services.customers b ON SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) = SUBSTRING(b.email FROM POSITION('@' IN b.email) + 1) AND a.last_name != b.last_name AND a.customer_id < b.customer_id WHERE a.email IS NOT NULL AND b.email IS NOT NULL AND SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) IN (SELECT email_domain FROM DomainCounts);

[User] Sort the results by email domain ascending, then by the first customer's last name.

[Assistant] WITH DomainCounts AS (SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS email_domain, COUNT(*) AS domain_count FROM financial_services.customers WHERE email IS NOT NULL GROUP BY 1 HAVING COUNT(*) > 1) SELECT a.customer_id AS customer_a_id, a.first_name AS customer_a_first_name, a.last_name AS customer_a_last_name, b.customer_id AS customer_b_id, b.first_name AS customer_b_first_name, b.last_name AS customer_b_last_name, SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) AS email_domain FROM financial_services.customers a JOIN financial_services.customers b ON SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) = SUBSTRING(b.email FROM POSITION('@' IN b.email) + 1) AND a.last_name != b.last_name AND a.customer_id < b.customer_id WHERE a.email IS NOT NULL AND b.email IS NOT NULL AND SUBSTRING(a.email FROM POSITION('@' IN a.email) + 1) IN (SELECT email_domain FROM DomainCounts) ORDER BY email_domain, a.last_name;


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

[User] 我想查看所有检查记录中检查员的ID和检查结果，同时统计每个检查员的检查次数。

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

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

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

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

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

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

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

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

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

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

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

[User] Can you help me retrieve inspection records for a specific step ID, including the inspection type, result, timestamp, and the associated build ID?

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

[User] Can you add a filter to show only inspections with a result of 'Fail'?

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

[User] What if I want to further narrow it down to inspections performed after March 1, 2023?

[Assistant] db.inspections.find({ step_id: 'specific_step_id', result: 'Fail', inspection_timestamp: { $gt: ISODate('2023-03-01T00:00:00Z') } }, { inspection_type: 1, result: 1, inspection_timestamp: 1, build_id: 1, _id: 0 })

[User] Can you also include the remarks field and sort the results by timestamp in ascending order?

[Assistant] db.inspections.find({ step_id: 'specific_step_id', result: 'Fail', inspection_timestamp: { $gt: ISODate('2023-03-01T00:00:00Z') } }, { inspection_type: 1, result: 1, inspection_timestamp: 1, build_id: 1, remarks: 1, _id: 0 }).sort({ inspection_timestamp: 1 })

[User] 我想查询某个构建ID下的所有检查记录，包括检查类型、检查结果和检查时间，同时关联到对应的步骤信息。

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      build_id: 'specific_build_id'
    }
  },
  {
    $lookup: {
      from: 'steps',
      localField: 'step_id',
      foreignField: 'step_id',
      as: 'step_info'
    }
  },
  {
    $unwind: {
      path: '$step_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      result: 1,
      inspection_timestamp: 1,
      'step_info.step_name': 1,
      'step_info.description': 1
    }
  }
]);

[User] 如果我想进一步筛选出检查结果为'Pass'的记录，应该怎么做？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      build_id: 'specific_build_id',
      result: 'Pass'
    }
  },
  {
    $lookup: {
      from: 'steps',
      localField: 'step_id',
      foreignField: 'step_id',
      as: 'step_info'
    }
  },
  {
    $unwind: {
      path: '$step_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      result: 1,
      inspection_timestamp: 1,
      'step_info.step_name': 1,
      'step_info.description': 1
    }
  }
]);

[User] I need to get a count of inspections performed by each inspector, including their employee ID and the total number of inspections they have conducted.

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} } } }])

[User] Can you modify this to show only inspectors who have performed more than 10 inspections?

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} } } }, { $match: { totalInspections: { $gt: 10 } } }])

[User] What if I also want to include the number of failed inspections for each inspector?

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} }, failedInspections: { $sum: { $cond: [{ $eq: ['$result', 'Fail'] }, 1, 0] } } } }, { $match: { totalInspections: { $gt: 10 } } }])

[User] Can you sort the results by the total number of inspections in descending order?

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} }, failedInspections: { $sum: { $cond: [{ $eq: ['$result', 'Fail'] }, 1, 0] } } } }, { $match: { totalInspections: { $gt: 10 } } }, { $sort: { totalInspections: -1 } }])

[User] 我想查询所有检查结果为'Pass'的记录，包括检查类型、检查时间和检查备注，同时关联到对应的组件信息。

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Pass'
    }
  },
  {
    $lookup: {
      from: 'components',
      localField: 'component_id',
      foreignField: 'component_id',
      as: 'component_info'
    }
  },
  {
    $unwind: {
      path: '$component_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      inspection_timestamp: 1,
      remarks: 1,
      'component_info.component_name': 1,
      'component_info.description': 1
    }
  }
]);

[User] 如果我想只看检查时间在2023年1月1日之后的记录，应该怎么修改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Pass',
      inspection_timestamp: {
        $gte: ISODate('2023-01-01T00:00:00Z')
      }
    }
  },
  {
    $lookup: {
      from: 'components',
      localField: 'component_id',
      foreignField: 'component_id',
      as: 'component_info'
    }
  },
  {
    $unwind: {
      path: '$component_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      inspection_timestamp: 1,
      remarks: 1,
      'component_info.component_name': 1,
      'component_info.description': 1
    }
  }
]);


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

[User] Show me all male patients who have received more than one prescription, including their full name, date of birth, and the total number of prescriptions.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Could you also include the names of the medications they've been prescribed?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Actually, I only want to see patients who also have at least one active diagnosis.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(DISTINCT pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] One of the medication_ids columns seems off, could you instead also show the medication_id and dosage for each prescription individually, as well as the diagnosis_code for their active diagnosis?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, pr.prescription_id, pr.medication_id, pr.dosage, d.diagnosis_code
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active';

[User] Show all prescriptions made in 2024 for medications prescribed during appointments scheduled at location 'LOC001', including prescription_id, patient_id, medication_id, and appointment_time.

[Assistant]
SELECT pr.prescription_id, pr.patient_id, pr.medication_id, ap.appointment_time
FROM healthcare.prescriptions pr
JOIN healthcare.medical_records mr ON pr.record_id = mr.record_id
JOIN healthcare.appointments ap ON mr.appointment_id = ap.appointment_id
WHERE ap.location_id = 'LOC001'
  AND EXTRACT(YEAR FROM pr.prescription_date) = 2024;

[User] List the contact phone and website for all insurance plans provided by 'Continental Health'.

[Assistant]
SELECT plan_name, contact_phone, website
FROM healthcare.insurance_plans
WHERE insurance_provider = 'Continental Health';

[User] Find all patients who have never received any diagnoses. Show patient ID, first_name, and last_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name
FROM healthcare.patients p
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] Only include those who have had at least one appointment.

[Assistant]
SELECT DISTINCT p.patient_id,
                p.first_name,
                p.last_name
FROM healthcare.patients p
JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
LEFT JOIN healthcare.diagnoses d
  ON p.patient_id = d.patient_id
WHERE d.diagnosis_id IS NULL;

[User] How many patients are there in each gender category?

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender;

[User] Limit this to categories with more than 50 patients.

[Assistant]
SELECT gender,
       COUNT(*) AS patient_count
FROM healthcare.patients
GROUP BY gender
HAVING COUNT(*) > 50;

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

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

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

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

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

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

[User] List each chronic active diagnosis along with the prescribed medication details, showing diagnosis_id, diagnosis_code, medication_id, dosage, and diagnosis_date.

[Assistant] SELECT d.diagnosis_id, d.diagnosis_code, p.medication_id, p.dosage, d.diagnosis_date FROM healthcare.diagnoses d JOIN healthcare.prescriptions p ON d.record_id = p.record_id AND d.patient_id = p.patient_id WHERE d.is_chronic = TRUE AND d.status = 'Active';

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

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

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

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

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

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

[User] Count the number of medications for each unique generic name. Show the generic name and the count.

[Assistant]
SELECT
  generic_name,
  COUNT(medication_id) AS medication_count
FROM healthcare.medications
WHERE
  generic_name IS NOT NULL
GROUP BY
  generic_name;

[User] Only show generic names that have more than 5 associated medications.

[Assistant]
SELECT
  generic_name,
  COUNT(medication_id) AS medication_count
FROM healthcare.medications
WHERE
  generic_name IS NOT NULL
GROUP BY
  generic_name
HAVING
  COUNT(medication_id) > 5;

[User] Show all prescriptions along with the patient's full name and the medication name. Include prescription_id, prescription_date, patient first_name, patient last_name, and medication_name.

[Assistant]
SELECT pr.prescription_id,
       pr.prescription_date,
       p.first_name AS patient_first_name,
       p.last_name AS patient_last_name,
       m.medication_name
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id;

[User] Also include the prescribing doctor's full name and only show prescriptions with refills_allowed > 0.

[Assistant]
SELECT pr.prescription_id,
       pr.prescription_date,
       p.first_name AS patient_first_name,
       p.last_name AS patient_last_name,
       d.first_name AS doctor_first_name,
       d.last_name AS doctor_last_name,
       m.medication_name
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.refills_allowed > 0;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.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 PRIMARY KEY, tag_name 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.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.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
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] Show all users who follow both user 'U100' and user 'U101'.

[Assistant]
SELECT f1.follower_user_id
FROM social_media.follows f1
JOIN social_media.follows f2 ON f1.follower_user_id = f2.follower_user_id
WHERE f1.following_user_id = 'U100' AND f2.following_user_id = 'U101';

[User] For each conversation, how many participants have joined before January 1, 2024?

[Assistant]
SELECT conversation_id, COUNT(user_id) AS participant_count
FROM social_media.conversation_participants
WHERE joined_at < '2024-01-01'
GROUP BY conversation_id;

[User] Show only conversations with more than 10 such participants.

[Assistant]
SELECT conversation_id, COUNT(user_id) AS participant_count
FROM social_media.conversation_participants
WHERE joined_at < '2024-01-01'
GROUP BY conversation_id
HAVING COUNT(user_id) > 10;

[User] Which users have participated in group chats and also liked comments? Please show their usernames, the group name, and the comment_id they've liked.

[Assistant]
SELECT u.username, c.group_name, l.comment_id
FROM social_media.conversation_participants cp
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.likes l ON u.user_id = l.user_id
WHERE c.is_group_chat = true AND l.comment_id IS NOT NULL;

[User] Could you also include the joined_at time for when each user joined the group chat?

[Assistant]
SELECT u.username, c.group_name, cp.joined_at, l.comment_id
FROM social_media.conversation_participants cp
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.likes l ON u.user_id = l.user_id
WHERE c.is_group_chat = true AND l.comment_id IS NOT NULL;

[User] List the usernames of users that are being followed by user 'U123'.

[Assistant] SELECT T2.username FROM social_media.follows AS T1 JOIN social_media.users AS T2 ON T1.following_user_id = T2.user_id WHERE T1.follower_user_id = 'U123'

[User] Could you also include their email addresses?

[Assistant] SELECT T2.username, T2.email FROM social_media.follows AS T1 JOIN social_media.users AS T2 ON T1.following_user_id = T2.user_id WHERE T1.follower_user_id = 'U123'

[User] Only show those users who are verified.

[Assistant] SELECT T2.username, T2.email FROM social_media.follows AS T1 JOIN social_media.users AS T2 ON T1.following_user_id = T2.user_id WHERE T1.follower_user_id = 'U123' AND T2.is_verified = true

[User] Order the results alphabetically by username.

[Assistant] SELECT T2.username, T2.email FROM social_media.follows AS T1 JOIN social_media.users AS T2 ON T1.following_user_id = T2.user_id WHERE T1.follower_user_id = 'U123' AND T2.is_verified = true ORDER BY T2.username ASC

[User] Show the content of all comments made on posts that are tagged with hashtag 'H456'.

[Assistant] SELECT T1.content FROM social_media.comments AS T1 JOIN social_media.post_hashtags AS T2 ON T1.post_id = T2.post_id WHERE T2.hashtag_id = 'H456'

[User] Also, include the username of the person who wrote each comment.

[Assistant] SELECT T1.content, T3.username FROM social_media.comments AS T1 JOIN social_media.post_hashtags AS T2 ON T1.post_id = T2.post_id JOIN social_media.users AS T3 ON T1.user_id = T3.user_id WHERE T2.hashtag_id = 'H456'

[User] How many conversations in total are recorded?

[Assistant] SELECT count(*) FROM conversations;

[User] Show me a list of comments and the names of hashtags associated with the posts those comments are on.

[Assistant] SELECT T1.comment_id, T3.tag_name FROM comments AS T1 JOIN post_hashtags AS T2 ON T1.post_id = T2.post_id JOIN hashtags AS T3 ON T2.hashtag_id = T3.hashtag_id;

[User] Can you also include the content of the comment and filter the results to only show comments on posts tagged with 'photography'?

[Assistant] SELECT T1.comment_id, T1.content, T3.tag_name FROM comments AS T1 JOIN post_hashtags AS T2 ON T1.post_id = T2.post_id JOIN hashtags AS T3 ON T2.hashtag_id = T3.hashtag_id WHERE T3.tag_name = 'photography';

[User] Please only list comments that are top-level, meaning they are not replies to other comments.

[Assistant] SELECT T1.comment_id, T1.content, T3.tag_name FROM comments AS T1 JOIN post_hashtags AS T2 ON T1.post_id = T2.post_id JOIN hashtags AS T3 ON T2.hashtag_id = T3.hashtag_id WHERE T3.tag_name = 'photography' AND T1.parent_comment_id IS NULL;

[User] Show me the usernames of all verified users who have liked any comment and the like creation time.

[Assistant]
SELECT u.username, l.created_at
FROM social_media.likes l
JOIN social_media.users u ON l.user_id = u.user_id
WHERE l.comment_id IS NOT NULL AND u.is_verified = true;

[User] Now, show the comment ID as well.

[Assistant]
SELECT u.username, l.comment_id, l.created_at
FROM social_media.likes l
JOIN social_media.users u ON l.user_id = u.user_id
WHERE l.comment_id IS NOT NULL AND u.is_verified = true;

[User] How many group chats have been created since January 1, 2024?

[Assistant]
SELECT COUNT(*) AS group_chat_count
FROM social_media.conversations
WHERE is_group_chat = TRUE
  AND created_at >= '2024-01-01';

[User] What are the top 5 posts by number of likes, showing post_id, media_type and like_count, ordered by like_count descending?

[Assistant]
SELECT p.post_id, p.media_type, COUNT(l.like_id) AS like_count
FROM social_media.posts p
JOIN social_media.likes l ON p.post_id = l.post_id
GROUP BY p.post_id, p.media_type
ORDER BY like_count DESC
LIMIT 5;

[User] Actually, I only want posts where media_type is 'image' or 'video' and created in the last 30 days. Please adjust.

[Assistant]
SELECT p.post_id, p.media_type, COUNT(l.like_id) AS like_count
FROM social_media.posts p
JOIN social_media.likes l ON p.post_id = l.post_id
WHERE p.media_type IN ('image', 'video')
  AND p.created_at >= NOW() - INTERVAL '30 days'
GROUP BY p.post_id, p.media_type
ORDER BY like_count DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
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.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] Show me the policy number, premium amount, and payment status for every premium payment made, along with the customer's full name for each one.

[Assistant]
SELECT p.policy_number, pp.amount_paid, pp.status, c.first_name, c.last_name
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
JOIN insurance.customers c ON pp.customer_id = c.customer_id;

[User] Only show payments made by customers whose status is 'Active'.

[Assistant]
SELECT p.policy_number, pp.amount_paid, pp.status, c.first_name, c.last_name
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
JOIN insurance.customers c ON pp.customer_id = c.customer_id
WHERE c.status = 'Active';

[User] I only want to see policies where the premium amount exceeds 2000.

[Assistant]
SELECT p.policy_number, pp.amount_paid, pp.status, c.first_name, c.last_name
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
JOIN insurance.customers c ON pp.customer_id = c.customer_id
WHERE c.status = 'Active' AND p.premium_amount > 2000;

[User] Just show me the policy number, payment amount, customer full name, and sort by amount_paid descending.

[Assistant]
SELECT p.policy_number, pp.amount_paid, c.first_name, c.last_name
FROM insurance.premium_payments pp
JOIN insurance.policies p ON pp.policy_id = p.policy_id
JOIN insurance.customers c ON pp.customer_id = c.customer_id
WHERE c.status = 'Active' AND p.premium_amount > 2000
ORDER BY pp.amount_paid DESC;

[User] List each claim with its policy number and the selling agent's first and last name.

[Assistant]
SELECT c.claim_id, p.policy_number, a.first_name, a.last_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
LEFT JOIN insurance.agents a ON p.agent_id = a.agent_id;

[User] Filter to include only claims with settlement_amount not null and reported_date in 2023.

[Assistant]
SELECT c.claim_id, p.policy_number, a.first_name, a.last_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
LEFT JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE c.settlement_amount IS NOT NULL
  AND c.reported_date >= '2023-01-01'::timestamp
  AND c.reported_date < '2024-01-01'::timestamp;

[User] Show me the first and last names of all customers and the agency name of the agent who sold their policy.

[Assistant]
SELECT c.first_name, c.last_name, a.agency_name
FROM insurance.policies p
JOIN insurance.customers c ON p.customer_id = c.customer_id
LEFT JOIN insurance.agents a ON p.agent_id = a.agent_id;

[User] Count the number of premium payments that have a null payment method.

[Assistant]
SELECT COUNT(*) AS null_payment_method_count
FROM insurance.premium_payments
WHERE payment_method IS NULL;

[User] Show me the first name, last name, and policy number for all customers who have filed a claim with an estimated loss over $50,000, along with the agent's full name who sold the policy.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE cl.estimated_loss > 50000;

[User] Can you also include the policy's premium amount and status in the results?

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.premium_amount, p.status, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE cl.estimated_loss > 50000;

[User] Actually, only show those claims where the policy's status is 'Active' and the agent is currently 'Active' as well.

[Assistant]
SELECT c.first_name, c.last_name, p.policy_number, p.premium_amount, p.status, a.first_name AS agent_first_name, a.last_name AS agent_last_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.agents a ON p.agent_id = a.agent_id
WHERE cl.estimated_loss > 50000 AND p.status = 'Active' AND a.status = 'Active';

[User] Show policy number, cancellation date, and the customer's first and last name for policies cancelled due to 'Non-Payment'.

[Assistant] SELECT T1.policy_number, T1.cancellation_date, T2.first_name, T2.last_name FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id WHERE T1.cancellation_reason = 'Non-Payment';

[User] Can you also include the policy's start date and the agent's first and last name who sold it?

[Assistant] SELECT T1.policy_number, T1.cancellation_date, T2.first_name AS customer_first_name, T2.last_name AS customer_last_name, T1.start_date, T3.first_name AS agent_first_name, T3.last_name AS agent_last_name FROM policies AS T1 JOIN customers AS T2 ON T1.customer_id = T2.customer_id JOIN agents AS T3 ON T1.agent_id = T3.agent_id WHERE T1.cancellation_reason = 'Non-Payment';

[User] List policy number, start date, premium amount, and the agent's first and last name for all policies sold by agents licensed in 'NY'.

[Assistant] SELECT T1.policy_number, T1.start_date, T1.premium_amount, T2.first_name, T2.last_name FROM policies AS T1 JOIN agents AS T2 ON T1.agent_id = T2.agent_id WHERE T2.license_state = 'NY';

[User] Can you also include the customer's first and last name for each of these policies?

[Assistant] SELECT T1.policy_number, T1.start_date, T1.premium_amount, T2.first_name AS agent_first_name, T2.last_name AS agent_last_name, T3.first_name AS customer_first_name, T3.last_name AS customer_last_name FROM policies AS T1 JOIN agents AS T2 ON T1.agent_id = T2.agent_id JOIN customers AS T3 ON T1.customer_id = T3.customer_id WHERE T2.license_state = 'NY';

[User] Actually, only show policies that are currently 'Active'.

[Assistant] SELECT T1.policy_number, T1.start_date, T1.premium_amount, T2.first_name AS agent_first_name, T2.last_name AS agent_last_name, T3.first_name AS customer_first_name, T3.last_name AS customer_last_name FROM policies AS T1 JOIN agents AS T2 ON T1.agent_id = T2.agent_id JOIN customers AS T3 ON T1.customer_id = T3.customer_id WHERE T2.license_state = 'NY' AND T1.status = 'Active';

[User] Show me claim_id, incident_date, policy_number, and customer full name for all claims where settlement_amount is null.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL;

[User] The query should only include claims reported in 2024.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL
  AND c.incident_date >= '2024-01-01'
  AND c.incident_date < '2025-01-01';

[User] Also order the results by incident_date descending and limit the output to the top 10.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL
  AND c.incident_date >= '2024-01-01'
  AND c.incident_date < '2025-01-01'
ORDER BY c.incident_date DESC
LIMIT 10;

[User] Actually, I need to include the agent_id who sold each policy in the output as well.

[Assistant]
SELECT c.claim_id, c.incident_date, p.policy_number, cu.first_name || ' ' || cu.last_name AS customer_full_name, p.agent_id
FROM insurance.claims c
JOIN insurance.policies p ON c.policy_id = p.policy_id
JOIN insurance.customers cu ON c.customer_id = cu.customer_id
WHERE c.settlement_amount IS NULL
  AND c.incident_date >= '2024-01-01'
  AND c.incident_date < '2025-01-01'
ORDER BY c.incident_date DESC
LIMIT 10;

[User] I want to list all claims with their claim_id, incident_date, and the customer's full name for claims where estimated_loss is above 10000.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
WHERE cl.estimated_loss > 10000;

[User] Actually, I also need the policy_number associated with each claim.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name, p.policy_number
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
WHERE cl.estimated_loss > 10000;

[User] Additionally, only include claims that are still open (status = 'Open') and order by incident_date descending.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name, p.policy_number
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
WHERE cl.estimated_loss > 10000
  AND cl.status = 'Open'
ORDER BY cl.incident_date DESC;

[User] That's good, but limit to the top 10 results.

[Assistant]
SELECT cl.claim_id, cl.incident_date, c.first_name || ' ' || c.last_name AS customer_name, p.policy_number
FROM insurance.claims cl
JOIN insurance.customers c ON cl.customer_id = c.customer_id
JOIN insurance.policies p ON cl.policy_id = p.policy_id
WHERE cl.estimated_loss > 10000
  AND cl.status = 'Open'
ORDER BY cl.incident_date DESC
LIMIT 10;

[User] List the customer ID, first_name, last_name, city, and the number of active policies each customer has, but only include customers who live in 'CA' and have at least 2 active policies.

[Assistant]
SELECT cu.customer_id, cu.first_name, cu.last_name, cu.city, COUNT(p.policy_id) AS active_policy_count
FROM insurance.customers cu
JOIN insurance.policies p ON cu.customer_id = p.customer_id
WHERE cu.state = 'CA'
  AND p.status = 'Active'
GROUP BY cu.customer_id, cu.first_name, cu.last_name, cu.city
HAVING COUNT(p.policy_id) >= 2;