System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] Count the number of tokens for each contract address.

[Assistant] SELECT contract_address, COUNT(*) AS token_count FROM web3.tokens GROUP BY contract_address;

[User] Only show contracts that have more than 5 tokens.

[Assistant] SELECT contract_address, COUNT(*) AS token_count FROM web3.tokens GROUP BY contract_address HAVING COUNT(*) > 5;

[User] List all users who created a wallet on the same day they registered. Show user ID, username, and the wallet address.

[Assistant] SELECT u.user_id, u.username, w.address FROM web3.users AS u JOIN web3.wallets AS w ON u.user_id = w.user_id WHERE DATE(u.created_at) = DATE(w.created_at);

[User] Find the contract ID, address, and deployer address for all contracts that have not emitted any events.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address FROM web3.contracts AS c LEFT JOIN web3.events AS e ON c.contract_id = e.contract_id WHERE e.event_id IS NULL;

[User] List all users and the total value of all transactions they have initiated. Show user_id, username, and total_transaction_value.

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

[User] Actually, only show users who have initiated at least one transaction, and sort them by total_transaction_value descending.

[Assistant]
SELECT u.user_id, u.username, SUM(t.value) AS total_transaction_value
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions t ON w.address = t.from_address
GROUP BY u.user_id, u.username
HAVING SUM(t.value) > 0
ORDER BY total_transaction_value DESC;

[User] Show all contracts and the names of all events they have ever emitted. Include contract_id, contract address, and event_name.

[Assistant]
SELECT c.contract_id, c.address, e.event_name
FROM web3.contracts c
JOIN web3.events e ON c.contract_id = e.contract_id
ORDER BY c.contract_id, e.event_name;

[User] Show all contracts along with the number of events each contract has emitted. Include the contract address and the event count.

[Assistant]
SELECT c.address, COUNT(e.event_id) AS event_count
FROM web3.contracts c
LEFT JOIN web3.events e ON c.contract_id = e.contract_id
GROUP BY c.address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )

[User] I need a list of genres and pairs of game titles in the same genre.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre;

[User] Please avoid duplicate pairs by ensuring each pair appears only once.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title;

[User] Only include genres that have at least three games.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  );

[User] Also sort the output by genre ascending and game1 ascending.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  )
ORDER BY g1.genre ASC, g1.title ASC;

[User] List each game along with the title and release_date of the next game released by the same developer.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Actually, only include next games released within one year of the original game.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Also show the gap in days between the two release dates.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date,
       (g2.release_date - g1.release_date) AS days_gap
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY days_gap DESC;

[User] Finally, limit to developers who have at least 5 games.

[Assistant]
WITH dev_counts AS (
  SELECT developer_id, COUNT(*) AS game_count
  FROM gaming_technology.games
  GROUP BY developer_id
  HAVING COUNT(*) >= 5
)
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date,
       (g2.release_date - g1.release_date) AS days_gap
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
JOIN dev_counts dc
  ON g1.developer_id = dc.developer_id
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Can you list each game alongside another game in the same genre but by a different developer?

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id;

[User] Exclude any pairs where either game was released before 2019.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01';

[User] Limit the output to the first 10 pairs ordered by genre and developer_id.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01'
ORDER BY g1.genre, g1.developer_id
LIMIT 10;

[User] How many games are there per platform, and what is the earliest release_date for each platform?

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform;

[User] Only include platforms with at least 10 games.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10;

[User] Sort the results by game_count descending.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10
ORDER BY game_count DESC;

[User] Also include the number of unique genres available on each platform.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release,
       COUNT(DISTINCT genre) AS genre_count
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10
ORDER BY game_count DESC;

[User] List all pairs of games developed by the same developer, returning developer_id, title of the first game, and title of the second game.

[Assistant]
SELECT g1.developer_id, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id;

[User] Only include developers who have created more than 3 games.

[Assistant]
SELECT g1.developer_id, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
WHERE g1.developer_id IN (
  SELECT developer_id
  FROM gaming_technology.games
  GROUP BY developer_id
  HAVING COUNT(*) > 3
);

[User] Also show the total number of games each developer has made alongside each pair.

[Assistant]
SELECT g1.developer_id, cnt.total_games, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
JOIN (
  SELECT developer_id, COUNT(*) AS total_games
  FROM gaming_technology.games
  GROUP BY developer_id
) cnt ON g1.developer_id = cnt.developer_id
WHERE cnt.total_games > 3;

[User] I only want pairs where both games were released after '2021-01-01'.

[Assistant]
SELECT g1.developer_id, cnt.total_games, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
JOIN (
  SELECT developer_id, COUNT(*) AS total_games
  FROM gaming_technology.games
  GROUP BY developer_id
) cnt ON g1.developer_id = cnt.developer_id
WHERE cnt.total_games > 3
  AND g1.release_date > '2021-01-01'
  AND g2.release_date > '2021-01-01';

[User] How many games are available on each platform?

[Assistant]
SELECT platform, COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY platform;

[User] Exclude platforms with fewer than five games.

[Assistant]
SELECT platform, COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5;

[User] Also show the earliest release_date for each platform.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5;

[User] Finally, order by game_count descending.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5
ORDER BY game_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )

[User] List the citizen ID, full name, and registration date for all unverified citizens who registered in the year 2022.

[Assistant] SELECT citizen_id, first_name, last_name, registration_date FROM government_services.citizens WHERE is_verified = FALSE AND EXTRACT(YEAR FROM registration_date) = 2022;

[User] Show me the names of all employees along with the names of the agencies they work for, and the number of appointments each employee has scheduled.

[Assistant]
SELECT e.first_name, e.last_name, a.agency_name, COUNT(appt.appointment_id) AS appointment_count
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
LEFT JOIN government_services.appointments appt ON e.employee_id = appt.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name, a.agency_name;

[User] Can you only show employees who have scheduled more than 5 appointments?

[Assistant]
SELECT e.first_name, e.last_name, a.agency_name, COUNT(appt.appointment_id) AS appointment_count
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
LEFT JOIN government_services.appointments appt ON e.employee_id = appt.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name, a.agency_name
HAVING COUNT(appt.appointment_id) > 5;

[User] Show the full name (first and last name) of employees who are assigned to applications with a status of 'Completed'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.employees AS T1 INNER JOIN government_services.applications AS T2 ON T1.employee_id = T2.assigned_employee_id WHERE T2.status = 'Completed';

[User] List the agency names and the total amount received from payments with the status 'Pending'.

[Assistant]
SELECT ag.agency_name, SUM(p.amount) AS total_pending_payments
FROM government_services.payments p
JOIN government_services.services s ON p.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE p.status = 'Pending'
GROUP BY ag.agency_name;

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

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

[User] Which citizens have had both applications and appointments for services in the 'Healthcare' category? List their full name, application ID, and appointment ID.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, a.application_id, appt.appointment_id
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
JOIN government_services.services s1 ON a.service_id = s1.service_id
JOIN government_services.appointments appt ON c.citizen_id = appt.citizen_id
JOIN government_services.services s2 ON appt.service_id = s2.service_id
WHERE s1.category = 'Healthcare' AND s2.category = 'Healthcare';


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 text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me all claims with police reports that were handled by agents hired in the last 2 years, along with the agent's full name and agency.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years'

[User] Now filter these results to only show claims where the estimated loss is above $10,000 and include the settlement amount if available.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years' AND c.estimated_loss > 10000

[User] I also want to see how many documents were submitted for each of these claims.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name, COUNT(d.document_id) AS document_count FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id LEFT JOIN insurance.claim_documents d ON c.claim_id = d.claim_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years' AND c.estimated_loss > 10000 GROUP BY c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, a.first_name, a.last_name, a.agency_name

[User] Finally, order the results by the highest estimated loss first and include only claims with at least 3 documents.

[Assistant] SELECT c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, CONCAT(a.first_name, ' ', a.last_name) AS agent_name, a.agency_name, COUNT(d.document_id) AS document_count FROM insurance.claims c JOIN insurance.agents a ON c.claim_handler_id = a.agent_id LEFT JOIN insurance.claim_documents d ON c.claim_id = d.claim_id WHERE c.police_report_number IS NOT NULL AND a.hire_date >= CURRENT_DATE - INTERVAL '2 years' AND c.estimated_loss > 10000 GROUP BY c.claim_id, c.policy_id, c.incident_date, c.police_report_number, c.estimated_loss, c.settlement_amount, a.first_name, a.last_name, a.agency_name HAVING COUNT(d.document_id) >= 3 ORDER BY c.estimated_loss DESC

[User] List the payment ID, amount paid, and due date for all premium payments with a status of 'overdue'.

[Assistant] SELECT payment_id, amount_paid, due_date FROM premium_payments WHERE status = 'overdue'

[User] Show all policy beneficiaries along with the total premium amount paid for the policy they are associated with.

[Assistant] SELECT T1.beneficiary_id, T1.first_name, T1.last_name, T1.policy_id, T1.percentage_share, SUM(T2.amount_paid) AS total_policy_premium_paid FROM policy_beneficiaries AS T1 JOIN premium_payments AS T2 ON T1.policy_id = T2.policy_id AND T1.customer_id = T2.customer_id GROUP BY T1.beneficiary_id, T1.first_name, T1.last_name, T1.policy_id, T1.percentage_share

[User] Only include beneficiaries with a percentage share greater than 10 and policies where the total premium paid exceeds 5000.

[Assistant] SELECT T1.beneficiary_id, T1.first_name, T1.last_name, T1.policy_id, T1.percentage_share, SUM(T2.amount_paid) AS total_policy_premium_paid FROM policy_beneficiaries AS T1 JOIN premium_payments AS T2 ON T1.policy_id = T2.policy_id AND T1.customer_id = T2.customer_id GROUP BY T1.beneficiary_id, T1.first_name, T1.last_name, T1.policy_id, T1.percentage_share HAVING T1.percentage_share > 10 AND SUM(T2.amount_paid) > 5000

[User] List all active agents with the number of open claims they've handled and the average settlement amount for their closed claims. Include agent_id, first_name, last_name, open_claims_count, and avg_settlement_closed.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name,
       COUNT(CASE WHEN c.status = 'Open' THEN 1 END) AS open_claims_count,
       AVG(CASE WHEN c.status = 'Closed' THEN c.settlement_amount END) AS avg_settlement_closed
FROM insurance.agents a
LEFT JOIN insurance.claims c ON a.agent_id = c.claim_handler_id
WHERE a.status = 'Active'
GROUP BY a.agent_id, a.first_name, a.last_name;

[User] Actually, only include agents with more than 5 open claims, and also include their total number of closed claims as closed_claims_count.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name,
       COUNT(CASE WHEN c.status = 'Open' THEN 1 END) AS open_claims_count,
       SUM(CASE WHEN c.status = 'Closed' THEN 1 END) AS closed_claims_count,
       AVG(CASE WHEN c.status = 'Closed' THEN c.settlement_amount END) AS avg_settlement_closed
FROM insurance.agents a
LEFT JOIN insurance.claims c ON a.agent_id = c.claim_handler_id
WHERE a.status = 'Active'
GROUP BY a.agent_id, a.first_name, a.last_name
HAVING COUNT(CASE WHEN c.status = 'Open' THEN 1 END) > 5;

[User] Also, sort the results by avg_settlement_closed descending and limit to the top 10 agents.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name,
       COUNT(CASE WHEN c.status = 'Open' THEN 1 END) AS open_claims_count,
       SUM(CASE WHEN c.status = 'Closed' THEN 1 END) AS closed_claims_count,
       AVG(CASE WHEN c.status = 'Closed' THEN c.settlement_amount END) AS avg_settlement_closed
FROM insurance.agents a
LEFT JOIN insurance.claims c ON a.agent_id = c.claim_handler_id
WHERE a.status = 'Active'
GROUP BY a.agent_id, a.first_name, a.last_name
HAVING COUNT(CASE WHEN c.status = 'Open' THEN 1 END) > 5
ORDER BY avg_settlement_closed DESC
LIMIT 10;

[User] Find beneficiaries with percentage_share above 50% for policies that have any claim with estimated_loss greater than 20000. Show beneficiary_id, first_name, last_name, and policy_id.

[Assistant]
SELECT pb.beneficiary_id, pb.first_name, pb.last_name, pb.policy_id
FROM insurance.policy_beneficiaries pb
JOIN insurance.claims c ON pb.policy_id = c.policy_id
WHERE pb.percentage_share > 50
  AND c.estimated_loss > 20000;

[User] Actually, include the claim's incident_date and estimated_loss as well, and only consider claims with status 'Open'.

[Assistant]
SELECT pb.beneficiary_id, pb.first_name, pb.last_name, pb.policy_id, c.incident_date, c.estimated_loss
FROM insurance.policy_beneficiaries pb
JOIN insurance.claims c ON pb.policy_id = c.policy_id
WHERE pb.percentage_share > 50
  AND c.estimated_loss > 20000
  AND c.status = 'Open';

[User] What is the total estimated loss for all claims reported in the year 2024?

[Assistant] SELECT SUM(estimated_loss) FROM insurance.claims WHERE EXTRACT(YEAR FROM reported_date) = 2024;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id.text, property_id.text, room_number.text, room_type_id.text, floor.integer, status.text, is_smoking.boolean, features.text, current_condition.text, last_cleaned_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )

[User] How many available services are there per department for each property? Include property_id, department, and the service count.

[Assistant]
SELECT
  property_id,
  department,
  COUNT(*) AS available_services_count
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY property_id, department;

[User] Also include the average price of these available services per department.

[Assistant]
SELECT
  property_id,
  department,
  COUNT(*) AS available_services_count,
  AVG(price) AS avg_service_price
FROM hospitality_technology.services
WHERE is_available = TRUE
GROUP BY property_id, department;

[User] Find the top 3 staff members who have responded to the most public reviews. Include their staff_id, first_name, last_name, and the count of responses.

[Assistant]
SELECT
  s.staff_id,
  s.first_name,
  s.last_name,
  COUNT(*) AS response_count
FROM hospitality_technology.staff AS s
JOIN hospitality_technology.reviews AS r
  ON s.staff_id = r.response_staff_id
WHERE r.is_public = TRUE
  AND r.response_staff_id IS NOT NULL
GROUP BY s.staff_id, s.first_name, s.last_name
ORDER BY response_count DESC
LIMIT 3;

[User] How many available rooms and available services are there for each property?

[Assistant]
SELECT
  r.property_id,
  SUM(CASE WHEN r.status = 'Available' THEN 1 ELSE 0 END) AS available_rooms_count,
  SUM(CASE WHEN s.is_available = TRUE THEN 1 ELSE 0 END) AS available_services_count
FROM hospitality_technology.rooms AS r
LEFT JOIN hospitality_technology.services AS s
  ON r.property_id = s.property_id
GROUP BY r.property_id;

[User] Exclude properties that have fewer than 10 available rooms.

[Assistant]
SELECT
  r.property_id,
  SUM(CASE WHEN r.status = 'Available' THEN 1 ELSE 0 END) AS available_rooms_count,
  SUM(CASE WHEN s.is_available = TRUE THEN 1 ELSE 0 END) AS available_services_count
FROM hospitality_technology.rooms AS r
LEFT JOIN hospitality_technology.services AS s
  ON r.property_id = s.property_id
GROUP BY r.property_id
HAVING SUM(CASE WHEN r.status = 'Available' THEN 1 ELSE 0 END) >= 10;

[User] Also order the results by available_services_count descending.

[Assistant]
SELECT
  r.property_id,
  SUM(CASE WHEN r.status = 'Available' THEN 1 ELSE 0 END) AS available_rooms_count,
  SUM(CASE WHEN s.is_available = TRUE THEN 1 ELSE 0 END) AS available_services_count
FROM hospitality_technology.rooms AS r
LEFT JOIN hospitality_technology.services AS s
  ON r.property_id = s.property_id
GROUP BY r.property_id
HAVING SUM(CASE WHEN r.status = 'Available' THEN 1 ELSE 0 END) >= 10
ORDER BY available_services_count DESC;

[User] Show me all rooms along with their current overall review rating for each room, including the room number and property id.

[Assistant]
SELECT r.room_number, r.property_id, AVG(rv.rating_overall) AS average_overall_rating
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
GROUP BY r.room_number, r.property_id;

[User] List all rooms with their latest review comment and the date of that review, showing the room number and property id.

[Assistant]
SELECT r.room_number, r.property_id, rv.comment, rv.review_date
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
WHERE rv.review_date = (
    SELECT MAX(rv2.review_date)
    FROM hospitality_technology.reviews rv2
    WHERE rv2.property_id = r.property_id
);

[User] Can you also include the overall rating in the result?

[Assistant]
SELECT r.room_number, r.property_id, rv.comment, rv.rating_overall, rv.review_date
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
WHERE rv.review_date = (
    SELECT MAX(rv2.review_date)
    FROM hospitality_technology.reviews rv2
    WHERE rv2.property_id = r.property_id
);

[User] Show only rooms located on the 2nd floor.

[Assistant]
SELECT r.room_number, r.property_id, rv.comment, rv.rating_overall, rv.review_date
FROM hospitality_technology.rooms r
LEFT JOIN hospitality_technology.reviews rv
  ON r.property_id = rv.property_id
WHERE r.floor = 2
  AND rv.review_date = (
    SELECT MAX(rv2.review_date)
    FROM hospitality_technology.reviews rv2
    WHERE rv2.property_id = r.property_id
);

[User] Give me the average cleanliness rating from reviews for each property.

[Assistant]
SELECT property_id, AVG(rating_cleanliness) AS avg_cleanliness_rating
FROM hospitality_technology.reviews
GROUP BY property_id;

[User] Actually, please also show the total number of reviews per property.

[Assistant]
SELECT property_id, AVG(rating_cleanliness) AS avg_cleanliness_rating, COUNT(*) AS total_reviews
FROM hospitality_technology.reviews
GROUP BY property_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )

[User] How many addresses on the Ethereum chain have an ROI between 2 and 4?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

[User] Could you also show their average profit?

[Assistant] SELECT AVG(profit) AS avg_profit FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

[User] List addresses on the 'Ethereum' chain that have an ROI greater than 5 and a profit greater than $1000. Show their address, profit, ROI, and realized ratio.

[Assistant] SELECT address, profit, roi, realized_ratio FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000

[User] Can you order these addresses by their profit in descending order?

[Assistant] SELECT address, profit, roi, realized_ratio FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000 ORDER BY profit DESC

[User] Only show addresses whose last trade time is in 2024.

[Assistant] SELECT address, profit, roi, realized_ratio FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000 AND last_trade_time LIKE '2024%' ORDER BY profit DESC

[User] Include the rank of these addresses in the output and show only the top 5 results.

[Assistant] SELECT address, profit, roi, realized_ratio, rank FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000 AND last_trade_time LIKE '2024%' ORDER BY profit DESC LIMIT 5

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

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

[User] For each chain, list the address with the highest ROI, showing the address, ROI, profit, and most profitable token.

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi;

[User] Add a filter to only include results where profit is greater than 50000.

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit WHERE profit > 50000 GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi WHERE t1.profit > 50000;

[User] Can you also add the rank of each address?

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token, t1.rank FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit WHERE profit > 50000 GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi WHERE t1.profit > 50000;

[User] Change the ROI filter to greater than 5 and profit greater than 100000.

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token, t1.rank FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit WHERE profit > 100000 AND roi > 5 GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi WHERE t1.profit > 100000 AND t1.roi > 5;

[User] Which addresses across all chains have a realized ratio above 0.9 and a profit above $20,000? Show their address, chain, profit, realized ratio, and most profitable token.

[Assistant] SELECT address, chain, profit, realized_ratio, most_profit_token FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000;

[User] Order these addresses by profit in descending order, and show the top 3.

[Assistant] SELECT address, chain, profit, realized_ratio, most_profit_token FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000 ORDER BY profit DESC LIMIT 3;

[User] Please add their ROI and last trade time to the results.

[Assistant] SELECT address, chain, profit, roi, realized_ratio, most_profit_token, last_trade_time FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000 ORDER BY profit DESC LIMIT 3;

[User] Can you also filter to only include addresses with an ROI greater than 3?

[Assistant] SELECT address, chain, profit, roi, realized_ratio, most_profit_token, last_trade_time FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000 AND roi > 3 ORDER BY profit DESC LIMIT 3;

[User] Which are the top 5 smart money addresses with the highest ROI on the BSC chain, and what are their profit, realized ratio, and most profitable token?

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token FROM smart_money_profit WHERE chain = 'BSC' ORDER BY roi DESC LIMIT 5;

[User] Can you also include their rank and last trade time in the output?

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' ORDER BY roi DESC LIMIT 5;

[User] I only want to see addresses with a profit above $10,000 and a realized ratio higher than 0.8.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY roi DESC LIMIT 5;

[User] Now, show the top one among these by profit instead of ROI.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY profit DESC LIMIT 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 project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
CREATE TABLE token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )

[User] For each chain in the smart money token inflow data, calculate the total number of addresses involved in buy transactions and the total number of addresses involved in sell transactions. Display the chain, total buy addresses, and total sell addresses.

[Assistant] SELECT chain, SUM(CASE WHEN type = 1 THEN address_amount ELSE 0 END) AS total_buy_addresses, SUM(CASE WHEN type = 2 THEN address_amount ELSE 0 END) AS total_sell_addresses FROM smart_money_token_inflow WHERE type IN (1, 2) GROUP BY chain;

[User] What is the total USD value of tokens held by CEXes for tokens belonging to the 'DeFi' narrative on the 'Ethereum' chain? Show the narrative, chain, and total value.

[Assistant] SELECT T2.narrative, T1.chain, SUM(T1.usd_value) AS total_usd_value FROM cex_token_balance AS T1 JOIN token_basic_info AS T2 ON T1.token_symbol = T2.token_symbol WHERE T2.narrative = 'DeFi' AND T1.chain = 'Ethereum' GROUP BY T2.narrative, T1.chain;

[User] Instead of just 'DeFi' on 'Ethereum', show the top 5 narratives with the highest total USD value across *all* chains in CEX balances. Also include the count of distinct token symbols for each narrative.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS total_usd_value, COUNT(DISTINCT T1.token_symbol) AS token_count FROM cex_token_balance AS T1 JOIN token_basic_info AS T2 ON T1.token_symbol = T2.token_symbol WHERE T2.narrative IS NOT NULL GROUP BY T2.narrative ORDER BY total_usd_value DESC LIMIT 5;

[User] Show all tokens on the Ethereum chain in token_dexpool_info that had a price increase in the last 6 hours, along with their 24h trading volume and smart money ROI.

[Assistant]
SELECT td.token_symbol,
       td.price_change_percentage_6h,
       td.volume_24h,
       smtp.roi
FROM token_dexpool_info AS td
JOIN smart_money_token_performance AS smtp
  ON td.token_symbol = smtp.token_symbol
 AND td.chain = smtp.chain
WHERE td.chain = 'Ethereum'
  AND td.price_change_percentage_6h > 0;

[User] I only want tokens with liquidity over 1,000,000 and ROI above 1. Show the price_change_24h as well.

[Assistant]
SELECT td.token_symbol,
       td.price_change_percentage_6h,
       td.price_change_percentage_24h,
       td.volume_24h,
       td.liquidity,
       smtp.roi
FROM token_dexpool_info AS td
JOIN smart_money_token_performance AS smtp
  ON td.token_symbol = smtp.token_symbol
 AND td.chain = smtp.chain
WHERE td.chain = 'Ethereum'
  AND td.price_change_percentage_6h > 0
  AND td.liquidity > 1000000
  AND smtp.roi > 1;

[User] Which chain has the highest average ROI among all tokens in smart_money_token_performance? Show the chain and the average ROI.

[Assistant]
SELECT chain, AVG(roi) AS avg_roi
FROM smart_money_token_performance
GROUP BY chain
ORDER BY avg_roi DESC
LIMIT 1;

[User] Could you also include the total number of tokens analyzed for that chain?

[Assistant]
SELECT chain, AVG(roi) AS avg_roi, COUNT(DISTINCT token_symbol) AS token_count
FROM smart_money_token_performance
GROUP BY chain
ORDER BY avg_roi DESC
LIMIT 1;

[User] List all projects that raised funds in March 2023. For each project, show its name, amount raised, fundraising round, and the token symbol and price of its associated token.

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%'

[User] Can you also include the current market cap and chain of each token in the result?

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%'

[User] I only want to see projects that raised more than $5,000,000. Please update the query.

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023-03%' AND p.investment_value > 5000000

[User] It seems some tokens are not matched because names are not identical. Can you try joining where the token_name contains the project_name (case-insensitive)?

[Assistant]
SELECT p.project_name, p.investment_value, p.rounds_name, t.token_symbol, t.price, t.market_cap, t.chain
FROM project_fundraising_record p
LEFT JOIN token_basic_info t ON LOWER(t.token_name) LIKE '%' || LOWER(p.project_name) || '%'
WHERE p.investment_date LIKE '2023-03%' AND p.investment_value > 5000000

[User] Show me the top 3 tokens with the highest 7-day price change percentage. Display their symbol, chain, and 7d price change.

[Assistant]
SELECT token_symbol, chain, price_change_percentage_7d
FROM token_basic_info
ORDER BY price_change_percentage_7d DESC
LIMIT 3


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.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )

[User] I want to list each security alongside another security issued by the same issuer.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id;

[User] Only include cases where the issuer has issued more than one security.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id
WHERE a.issuer_name IN (
  SELECT issuer_name
  FROM financial_services.securities
  GROUP BY issuer_name
  HAVING COUNT(*) > 1
);

[User] Sort the result by issuer_name, then by a.ticker_symbol.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id
WHERE a.issuer_name IN (
  SELECT issuer_name
  FROM financial_services.securities
  GROUP BY issuer_name
  HAVING COUNT(*) > 1
)
ORDER BY a.issuer_name, a.ticker_symbol;

[User] What is the count of securities for each security_type in the 'Technology' sector?

[Assistant] SELECT security_type, COUNT(*) as count FROM financial_services.securities WHERE sector = 'Technology' GROUP BY security_type;

[User] List all securities (security_id, ticker_symbol, security_name) that have a currency of 'EUR' and were last updated within the last 30 days, along with their exchange and sector information.

[Assistant] SELECT security_id, ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE currency = 'EUR' AND last_updated >= CURRENT_DATE - INTERVAL '30 days';

[User] Can you provide a summary of how many securities exist for each combination of exchange and sector?

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
GROUP BY exchange, sector;

[User] Please exclude any records where sector is NULL.

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector;

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

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector
ORDER BY total_count DESC;

[User] List all securities issued by 'Morgan Stanley' along with their ticker_symbol, security_name, and exchange. Then also show the sector for each.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley';

[User] Only include those securities that are traded on the NASDAQ exchange.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ';

[User] Add another filter: the security_type must be 'Equity'.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ' AND security_type = 'Equity';

[User] Finally, sort the results by ticker_symbol in ascending order.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ' AND security_type = 'Equity' ORDER BY ticker_symbol ASC;

[User] I’d like to find all pairs of securities that belong to the same sector.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector
WHERE a.security_id < b.security_id;

[User] Actually, only include pairs where the two securities are listed on different exchanges.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange;

[User] Also, I want the results sorted by sector, then by exchange_a.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange;

[User] One more thing: include both exchanges in the ORDER BY so that within each sector it’s sorted by exchange_a then exchange_b.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange, b.exchange;


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

[User] Show me all medications, their manufacturer, and NDC code for medications manufactured by 'Johnson & Johnson' or 'Roche'.

[Assistant] SELECT medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE manufacturer IN ('Johnson & Johnson', 'Roche');

[User] Actually, only include medications where the NDC code ends with '99'.

[Assistant] SELECT medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE manufacturer IN ('Johnson & Johnson', 'Roche') AND ndc_code LIKE '%99';

[User] Also return the description and sort the result by medication_name ascending.

[Assistant] SELECT medication_name, manufacturer, ndc_code, description FROM healthcare.medications WHERE manufacturer IN ('Johnson & Johnson', 'Roche') AND ndc_code LIKE '%99' ORDER BY medication_name ASC;

[User] How many medications does each manufacturer have?

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

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

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

[User] List the NDC code and description for any medication that has an NDC code starting with '5'.

[Assistant] SELECT ndc_code, description FROM healthcare.medications WHERE ndc_code LIKE '5%';

[User] Show the medication_id, medication_name, and manufacturer for all medication entries.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications;

[User] Filter to show only those where the manufacturer is specified (not null).

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE manufacturer IS NOT NULL;

[User] Also, include only medications where the generic name contains 'acid'.

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

[User] Can you add the NDC code to the result?

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

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

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

[User] List all combinations of manufacturers and generic names. For each combination, display the manufacturer, generic_name, and the number of medications.

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

[User] Only show combinations where there are at least 3 medications and exclude rows where generic_name is missing.

[Assistant] SELECT manufacturer, generic_name, COUNT(*) AS medication_count FROM healthcare.medications WHERE generic_name IS NOT NULL AND generic_name <> '' GROUP BY manufacturer, generic_name HAVING COUNT(*) >= 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)

[User] Find pairs of documents in the same case where one document is version 1 and the other is the highest version for that document_name, showing case_id, document_name, version1, latest_version, version1_upload_timestamp, and latest_upload_timestamp.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version;

[User] Actually, I only want the pairs where the difference between latest_version and version1 is at least 2.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version
WHERE (d2.version - d1.version) >= 2;

[User] Also include the uploaded_by_lawyer_id for both the version1 and the latest version documents.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp,
       d1.uploaded_by_lawyer_id AS version1_uploaded_by,
       d2.uploaded_by_lawyer_id AS latest_uploaded_by
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version
WHERE (d2.version - d1.version) >= 2;

[User] List document names and versions for documents that share the same case_id, showing each pair of versions.

[Assistant] SELECT d1.case_id, d1.document_name AS doc_name_v1, d1.version AS version1, d2.document_name AS doc_name_v2, d2.version AS version2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.case_id = d2.case_id AND d1.version < d2.version;

[User] Actually, I only want to compare the highest version against the second highest version per case.

[Assistant] SELECT d_prev.case_id, d_prev.document_name AS prev_doc, d_prev.version AS prev_version, d_latest.document_name AS latest_doc, d_latest.version AS latest_version FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id);

[User] Also include the upload timestamps and restrict to cases with at least three versions.

[Assistant] SELECT d_latest.case_id, d_prev.document_name AS prev_doc, d_prev.upload_timestamp AS prev_upload, d_latest.document_name AS latest_doc, d_latest.upload_timestamp AS latest_upload FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id) AND (SELECT COUNT(*) FROM legal_services.documents d2 WHERE d2.case_id = d_latest.case_id) >= 3;

[User] List pairs of documents uploaded by the same lawyer, showing uploader ID and both document names.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id;

[User] Only include pairs where the upload timestamps are within 7 days of each other.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id AND ABS(EXTRACT(EPOCH FROM (d1.upload_timestamp - d2.upload_timestamp)))/86400 <= 7;

[User] List the document name, type, version, and description for all documents.

[Assistant] SELECT document_name, document_type, version, description FROM documents;

[User] Only include documents where the description is not null.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL;

[User] Also, filter to only show documents with a version greater than 2.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2;

[User] Order the results by upload timestamp descending.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2 ORDER BY upload_timestamp DESC;

[User] Show me document names and upload timestamps for documents linked to cases that were opened after January 1, 2023.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01';

[User] Additionally, only include documents that have a version number greater than 1.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01' AND T1.version > 1;

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

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


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 blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address_id character varying(128) NOT NULL, -- identifier of the address associated with the wallet
    private_key text NOT NULL, -- private key of the wallet
    PRIMARY KEY (wallet_id)
)
CREATE TABLE blockchain.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    PRIMARY KEY (user_id)
)
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )

[User] Find users whose username contains 'admin'.

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username LIKE '%admin%';

[User] For these users, list their wallet IDs as well.

[Assistant] SELECT u.user_id, u.username, w.wallet_id FROM blockchain.users u JOIN blockchain.wallets w ON u.user_id = w.user_id WHERE u.username LIKE '%admin%';

[User] Only show wallets where the associated address has a balance greater than 1000.

[Assistant] SELECT u.user_id, u.username, w.wallet_id, a.balance FROM blockchain.users u JOIN blockchain.wallets w ON u.user_id = w.user_id JOIN blockchain.addresses a ON w.address_id = a.address_id WHERE u.username LIKE '%admin%' AND a.balance > 1000;

[User] Also, count how many such wallets each of these users has.

[Assistant] SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM blockchain.users u JOIN blockchain.wallets w ON u.user_id = w.user_id JOIN blockchain.addresses a ON w.address_id = a.address_id WHERE u.username LIKE '%admin%' AND a.balance > 1000 GROUP BY u.user_id, u.username;

[User] How many unique email domains are there among all registered users?

[Assistant] SELECT COUNT(DISTINCT SUBSTRING(email FROM POSITION('@' IN email) + 1)) AS unique_domains FROM blockchain.users;

[User] Can you list these domains along with the count of users for each domain?

[Assistant] SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain, COUNT(*) AS user_count FROM blockchain.users GROUP BY domain;

[User] Now show only domains that have more than 10 users.

[Assistant] SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain, COUNT(*) AS user_count FROM blockchain.users GROUP BY domain HAVING COUNT(*) > 10;

[User] Can you modify this to also include the earliest registration date for each domain?

[Assistant] SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain, COUNT(*) AS user_count, MIN(created_at) AS earliest_registration FROM blockchain.users GROUP BY domain HAVING COUNT(*) > 10;

[User] Show me all smart contracts along with the email address of the user who owns the wallet corresponding to the contract's creator address.

[Assistant]
SELECT sc.contract_id, sc.creator_address, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id;

[User] Can you also include the contract deployment timestamp and the wallet_id?

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp, w.wallet_id, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id;

[User] Actually, only show contracts created after July 1st, 2023.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp, w.wallet_id, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id
WHERE sc.timestamp > '2023-07-01';

[User] Sorry, I only want contracts where the user's email domain is 'gmail.com'.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp, w.wallet_id, u.email
FROM blockchain.smart_contracts sc
JOIN blockchain.wallets w ON sc.creator_address = w.address_id
JOIN blockchain.users u ON w.user_id = u.user_id
WHERE sc.timestamp > '2023-07-01' AND u.email LIKE '%@gmail.com';

[User] List all users along with the number of smart contracts created by wallets they own.

[Assistant]
SELECT u.user_id, u.username, COUNT(sc.contract_id) AS contracts_created
FROM blockchain.users u
JOIN blockchain.wallets w ON u.user_id = w.user_id
JOIN blockchain.smart_contracts sc ON w.address_id = sc.creator_address
GROUP BY u.user_id, u.username;

[User] Now only show users who created more than 3 smart contracts.

[Assistant]
SELECT u.user_id, u.username, COUNT(sc.contract_id) AS contracts_created
FROM blockchain.users u
JOIN blockchain.wallets w ON u.user_id = w.user_id
JOIN blockchain.smart_contracts sc ON w.address_id = sc.creator_address
GROUP BY u.user_id, u.username
HAVING COUNT(sc.contract_id) > 3;

[User] Also, sort the results by contracts_created in descending order.

[Assistant]
SELECT u.user_id, u.username, COUNT(sc.contract_id) AS contracts_created
FROM blockchain.users u
JOIN blockchain.wallets w ON u.user_id = w.user_id
JOIN blockchain.smart_contracts sc ON w.address_id = sc.creator_address
GROUP BY u.user_id, u.username
HAVING COUNT(sc.contract_id) > 3
ORDER BY contracts_created DESC;

[User] List the username and email for all users whose email address ends with '@example.com'.

[Assistant] SELECT username, email FROM blockchain.users WHERE email LIKE '%@example.com';

[User] Now, filter those results to only include users whose username starts with 'A'.

[Assistant] SELECT username, email FROM blockchain.users WHERE email LIKE '%@example.com' AND username LIKE 'A%';

[User] Can you provide a count of users for each unique email domain?

[Assistant] SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1), COUNT(*) FROM blockchain.users GROUP BY SUBSTRING(email FROM POSITION('@' IN email) + 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.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] List all insurance plans that will expire within the next 30 days, showing the patient IDs and subscriber names.

[Assistant]
SELECT patient_id, subscriber_name, policy_number, expiration_date
FROM healthcare.patient_insurance
WHERE expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '30 days');

[User] Actually, I only need to see plans that are primary insurance.

[Assistant]
SELECT patient_id, subscriber_name, policy_number, expiration_date
FROM healthcare.patient_insurance
WHERE expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '30 days')
AND is_primary = true;

[User] Can you also sort the results by expiration date in ascending order?

[Assistant]
SELECT patient_id, subscriber_name, policy_number, expiration_date
FROM healthcare.patient_insurance
WHERE expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '30 days')
AND is_primary = true
ORDER BY expiration_date ASC;

[User] List all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id;

[User] Actually, I only need patients who have more than 2 such plans.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Can you also include the earliest effective date among these plans for each patient?

[Assistant] SELECT patient_id, COUNT(*) AS plan_count, MIN(effective_date) AS earliest_effective_date FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Retrieve a list of all patient insurance policies, showing the subscriber name and the name of the insurance provider for the plan.

[Assistant] SELECT T1.subscriber_name, T2.insurance_provider FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plans AS T2 ON T1.plan_id = T2.plan_id;

[User] Refine this list to only include policies from the provider 'Aetna' and where the subscriber name contains 'Doe'.

[Assistant] SELECT T1.subscriber_name, T2.insurance_provider FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plans AS T2 ON T1.plan_id = T2.plan_id WHERE T2.insurance_provider = 'Aetna' AND T1.subscriber_name LIKE '%Doe%';

[User] Can you list all the policy numbers and their group_numbers for policies that will expire within the next 90 days from today?

[Assistant] SELECT policy_number, group_number FROM healthcare.patient_insurance WHERE expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days';

[User] Only show results where the group_number is not null.

[Assistant] SELECT policy_number, group_number FROM healthcare.patient_insurance WHERE expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days' AND group_number IS NOT NULL;

[User] Which patients have insurance policies that are effective between May 1st, 2023 and October 1st, 2023? Show their patient_id, policy_number, and effective_date, and also include the related plan_id.

[Assistant] SELECT patient_id, policy_number, effective_date, plan_id FROM healthcare.patient_insurance WHERE effective_date >= '2023-05-01' AND effective_date <= '2023-10-01';

[User] I only want to see policies that are still primary. Could you adjust the query to add that condition?

[Assistant] SELECT patient_id, policy_number, effective_date, plan_id FROM healthcare.patient_insurance WHERE effective_date >= '2023-05-01' AND effective_date <= '2023-10-01' AND is_primary = true;

[User] Actually, please also show only entries where the subscriber_name starts with the letter 'A'.

[Assistant] SELECT patient_id, policy_number, effective_date, plan_id FROM healthcare.patient_insurance WHERE effective_date >= '2023-05-01' AND effective_date <= '2023-10-01' AND is_primary = true AND subscriber_name LIKE 'A%';

[User] List the full name of patients whose primary insurance plan is provided by 'BlueCross BlueShield', along with the plan name.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield';

[User] Only include policies that have not expired.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield' AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE);

[User] Also include the policy number and filter to policies effective after '2023-01-01'.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name, T2.policy_number FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield' AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND T2.effective_date > '2023-01-01';

[User] Finally, order the results by the patient's last name and then first name.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name, T2.policy_number FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield' AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND T2.effective_date > '2023-01-01' ORDER BY T1.last_name, T1.first_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.components (
    component_id character varying(64) NOT NULL, -- unique identifier for the component
    part_number character varying(100) NOT NULL UNIQUE, -- manufacturer-specific part number
    component_name character varying(255) NOT NULL, -- descriptive name (e.g., Landing Gear Strut, Wing Spar)
    description text, -- detailed description
    material_id character varying(64), -- FK linking to the material used
    supplier_id character varying(64), -- FK linking to the supplier
    weight_kg numeric(10,3), -- weight of the component in kg
    cost_usd numeric(12,2), -- cost of the component in USD
    criticality_level character varying(20), -- e.g., 'High', 'Medium', 'Low'
    PRIMARY KEY (component_id)
)
CREATE TABLE manufacturing.materials (
    material_id character varying(64) NOT NULL,  -- unique identifier for the material
    material_name character varying(128) NOT NULL, -- common name (e.g., Titanium Alloy Grade 5, Carbon Fiber Prepreg)
    specification character varying(255), -- specification standard (e.g., AMS 4928)
    description text, -- detailed description of properties
    density_kg_m3 numeric(10, 4), -- density in kg per cubic meter
    tensile_strength_mpa integer, -- tensile strength in Megapascals
    PRIMARY KEY (material_id)
)
CREATE TABLE manufacturing.assembly_lines (
    line_id character varying(64) NOT NULL, -- unique identifier for the assembly line
    line_name character varying(128) NOT NULL, -- name of the line (e.g., Fuselage Assembly Line 1)
    location_building character varying(100), -- building where the line is located
    location_area character varying(100), -- specific area within the building
    aircraft_model_id character varying(64), -- FK to the primary aircraft model built on this line
    capacity_units_per_month integer, -- theoretical maximum output per month
    status character varying(50) NOT NULL, -- e.g., 'Active', 'Maintenance', 'Idle'
    PRIMARY KEY (line_id)
)
CREATE TABLE manufacturing.component_inventory (
    inventory_record_id character varying(64) NOT NULL, -- unique ID for this inventory record/batch
    component_id character varying(64) NOT NULL, -- FK to the component
    quantity integer NOT NULL, -- number of units of this component in stock for this batch
    location_warehouse character varying(100), -- warehouse identifier
    location_bin character varying(100), -- specific bin or shelf location
    received_date timestamp NOT NULL, -- when this batch was received
    expiry_date date, -- expiry date if applicable (e.g., for sealants, adhesives)
    batch_number character varying(100), -- supplier batch number
    last_updated timestamp NOT NULL, -- timestamp of the last update to this record
    PRIMARY KEY (inventory_record_id)
)

[User] 我想查询所有使用特定材料ID的组件信息，包括组件名称、零件编号和供应商ID，同时还需要获取该材料的名称和规格。

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id';

[User] 如果我想只显示重量大于10公斤的组件，应该怎么修改查询语句？

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10;

[User] 能不能再加上一个条件，只显示关键性等级为'High'的组件？

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10 AND c.criticality_level = 'High';

[User] 最后，请按组件名称的字母顺序对结果进行排序。

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10 AND c.criticality_level = 'High'
ORDER BY c.component_name ASC;

[User] 我想获取某个仓库中所有组件的库存信息，包括组件ID、库存数量和接收日期。

[Assistant]
SELECT ci.component_id, ci.quantity, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.location_warehouse = 'specific_warehouse';

[User] 如果我想只查看库存数量少于20的记录，应该怎么调整查询？

[Assistant]
SELECT ci.component_id, ci.quantity, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.location_warehouse = 'specific_warehouse' AND ci.quantity < 20;

[User] 能否再加上一个条件，排除接收日期在2022年之前的记录？

[Assistant]
SELECT ci.component_id, ci.quantity, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.location_warehouse = 'specific_warehouse' AND ci.quantity < 20 AND ci.received_date >= '2022-01-01';

[User] 请按库存数量从少到多排序结果。

[Assistant]
SELECT ci.component_id, ci.quantity, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.location_warehouse = 'specific_warehouse' AND ci.quantity < 20 AND ci.received_date >= '2022-01-01'
ORDER BY ci.quantity ASC;

[User] 我想查询某个特定组件ID的详细信息，包括组件名称、材料名称、材料密度以及供应商ID，同时还需要知道该组件在哪个装配线上的飞机型号ID。

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id';

[User] 如果我想只显示材料密度大于3000 kg/m3的记录，应该怎么修改？

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id' AND m.density_kg_m3 > 3000;

[User] 能否再加上一个条件，只显示装配线状态为'Active'的记录？

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id' AND m.density_kg_m3 > 3000 AND al.status = 'Active';

[User] 最后，请按材料密度从高到低对结果进行排序。

[Assistant]
SELECT c.component_id, c.component_name, m.material_name, m.density_kg_m3, c.supplier_id, al.aircraft_model_id
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
JOIN manufacturing.component_inventory ci ON c.component_id = ci.component_id
JOIN manufacturing.assembly_lines al ON ci.location_warehouse = al.location_building
WHERE c.component_id = 'specific_component_id' AND m.density_kg_m3 > 3000 AND al.status = 'Active'
ORDER BY m.density_kg_m3 DESC;

[User] 我想查询某个组件的检查记录，包括检查类型、检查结果和检查时间，同时还需要组件的名称和描述。

[Assistant]
SELECT i.inspection_type, i.result, i.inspection_timestamp, c.component_name, c.description
FROM manufacturing.inspections i
JOIN manufacturing.components c ON i.component_id = c.component_id
WHERE c.component_id = 'specific_component_id';

[User] 能不能只显示检查结果为'Fail'的记录？

[Assistant]
SELECT i.inspection_type, i.result, i.inspection_timestamp, c.component_name, c.description
FROM manufacturing.inspections i
JOIN manufacturing.components c ON i.component_id = c.component_id
WHERE c.component_id = 'specific_component_id' AND i.result = 'Fail';

[User] 如果我想进一步筛选出检查时间在过去一个月内的记录，应该怎么做？

[Assistant]
SELECT i.inspection_type, i.result, i.inspection_timestamp, c.component_name, c.description
FROM manufacturing.inspections i
JOIN manufacturing.components c ON i.component_id = c.component_id
WHERE c.component_id = 'specific_component_id' AND i.result = 'Fail' AND i.inspection_timestamp >= NOW() - INTERVAL '1 month';

[User] 请再加上检查备注信息，并按检查时间从新到旧排序。

[Assistant]
SELECT i.inspection_type, i.result, i.inspection_timestamp, c.component_name, c.description, i.remarks
FROM manufacturing.inspections i
JOIN manufacturing.components c ON i.component_id = c.component_id
WHERE c.component_id = 'specific_component_id' AND i.result = 'Fail' AND i.inspection_timestamp >= NOW() - INTERVAL '1 month'
ORDER BY i.inspection_timestamp DESC;

[User] 我想查询所有来自美国供应商的组件信息，包括组件名称、供应商名称和供应商的质量评分。

[Assistant]
SELECT c.component_name, s.supplier_name, s.quality_rating
FROM manufacturing.components c
JOIN manufacturing.suppliers s ON c.supplier_id = s.supplier_id
WHERE s.country = 'USA';

[User] 能不能加上组件的成本信息，并且只显示成本大于1000美元的组件？

[Assistant]
SELECT c.component_name, s.supplier_name, s.quality_rating, c.cost_usd
FROM manufacturing.components c
JOIN manufacturing.suppliers s ON c.supplier_id = s.supplier_id
WHERE s.country = 'USA' AND c.cost_usd > 1000;

[User] 如果我想进一步筛选出质量评分大于4.0的供应商，应该怎么改？

[Assistant]
SELECT c.component_name, s.supplier_name, s.quality_rating, c.cost_usd
FROM manufacturing.components c
JOIN manufacturing.suppliers s ON c.supplier_id = s.supplier_id
WHERE s.country = 'USA' AND c.cost_usd > 1000 AND s.quality_rating > 4.0;

[User] 请再加上按成本从高到低排序的结果。

[Assistant]
SELECT c.component_name, s.supplier_name, s.quality_rating, c.cost_usd
FROM manufacturing.components c
JOIN manufacturing.suppliers s ON c.supplier_id = s.supplier_id
WHERE s.country = 'USA' AND c.cost_usd > 1000 AND s.quality_rating > 4.0
ORDER BY c.cost_usd DESC;

[User] 我想了解某个组件的库存情况，包括库存数量、仓库位置和接收日期。

[Assistant]
SELECT ci.quantity, ci.location_warehouse, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.component_id = 'specific_component_id';

[User] 如果我想查询特定批次号的库存信息，应该怎么修改？

[Assistant]
SELECT ci.quantity, ci.location_warehouse, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.component_id = 'specific_component_id' AND ci.batch_number = 'specific_batch_number';

[User] 如果我想进一步筛选出接收日期在2023年之后的库存记录呢？

[Assistant]
SELECT ci.quantity, ci.location_warehouse, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.component_id = 'specific_component_id' AND ci.batch_number = 'specific_batch_number' AND ci.received_date > '2023-01-01';

[User] 请再加上按接收日期从新到旧排序。

[Assistant]
SELECT ci.quantity, ci.location_warehouse, ci.received_date
FROM manufacturing.component_inventory ci
WHERE ci.component_id = 'specific_component_id' AND ci.batch_number = 'specific_batch_number' AND ci.received_date > '2023-01-01'
ORDER BY ci.received_date DESC;