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.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )

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

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

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

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

[User] List the first and last names of all doctors whose email address ends with '@hospital.org'.

[Assistant] SELECT first_name, last_name FROM healthcare.doctors WHERE email LIKE '%@hospital.org';

[User] Find pairs of doctors who work at the same hospital but have different specialties. Show the full name of both doctors and their shared hospital affiliation ID.

[Assistant] SELECT d1.first_name AS doctor1_first_name, d1.last_name AS doctor1_last_name, d2.first_name AS doctor2_first_name, d2.last_name AS doctor2_last_name, d1.hospital_affiliation_id FROM healthcare.doctors d1 JOIN healthcare.doctors d2 ON d1.hospital_affiliation_id = d2.hospital_affiliation_id AND d1.doctor_id <> d2.doctor_id WHERE d1.specialty <> d2.specialty;

[User] Show me the first name, last name, and license number for all doctors whose specialty is 'Pediatrics'.

[Assistant] SELECT first_name, last_name, license_number FROM healthcare.doctors WHERE specialty = 'Pediatrics';

[User] Now, narrow down the list to include only those doctors whose email address contains '@hospital'.

[Assistant] SELECT first_name, last_name, license_number FROM healthcare.doctors WHERE specialty = 'Pediatrics' AND email LIKE '%@hospital%';

[User] Could you also show their hospital affiliation ID?

[Assistant] SELECT first_name, last_name, license_number, hospital_affiliation_id FROM healthcare.doctors WHERE specialty = 'Pediatrics' AND email LIKE '%@hospital%';

[User] Finally, order the results by last name in ascending order.

[Assistant] SELECT first_name, last_name, license_number, hospital_affiliation_id FROM healthcare.doctors WHERE specialty = 'Pediatrics' AND email LIKE '%@hospital%' ORDER BY last_name ASC;

[User] Show me all doctors who are affiliated with 'hospital_123', including their full names and specialties.

[Assistant] SELECT first_name, last_name, specialty FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123';

[User] Can you also include their phone numbers and email addresses in the result?

[Assistant] SELECT first_name, last_name, specialty, phone_number, email FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123';

[User] Only show doctors whose specialty is 'Pediatrics'.

[Assistant] SELECT first_name, last_name, specialty, phone_number, email FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123' AND specialty = 'Pediatrics';

[User] I got an error that says column 'speciality' does not exist. Can you check and fix the query?

[Assistant] SELECT first_name, last_name, specialty, phone_number, email FROM healthcare.doctors WHERE hospital_affiliation_id = 'hospital_123' AND specialty = 'Pediatrics';


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.diagnoses ( diagnosis_id.text, 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 )

[User] List the diagnosis_id, patient_id, and doctor_id for all diagnoses with status 'Pending' and is_chronic set to TRUE.

[Assistant] SELECT diagnosis_id, patient_id, doctor_id FROM healthcare.diagnoses WHERE status = 'Pending' AND is_chronic = TRUE;

[User] List each patient and the total number of chronic diagnoses they have received, as well as the number of distinct doctors who have made those diagnoses.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY patient_id;

[User] Only include patients who have received diagnoses recorded as 'Active' status.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE AND status = 'Active' GROUP BY patient_id;

[User] Show all diagnosis codes and descriptions for patients diagnosed by doctor 'doctor_789'.

[Assistant] SELECT patient_id, diagnosis_code, description FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789';

[User] Filter the results to include only diagnoses made after '2023-01-01'.

[Assistant] SELECT patient_id, diagnosis_code, description FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789' AND diagnosis_date > '2023-01-01';

[User] Can you also show whether each diagnosis is chronic?

[Assistant] SELECT patient_id, diagnosis_code, description, is_chronic FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789' AND diagnosis_date > '2023-01-01';

[User] Now, only include records where the diagnosis status is 'Active'.

[Assistant] SELECT patient_id, diagnosis_code, description, is_chronic FROM healthcare.diagnoses WHERE doctor_id = 'doctor_789' AND diagnosis_date > '2023-01-01' AND status = 'Active';

[User] How many unique patients have been diagnosed with code_type 'ICD-10'?

[Assistant] SELECT COUNT(DISTINCT patient_id) FROM healthcare.diagnoses WHERE code_type = 'ICD-10';

[User] Find all unique diagnosis codes that are associated with more than one doctor, and show how many doctors are linked to each code.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT doctor_id) AS doctor_count FROM healthcare.diagnoses GROUP BY diagnosis_code HAVING COUNT(DISTINCT doctor_id) > 1;

[User] Also, show only codes that are used after January 1st, 2023.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT doctor_id) AS doctor_count FROM healthcare.diagnoses WHERE diagnosis_date > '2023-01-01' GROUP BY diagnosis_code HAVING COUNT(DISTINCT doctor_id) > 1;

[User] Can you show me the total number of diagnosis records for each doctor, along with the doctor's ID? Please include only those diagnoses marked as 'chronic'.

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id;

[User] Now, can you also include the average number of chronic diagnoses per patient for each doctor in the results?

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses, COUNT(*)::FLOAT / COUNT(DISTINCT patient_id) AS avg_chronic_per_patient FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id;

[User] Please filter the results to only include doctors with at least 5 chronic diagnoses.

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses, COUNT(*)::FLOAT / COUNT(DISTINCT patient_id) AS avg_chronic_per_patient FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id HAVING COUNT(*) >= 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 trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )

[User] Show me the usernames and emails of all users who have placed at least one 'buy' order for the asset named 'Bitcoin'.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM trading_platform.users AS T1 JOIN trading_platform.orders AS T2 ON T1.user_id = T2.user_id JOIN trading_platform.assets AS T3 ON T2.asset_id = T3.asset_id WHERE T2.order_type = 'buy' AND T3.name = 'Bitcoin'

[User] From that list, only show the users whose KYC status is currently 'pending'.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM trading_platform.users AS T1 JOIN trading_platform.orders AS T2 ON T1.user_id = T2.user_id JOIN trading_platform.assets AS T3 ON T2.asset_id = T3.asset_id JOIN trading_platform.kyc_audit AS T4 ON T1.user_id = T4.user_id WHERE T2.order_type = 'buy' AND T3.name = 'Bitcoin' AND T4.status = 'pending'

[User] List the names and symbols of all assets that have at least one associated metadata entry in the metadata table.

[Assistant] SELECT DISTINCT T1.name, T1.symbol FROM trading_platform.assets AS T1 JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id

[User] For these assets, also show the total count of metadata entries associated with each one.

[Assistant] SELECT T1.name, T1.symbol, COUNT(T2.metadata_id) AS metadata_count FROM trading_platform.assets AS T1 JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id GROUP BY T1.asset_id, T1.name, T1.symbol

[User] Now, filter the results to only show assets that have more than 2 metadata entries.

[Assistant] SELECT T1.name, T1.symbol, COUNT(T2.metadata_id) AS metadata_count FROM trading_platform.assets AS T1 JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id GROUP BY T1.asset_id, T1.name, T1.symbol HAVING COUNT(T2.metadata_id) > 2

[User] The previous query only shows assets with metadata. Please include *all* assets, showing 0 metadata entries for those that have none, and order the list by the metadata count in descending order.

[Assistant] SELECT T1.name, T1.symbol, COUNT(T2.metadata_id) AS metadata_count FROM trading_platform.assets AS T1 LEFT JOIN trading_platform.metadata AS T2 ON T1.asset_id = T2.asset_id GROUP BY T1.asset_id, T1.name, T1.symbol ORDER BY metadata_count DESC

[User] What is the total sum of all amounts for all UTXOs in the system, regardless of whether they are spent or unspent?

[Assistant] SELECT SUM(amount) FROM trading_platform.utxos

[User] I want a report of user IDs with their KYC status and the count of wallets they have.

[Assistant]
SELECT k.user_id, k.status, COUNT(w.wallet_id) AS wallet_count
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.wallets w ON k.user_id = w.user_id
GROUP BY k.user_id, k.status;

[User] Filter it to only include approved users whose wallets were created this month.

[Assistant]
SELECT k.user_id, k.status, COUNT(w.wallet_id) AS wallet_count
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.wallets w ON k.user_id = w.user_id AND w.created_at >= date_trunc('month', CURRENT_DATE)
WHERE k.status = 'approved'
GROUP BY k.user_id, k.status;

[User] Also include how many unread notifications each user has.

[Assistant]
SELECT k.user_id, k.status, COUNT(DISTINCT w.wallet_id) AS wallet_count,
       COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) AS unread_notifications
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.wallets w ON k.user_id = w.user_id AND w.created_at >= date_trunc('month', CURRENT_DATE)
LEFT JOIN trading_platform.notifications n ON k.user_id = n.user_id
WHERE k.status = 'approved'
GROUP BY k.user_id, k.status;

[User] Limit the results to the top 10 users with the highest wallet counts.

[Assistant]
SELECT user_id, status, wallet_count, unread_notifications
FROM (
  SELECT k.user_id, k.status, COUNT(DISTINCT w.wallet_id) AS wallet_count,
         COUNT(n.notification_id) FILTER (WHERE n.read_at IS NULL) AS unread_notifications
  FROM trading_platform.kyc_audit k
  LEFT JOIN trading_platform.wallets w ON k.user_id = w.user_id AND w.created_at >= date_trunc('month', CURRENT_DATE)
  LEFT JOIN trading_platform.notifications n ON k.user_id = n.user_id
  WHERE k.status = 'approved'
  GROUP BY k.user_id, k.status
) sub
ORDER BY wallet_count DESC
LIMIT 10;

[User] I need to get the total trading volume for each asset along with the asset name.

[Assistant]
SELECT a.asset_id, a.name, SUM(t.quantity * t.price) AS total_volume
FROM trading_platform.trades t
JOIN trading_platform.assets a ON t.asset_id = a.asset_id
GROUP BY a.asset_id, a.name;

[User] Show only the top 5 assets by total volume since '2024-01-01'.

[Assistant]
SELECT a.asset_id, a.name, SUM(t.quantity * t.price) AS total_volume
FROM trading_platform.trades t
JOIN trading_platform.assets a ON t.asset_id = a.asset_id
WHERE t.traded_at >= '2024-01-01'
GROUP BY a.asset_id, a.name
ORDER BY total_volume DESC
LIMIT 5;

[User] Give me all unspent UTXOs for address '1A2b3C4d5E', sorted by amount descending.

[Assistant]
SELECT utxo_id, transaction_id, output_index, address, amount
FROM trading_platform.utxos
WHERE address = '1A2b3C4d5E' AND spent = FALSE
ORDER BY amount 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 insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Show the document ID, claim ID, and file name for all documents with a MIME type starting with 'image/'.

[Assistant] SELECT document_id, claim_id, file_name FROM insurance.claim_documents WHERE mime_type LIKE 'image/%';

[User] Can you also include the uploaded_by user and only show documents uploaded after January 1, 2023?

[Assistant] SELECT document_id, claim_id, file_name, uploaded_by FROM insurance.claim_documents WHERE mime_type LIKE 'image/%' AND uploaded_at >= '2023-01-01';

[User] List all claim IDs that have both an 'Accident Report' and a 'Damage Assessment' document type.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE document_type IN ('Accident Report', 'Damage Assessment')
GROUP BY claim_id
HAVING COUNT(DISTINCT document_type) = 2;

[User] This returns claim IDs even if they have only multiple 'Accident Report' entries and no 'Damage Assessment'. I want to ensure each claim_id has at least one of each type.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0;

[User] Also, only include documents uploaded after '2024-01-01'.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE uploaded_at > '2024-01-01'
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0;

[User] Finally, sort the result by claim_id in ascending order.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE uploaded_at > '2024-01-01'
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0
ORDER BY claim_id ASC;

[User] How many documents exist for each document_type? Return document_type and the count.

[Assistant]
SELECT document_type,
       COUNT(*) AS document_count
FROM insurance.claim_documents
GROUP BY document_type;

[User] Show me all documents uploaded in 2024 that do not have a description.

[Assistant]
SELECT document_id, file_name, uploaded_at
FROM insurance.claim_documents
WHERE uploaded_at >= '2024-01-01'
  AND uploaded_at < '2025-01-01'
  AND (description IS NULL OR description = '');

[User] Find the claim ID and the total number of documents associated with each claim ID that has more than 10 documents.

[Assistant] SELECT claim_id, COUNT(*) FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(*) > 10;

[User] Which document types have been used for more than 100 documents, and what is the total file size across all documents of each such type?

[Assistant]
SELECT document_type, COUNT(*) AS document_count, SUM(file_size_bytes) AS total_file_size_bytes
FROM insurance.claim_documents
GROUP BY document_type
HAVING COUNT(*) > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

[User] How many insurance policies does each subscriber have? Please display the subscriber name and policy count.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name;

[User] Please include only subscribers who have more than one policy.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name HAVING COUNT(*) > 1;

[User] List patient insurance details, including patient ID, policy number, and subscriber name, along with the corresponding plan name for each entry.

[Assistant] SELECT T1.patient_id, T1.policy_number, T1.subscriber_name, T2.plan_name FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id

[User] Modify the query to only include entries where the insurance plan type is 'PPO'.

[Assistant] SELECT T1.patient_id, T1.policy_number, T1.subscriber_name, T2.plan_name FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'PPO'

[User] Further filter the results to show only policies marked as primary (is_primary = true) and sort the output by subscriber name in ascending order.

[Assistant] SELECT T1.patient_id, T1.policy_number, T1.subscriber_name, T2.plan_name FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'PPO' AND T1.is_primary = true ORDER BY T1.subscriber_name ASC

[User] Show me a list of all insurance policies along with the subscriber's name and the effective and expiration dates for each policy, including the associated plan ID.

[Assistant] SELECT policy_number, subscriber_name, effective_date, expiration_date, plan_id FROM healthcare.patient_insurance;

[User] Now, I only want to see policies that are primary and do not have a group number assigned. Please also include the patient_id.

[Assistant] SELECT policy_number, subscriber_name, effective_date, expiration_date, plan_id, patient_id FROM healthcare.patient_insurance WHERE is_primary = TRUE AND group_number IS NULL;

[User] Actually, please filter further to only show policies that expire after 2024-12-31.

[Assistant] SELECT policy_number, subscriber_name, effective_date, expiration_date, plan_id, patient_id FROM healthcare.patient_insurance WHERE is_primary = TRUE AND group_number IS NULL AND expiration_date > '2024-12-31';

[User] I need a list showing each patient along with their current primary insurance policy number and their immediately previous primary policy number.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.effective_date < ci.effective_date
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE)
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.effective_date < ci.effective_date
  );

[User] Actually, I only want to include previous policies that have an expiration_date set.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.expiration_date IS NOT NULL
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.expiration_date IS NOT NULL
        AND pii.effective_date < ci.effective_date
  )
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE);

[User] How many active insurance policies are there for each plan_id? Show plan_id and active_count.

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

[User] For each subscriber, count the number of insurance plans they have where the plan type is 'HMO'. Show the subscriber name and their count.

[Assistant] SELECT T1.subscriber_name, COUNT(T2.plan_id) FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'HMO' GROUP BY T1.subscriber_name

[User] Filter the list from the previous query to include only subscribers who are associated with more than 3 'HMO' plans.

[Assistant] SELECT T1.subscriber_name, COUNT(T2.plan_id) FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'HMO' GROUP BY T1.subscriber_name HAVING COUNT(T2.plan_id) > 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
Use Hashes. Key pattern: 'component:<component_id>'. Example: HSET component:LGSTRUT01 part_number "PN-5521-A" component_name "Landing Gear Strut" material_id "mat:TI64" supplier_id "sup:ACME_AERO" ... Consider Sets for reverse lookups (e.g., 'material_components:<material_id>' -> Set<component_id>).

[User] Can you help me get a list of components and their associated materials, including the supplier information for each component?

[Assistant]
SMEMBERS material_components:<material_id>
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> material_id

[User] Can you filter this to show only components from a specific material ID?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> material_id

[User] What if I want to see only components from a specific supplier as well?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id

[User] Can you also include the component name and sort the results by component name?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id
HGET component:<component_id> component_name
SORT BY component_name ASC

[User] I need to find all components associated with a specific supplier. Can you help with that?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE

[User] Can you also show me the material ID for each of these components?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id

[User] What if I want to exclude components with a specific material ID?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id
IF HGET component:<component_id> material_id != 'mat:TI64' THEN INCLUDE

[User] Can you add the component name to the result as well?

[Assistant]
HGETALL component:<component_id>
IF HGET component:<component_id> supplier_id = 'sup:ACME_AERO' THEN INCLUDE
HGET component:<component_id> material_id
IF HGET component:<component_id> material_id != 'mat:TI64' THEN INCLUDE
HGET component:<component_id> component_name

[User] Can you help me retrieve the list of components made of a specific material along with their supplier details?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id

[User] Can you also include the part number for each component in the result?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number

[User] If I want to filter out components from a specific supplier, how can I modify the query?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number
IF HGET component:<component_id> supplier_id != 'sup:ACME_AERO' THEN INCLUDE

[User] Can you also sort the results based on the part number?

[Assistant]
SMEMBERS material_components:mat:TI64
HGETALL component:<component_id>
HGET component:<component_id> supplier_id
HGET component:<component_id> part_number
IF HGET component:<component_id> supplier_id != 'sup:ACME_AERO' THEN INCLUDE
SORT BY part_number 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 token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE 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_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )

[User] Which exchange holds the largest total USD value of the token with the highest 24h price increase in the 'AI' narrative, and what is that value?

[Assistant]
SELECT ctb.exchange, SUM(ctb.usd_value) AS total_usd_value
FROM token_basic_info tbi
JOIN cex_token_balance ctb ON tbi.token_address = ctb.token_address AND tbi.chain = ctb.chain
WHERE tbi.narrative = 'AI' AND tbi.token_symbol = (
    SELECT token_symbol
    FROM token_basic_info
    WHERE narrative = 'AI'
    ORDER BY price_change_percentage_24h DESC
    LIMIT 1
)
GROUP BY ctb.exchange
ORDER BY total_usd_value DESC
LIMIT 1;

[User] Actually, can you show the top 2 exchanges by total USD value instead of just the top one?

[Assistant]
SELECT ctb.exchange, SUM(ctb.usd_value) AS total_usd_value
FROM token_basic_info tbi
JOIN cex_token_balance ctb ON tbi.token_address = ctb.token_address AND tbi.chain = ctb.chain
WHERE tbi.narrative = 'AI' AND tbi.token_symbol = (
    SELECT token_symbol
    FROM token_basic_info
    WHERE narrative = 'AI'
    ORDER BY price_change_percentage_24h DESC
    LIMIT 1
)
GROUP BY ctb.exchange
ORDER BY total_usd_value DESC
LIMIT 2;

[User] Great, now also include the chain and current price of this token in the results.

[Assistant]
SELECT ctb.exchange, ctb.chain, SUM(ctb.usd_value) AS total_usd_value, tbi.price
FROM token_basic_info tbi
JOIN cex_token_balance ctb ON tbi.token_address = ctb.token_address AND tbi.chain = ctb.chain
WHERE tbi.narrative = 'AI' AND tbi.token_symbol = (
    SELECT token_symbol
    FROM token_basic_info
    WHERE narrative = 'AI'
    ORDER BY price_change_percentage_24h DESC
    LIMIT 1
)
GROUP BY ctb.exchange, ctb.chain, tbi.price
ORDER BY total_usd_value DESC
LIMIT 2;

[User] Which are the top 3 tokens on BSC by total USD value held by all CEXs, and what is their narrative and current price?

[Assistant]
SELECT ctb.token_symbol, tbi.narrative, tbi.price, SUM(ctb.usd_value) AS total_usd_value
FROM cex_token_balance ctb
JOIN token_basic_info tbi ON ctb.token_symbol = tbi.token_symbol AND ctb.chain = tbi.chain
WHERE ctb.chain = 'BSC'
GROUP BY ctb.token_symbol, tbi.narrative, tbi.price
ORDER BY total_usd_value DESC
LIMIT 3;

[User] Can you also show, for each token, the number of CEX addresses holding it?

[Assistant]
SELECT ctb.token_symbol, tbi.narrative, tbi.price, COUNT(DISTINCT ctb.address) AS cex_address_count, SUM(ctb.usd_value) AS total_usd_value
FROM cex_token_balance ctb
JOIN token_basic_info tbi ON ctb.token_symbol = tbi.token_symbol AND ctb.chain = tbi.chain
WHERE ctb.chain = 'BSC'
GROUP BY ctb.token_symbol, tbi.narrative, tbi.price
ORDER BY total_usd_value DESC
LIMIT 3;

[User] Only include tokens with total USD value above 1,000,000.

[Assistant]
SELECT ctb.token_symbol, tbi.narrative, tbi.price, COUNT(DISTINCT ctb.address) AS cex_address_count, SUM(ctb.usd_value) AS total_usd_value
FROM cex_token_balance ctb
JOIN token_basic_info tbi ON ctb.token_symbol = tbi.token_symbol AND ctb.chain = tbi.chain
WHERE ctb.chain = 'BSC'
GROUP BY ctb.token_symbol, tbi.narrative, tbi.price
HAVING SUM(ctb.usd_value) > 1000000
ORDER BY total_usd_value DESC
LIMIT 3;

[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 1;

[User] What is the average ROI for smart money addresses on the Binance chain?

[Assistant] SELECT AVG(roi) FROM smart_money_profit WHERE chain = 'Binance';

[User] Show me tokens with a 24-hour trading volume over $1,000,000 from DEX pools that also have a positive net flow from smart money addresses. Display the token symbol, chain, 24h volume, and net flow.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0;

[User] Okay, now refine the results to only include tokens where the smart money ROI is greater than 5 (500%) and the realized ratio is above 0.5.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Add the token's current price from the basic info table and its narrative category to the results.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Order the final list by 24-hour trading volume descending and show the top 10.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5 ORDER BY tdi.volume_24h DESC LIMIT 10;

[User] List tokens that have a price increase of more than 10% in the last 24 hours and belong to a narrative with a trend rank of 10 or better. For these tokens, show their symbol, chain, 24h price change, the narrative, and the narrative's trend rank.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10;

[User] Now, for these same tokens, include their smart money Net Flow and ROI.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank, T3.net_flow, T3.roi FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative INNER JOIN smart_money_token_performance AS T3 ON T1.token_symbol = T3.token_symbol AND T1.chain = T3.chain WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10;

[User] Filter the results to only include tokens where the Smart Money Net Flow is greater than 10000 and the ROI is greater than 2.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank, T3.net_flow, T3.roi FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative INNER JOIN smart_money_token_performance AS T3 ON T1.token_symbol = T3.token_symbol AND T1.chain = T3.chain WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10 AND T3.net_flow > 10000 AND T3.roi > 2;

[User] Order the results by Smart Money Net Flow in descending order and show the top 5.

[Assistant] SELECT T1.token_symbol, T1.chain, T1.price_change_percentage_24h, T1.narrative, T2.trend_rank, T3.net_flow, T3.roi FROM token_basic_info AS T1 INNER JOIN narrative_info AS T2 ON T1.narrative = T2.narrative INNER JOIN smart_money_token_performance AS T3 ON T1.token_symbol = T3.token_symbol AND T1.chain = T3.chain WHERE T1.price_change_percentage_24h > 10 AND T2.trend_rank <= 10 AND T3.net_flow > 10000 AND T3.roi > 2 ORDER BY T3.net_flow 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 train_station_management.train_cars (
    car_id character varying(64) NOT NULL, -- Unique identifier for the train car
    train_id character varying(64) NOT NULL, -- Foreign key referencing trains
    car_number character varying(10) NOT NULL, -- Identifier of the car within the train set
    car_type character varying(64) NOT NULL, -- e.g., Locomotive, Passenger, Sleeper, Dining, Baggage
    class character varying(32), -- e.g., First, Business, Economy (null for non-passenger cars)
    capacity integer, -- Passenger capacity of this specific car (null for non-passenger cars)
    features text, -- Comma-separated list of features (e.g., 'WiFi', 'Power Outlet', 'Accessible Restroom')
    PRIMARY KEY (car_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id)
)
CREATE TABLE train_station_management.routes (
    route_id character varying(64) NOT NULL, -- Unique identifier for the route
    route_name character varying(128) NOT NULL, -- Name of the route (e.g., 'Northeast Corridor')
    description text, -- Description of the route
    origin_station_id character varying(64) NOT NULL, -- Starting station
    destination_station_id character varying(64) NOT NULL, -- Final station
    is_active boolean NOT NULL DEFAULT true, -- Is the route currently operational?
    PRIMARY KEY (route_id),
    FOREIGN KEY (origin_station_id) REFERENCES train_station_management.stations(station_id),
    FOREIGN KEY (destination_station_id) REFERENCES train_station_management.stations(station_id)
)
CREATE TABLE train_station_management.tickets (
    ticket_id character varying(64) NOT NULL, -- Unique identifier for the ticket
    booking_id character varying(64) NOT NULL, -- Foreign key referencing the booking
    car_id character varying(64) NOT NULL, -- Foreign key referencing the train car
    seat_number character varying(10), -- Assigned seat number (e.g., '12A')
    ticket_type character varying(32) NOT NULL DEFAULT 'Adult', -- e.g., Adult, Child, Senior, Student
    price numeric(10, 2) NOT NULL, -- Price of this specific ticket
    is_checked_in boolean NOT NULL DEFAULT false, -- Has the passenger checked in with this ticket?
    qr_code_data text, -- Data for generating a QR code for the ticket
    PRIMARY KEY (ticket_id),
    FOREIGN KEY (booking_id) REFERENCES train_station_management.bookings(booking_id),
    FOREIGN KEY (car_id) REFERENCES train_station_management.train_cars(car_id)
)

[User] Can you help me find the total passenger capacity for each train car on a specific route with route_id 'RT123'?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL;

[User] Can you modify the query to include only passenger cars with a capacity greater than 50?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you also add the route name and description to the result?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity, r.route_name, r.description
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you retrieve the total number of tickets sold for each car type?

[Assistant]
SELECT tc.car_type, COUNT(t.ticket_id) AS total_tickets
FROM train_station_management.train_cars tc
JOIN train_station_management.tickets t ON tc.car_id = t.car_id
GROUP BY tc.car_type;

[User] I need to find all tickets for a specific route 'RT456' along with the car details and route information.

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456';

[User] Can you filter this to show only tickets that have been checked in?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

[User] Can you also add the ticket type to the results?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, t.ticket_type, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

[User] Can you assist me in finding all staff members assigned to schedules for a specific route with route_id 'RT456', including the train details and schedule status?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.schedules s ON s.train_id = st.primary_station_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] I noticed the query might not be correct. Can you revise it to ensure it connects staff to schedules properly through their primary station or related data?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] Can you filter the results to include only staff with the role of 'Engineer' and schedules with status 'On Time'?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456' AND st.role = 'Engineer' AND s.status = 'On Time';

[User] Can you help me get the total number of passenger cars for each train car type in the database?

[Assistant]
SELECT car_type, COUNT(*) as total_cars
FROM train_station_management.train_cars
WHERE car_type = 'Passenger'
GROUP BY car_type;

[User] Can you help me retrieve the details of all bookings for a specific route with route_id 'RT789', including the passenger names and the scheduled departure times?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789';

[User] Can you modify the query to include only bookings with a status of 'Pending'?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

[User] Can you also add the route name and origin station ID to the results?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

[User] Can you sort the results by departure datetime in descending order?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending'
ORDER BY s.departure_datetime 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 healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )

[User] For each location, what is the average appointment duration? Show location_id and the average duration.

[Assistant] SELECT location_id, AVG(duration_minutes) FROM healthcare.appointments GROUP BY location_id;

[User] Show all appointments that have 'follow-up' mentioned in the notes field.

[Assistant] SELECT * FROM healthcare.appointments WHERE notes LIKE '%follow-up%';

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id AS current_appointment, next_appointment_id, and waiting_time in minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 ) ;

[User] Only include waiting times less than 30 minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 )
WHERE EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 < 30;

[User] Get the total number of appointments grouped by status.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status;

[User] Now filter to include only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;

[User] Find overlapping appointments for each doctor. Return doctor_id, appointment_id_1, appointment_id_2, and overlap duration in minutes.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes);

[User] Exclude overlaps less than 15 minutes.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes)
HAVING (EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60) >= 15;

[User] Also only include overlaps where status is 'Scheduled' for both appointments.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.status = 'Scheduled'
  AND b.status = 'Scheduled'
  AND a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes)
HAVING (EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60) >= 15;

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id, next_appointment_id, and the waiting time in minutes between them.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   );

[User] Now include only the pairs where the waiting time is less than 30 minutes.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   )
WHERE EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 < 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 social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] List the content and comment ID for all comments made by users with private profiles.

[Assistant] SELECT c.comment_id, c.content FROM social_media.comments AS c JOIN social_media.user_settings AS us ON c.user_id = us.user_id WHERE us.private_profile = TRUE;

[User] Only show comments created in the year 2024.

[Assistant] SELECT c.comment_id, c.content FROM social_media.comments AS c JOIN social_media.user_settings AS us ON c.user_id = us.user_id WHERE us.private_profile = TRUE AND c.created_at >= '2024-01-01' AND c.created_at < '2025-01-01';

[User] List the conversation IDs and user IDs for participants who have email notifications enabled.

[Assistant] SELECT cp.conversation_id, cp.user_id FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE;

[User] Now, only include those users whose profile is set to private.

[Assistant] SELECT cp.conversation_id, cp.user_id FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE AND us.private_profile = TRUE;

[User] Also, filter the results to include only participants who joined after a specific date, say '2023-01-01'.

[Assistant] SELECT cp.conversation_id, cp.user_id FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE AND us.private_profile = TRUE AND cp.joined_at > '2023-01-01';

[User] Instead of user ID, can you show their theme setting and order the results by the join date ascending?

[Assistant] SELECT cp.conversation_id, us.theme, cp.joined_at FROM social_media.conversation_participants AS cp JOIN social_media.user_settings AS us ON cp.user_id = us.user_id WHERE us.email_notifications_enabled = TRUE AND us.private_profile = TRUE AND cp.joined_at > '2023-01-01' ORDER BY cp.joined_at ASC;

[User] Show me the content and creation time of comments made on posts authored by the user with ID 'user_X'.

[Assistant] SELECT T1.content, T1.created_at FROM social_media.comments AS T1 JOIN social_media.posts AS T2 ON T1.post_id = T2.post_id WHERE T2.user_id = 'user_X';

[User] Can you also include the username of the user who made each comment?

[Assistant] SELECT T1.content, T1.created_at, T3.username FROM social_media.comments AS T1 JOIN social_media.posts AS T2 ON T1.post_id = T2.post_id JOIN social_media.users AS T3 ON T1.user_id = T3.user_id WHERE T2.user_id = 'user_X';

[User] List the usernames of users who have commented on posts that are not replies to other comments.

[Assistant] SELECT DISTINCT T2.username FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL;

[User] Can you filter this to only include users who have made more than one such comment?

[Assistant] SELECT T2.username FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL GROUP BY T2.username HAVING COUNT(T1.comment_id) > 1;

[User] Also, show the total count of these top-level comments for each user and order the results by the count descending.

[Assistant] SELECT T2.username, COUNT(T1.comment_id) AS top_level_comment_count FROM social_media.comments AS T1 JOIN social_media.users AS T2 ON T1.user_id = T2.user_id WHERE T1.parent_comment_id IS NULL GROUP BY T2.username HAVING COUNT(T1.comment_id) > 1 ORDER BY top_level_comment_count DESC;

[User] Count the number of comments that have been updated since they were first created.

[Assistant] SELECT COUNT(*) FROM social_media.comments WHERE updated_at > created_at;

[User] List all comment IDs that have not received any likes.

[Assistant] SELECT T1.comment_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;

[User] Can you also include the content of these comments and the post_id they belong to?

[Assistant] SELECT T1.comment_id, T1.content, T1.post_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Show me the names and URLs of all DApps, and for each DApp, list the KYC status and last review date for all users who have an audit entry.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
ORDER BY d.name, k.user_id;

[User] I only want DApps whose name includes the word 'market', and for KYC audits, show only those with status 'approved'.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.name ILIKE '%market%' AND k.status = 'approved'
ORDER BY d.name, k.user_id;

[User] List the names of all DApps whose description contains the word 'auction' along with the user IDs of anyone who has had a KYC audit.

[Assistant]
SELECT d.name AS dapp_name, k.user_id
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
ORDER BY d.name, k.user_id;

[User] Just show KYC audits with a status that is not 'approved'.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id;

[User] Actually, I want to include the reviewed_at time for each audit result too.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] Filter further to only show audits reviewed after January 1, 2024.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
  AND k.reviewed_at > '2024-01-01'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] How many unique users have a KYC audit record with status 'pending'?

[Assistant]
SELECT COUNT(DISTINCT user_id) AS pending_kyc_users
FROM trading_platform.kyc_audit
WHERE status = 'pending';

[User] Show me all KYC audit records for user ID 'user_abc_123'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123';

[User] From those, list only the ones with status 'pending'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending';

[User] Order the results by the review date in ascending order.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at ASC;

[User] Just show the latest pending audit for that user, displaying the user_id, status, and reviewed_at date.

[Assistant] SELECT user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at DESC LIMIT 1;

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Count the number of metadata entries for each asset.

[Assistant]
SELECT asset_id, COUNT(*) AS metadata_count
FROM trading_platform.metadata
GROUP BY asset_id;

[User] List all peers with their IP addresses who have not been seen in the last 7 days.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen < NOW() - INTERVAL '7 days';

[User] Show me, for each wallet address, the total sum of amounts for all unspent UTXOs, along with the user ID who owns the wallet.

[Assistant]
SELECT w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.address, w.user_id;

[User] Now, include only the wallets where the total unspent amount is greater than 50, and show the wallet_id as well.

[Assistant]
SELECT w.wallet_id, w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.wallet_id, w.address, w.user_id
HAVING COALESCE(SUM(u.amount), 0) > 50;

[User] Show me each user's username, their wallet address, and the total quantity of open orders they have placed, along with the name of the asset for each order.

[Assistant]
SELECT u.username, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, w.address, o.asset_id
ORDER BY u.username, w.address, o.asset_id;

[User] Can you also include the email address for each user and only show those with at least 2 open orders?

[Assistant]
SELECT u.username, u.email, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity, COUNT(o.order_id) AS open_order_count
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, u.email, w.address, o.asset_id
HAVING COUNT(o.order_id) >= 2
ORDER BY u.username, w.address, o.asset_id;

[User] For each asset, show the asset_id, the number of associated metadata entries, and the quantity of orders placed for that asset.

[Assistant]
SELECT a.asset_id,
       COUNT(DISTINCT m.metadata_id) AS metadata_count,
       COUNT(o.order_id) AS order_count
FROM (SELECT DISTINCT asset_id FROM trading_platform.metadata
      UNION
      SELECT DISTINCT asset_id FROM trading_platform.orders) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] The query failed because some assets do not have metadata. Please ensure all assets from the orders table are included, with metadata_count as 0 when none exist.

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] Thanks. Now, could you also show the total number of unique users who have placed orders for each asset?

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count,
       COUNT(DISTINCT o.user_id) AS unique_user_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] Only include assets with at least 3 different users placing orders, and show the results ordered by unique_user_count descending.

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count,
       COUNT(DISTINCT o.user_id) AS unique_user_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
HAVING COUNT(DISTINCT o.user_id) >= 3
ORDER BY unique_user_count DESC;

[User] I want each user with the date and action of their most recent log entry, along with how many log entries they have in the last 7 days.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COUNT(l.*)     AS log_count
FROM trading_platform.users u
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= NOW() - INTERVAL '7 days'
GROUP BY u.user_id, u.username, rl.logged_at, rl.action;

[User] Actually, I only care about log actions that contain the word 'trade'.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COUNT(l.*)     AS log_count
FROM trading_platform.users u
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= NOW() - INTERVAL '7 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username, rl.logged_at, rl.action;

[User] Include users who have no such logs, showing null for latest_action and latest_log_date, and zero for log_count.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COALESCE(cnt.log_count, 0) AS log_count
FROM trading_platform.users u
LEFT JOIN a recent AS (
  SELECT user_id, COUNT(*) AS log_count
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
  GROUP BY user_id
) cnt ON u.user_id = cnt.user_id
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1;

[User] Finally, order the results by log_count ascending.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
),
log_counts AS (
  SELECT user_id, COUNT(*) AS log_count
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
  GROUP BY user_id
)
SELECT u.user_id,
       u.username,
       rl.logged_at    AS latest_log_date,
       rl.action       AS latest_action,
       COALESCE(lc.log_count, 0) AS log_count
FROM trading_platform.users u
LEFT JOIN log_counts lc
  ON u.user_id = lc.user_id
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
ORDER BY log_count 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 trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )

[User] Show all peers, listing their ID, IP address, and port.

[Assistant] SELECT peer_id, ip_address, port FROM trading_platform.peers;

[User] Display the username and the total number of wallets for each user.

[Assistant] SELECT u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.username;

[User] Refine that to only show users with more than one wallet.

[Assistant] SELECT u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.username HAVING COUNT(w.wallet_id) > 1;

[User] List all users, showing their user ID, username, and the total number of wallets they have created. Include users who have no wallets.

[Assistant] SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.username;

[User] Now, filter the results to only include users who have created at least 2 wallets.

[Assistant] SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.username HAVING COUNT(w.wallet_id) >= 2;

[User] Also, for these users (with >= 2 wallets), show the address of their earliest created wallet.

[Assistant] WITH UserWalletCounts AS ( SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.username HAVING COUNT(w.wallet_id) >= 2 ), EarliestWallets AS ( SELECT w.user_id, w.address AS earliest_wallet_address, ROW_NUMBER() OVER(PARTITION BY w.user_id ORDER BY w.created_at ASC) as rn FROM trading_platform.wallets w ) SELECT uwc.user_id, uwc.username, uwc.wallet_count, ew.earliest_wallet_address FROM UserWalletCounts uwc JOIN EarliestWallets ew ON uwc.user_id = ew.user_id WHERE ew.rn = 1;

[User] Finally, order the results by the count of wallets in descending order and limit to the top 5 users.

[Assistant] WITH UserWalletCounts AS ( SELECT u.user_id, u.username, COUNT(w.wallet_id) AS wallet_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id GROUP BY u.user_id, u.username HAVING COUNT(w.wallet_id) >= 2 ), EarliestWallets AS ( SELECT w.user_id, w.address AS earliest_wallet_address, ROW_NUMBER() OVER(PARTITION BY w.user_id ORDER BY w.created_at ASC) as rn FROM trading_platform.wallets w ) SELECT uwc.user_id, uwc.username, uwc.wallet_count, ew.earliest_wallet_address FROM UserWalletCounts uwc JOIN EarliestWallets ew ON uwc.user_id = ew.user_id WHERE ew.rn = 1 ORDER BY uwc.wallet_count DESC LIMIT 5;

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

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT l.details) AS dapp_count FROM trading_platform.users u JOIN trading_platform.logs l ON u.user_id = l.user_id WHERE l.action = 'dapp_interaction' GROUP BY u.user_id, u.email ORDER BY dapp_count DESC LIMIT 5;

[User] Now modify the query to only include interactions that happened in the last 30 days and show the DApp names instead of just counts.

[Assistant] SELECT u.user_id, u.email, d.name AS dapp_name FROM trading_platform.users u JOIN trading_platform.logs l ON u.user_id = l.user_id JOIN trading_platform.dapps d ON l.details = d.dapp_id WHERE l.action = 'dapp_interaction' AND l.logged_at >= NOW() - INTERVAL '30 days' ORDER BY l.logged_at DESC LIMIT 5;

[User] Actually, I want to see the total number of interactions per user instead of distinct DApps, and include their wallet addresses.

[Assistant] SELECT u.user_id, u.email, w.address AS wallet_address, COUNT(l.log_id) AS interaction_count FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id JOIN trading_platform.logs l ON u.user_id = l.user_id WHERE l.action = 'dapp_interaction' AND l.logged_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email, w.address ORDER BY interaction_count DESC LIMIT 5;

[User] List each user’s user_id and username along with their total trading value (sum of quantity * price from trades) as a buyer for trades executed in June 2024. Show the top 5 users by total value descending.

[Assistant]
SELECT u.user_id, u.username, SUM(t.quantity * t.price) AS total_value
FROM trading_platform.users u
JOIN trading_platform.trades t ON u.user_id = t.buyer_id
WHERE t.traded_at >= '2024-06-01' AND t.traded_at < '2024-07-01'
GROUP BY u.user_id, u.username
ORDER BY total_value DESC
LIMIT 5;

[User] Refine the query to include only users whose most recent KYC audit status is 'approved'.

[Assistant]
SELECT u.user_id, u.username, SUM(t.quantity * t.price) AS total_value
FROM trading_platform.users u
JOIN trading_platform.trades t ON u.user_id = t.buyer_id
JOIN (
  SELECT user_id, status
  FROM trading_platform.kyc_audit
  WHERE (user_id, reviewed_at) IN (
    SELECT user_id, MAX(reviewed_at) FROM trading_platform.kyc_audit GROUP BY user_id
  )
) ka ON u.user_id = ka.user_id AND ka.status = 'approved'
WHERE t.traded_at >= '2024-06-01' AND t.traded_at < '2024-07-01'
GROUP BY u.user_id, u.username
ORDER BY total_value DESC
LIMIT 5;

[User] Get the number of log entries for each user where the action contains 'fail' in the last 30 days.

[Assistant]
SELECT l.user_id, COUNT(*) AS fail_count
FROM trading_platform.logs l
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY l.user_id;

[User] Only include users with at least 3 such log entries.

[Assistant]
SELECT l.user_id, COUNT(*) AS fail_count
FROM trading_platform.logs l
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY l.user_id
HAVING COUNT(*) >= 3;

[User] Also include the username from the users table.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS fail_count
FROM trading_platform.users u
JOIN trading_platform.logs l ON u.user_id = l.user_id
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY u.user_id, u.username
HAVING COUNT(l.log_id) >= 3;

[User] Order the results by fail_count descending and limit to the top 5 users.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS fail_count
FROM trading_platform.users u
JOIN trading_platform.logs l ON u.user_id = l.user_id
WHERE l.action ILIKE '%fail%' AND l.logged_at >= NOW() - INTERVAL '30 days'
GROUP BY u.user_id, u.username
HAVING COUNT(l.log_id) >= 3
ORDER BY fail_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 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 )

[User] Show me all replies to comments, including the reply's comment ID, the parent comment ID, and the content.

[Assistant] SELECT comment_id, parent_comment_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] I also want to see which post each reply was made on. Can you include the post ID as well?

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] Now, only show replies made after June 1, 2024.

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL AND created_at > '2024-06-01';

[User] Show me all comments that have non-empty content, including their ID, post ID, user ID, and content.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE content IS NOT NULL AND content != '';

[User] List all top-level comments, showing their ID, post ID, user ID, and content.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL;

[User] From those, show only the ones made after June 1st, 2024.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL AND created_at > '2024-06-01';

[User] Now, for these top-level comments, can you list any replies they have received, showing the reply's ID, content, and the user ID of the reply author?

[Assistant] SELECT c.comment_id AS top_level_comment_id, r.comment_id AS reply_id, r.content AS reply_content, r.user_id AS reply_user_id FROM social_media.comments c JOIN social_media.comments r ON c.comment_id = r.parent_comment_id WHERE c.parent_comment_id IS NULL AND c.created_at > '2024-06-01';

[User] Show me the number of comments each user has made on each post.

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

[User] Can you also show the creation time of the most recent comment for each post by each user?

[Assistant] SELECT post_id, user_id, COUNT(*) AS comment_count, MAX(created_at) AS latest_comment_time FROM social_media.comments GROUP BY post_id, user_id;

[User] Can you list all replies along with their parent comment content for post_id 'P100'?

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL;

[User] Actually, I only want replies made after '2024-07-01'.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01';

[User] Now include the original comment's created_at timestamp as well.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, parent.created_at AS parent_created_at, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01';

[User] Finally, order the results by reply creation time ascending.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, parent.created_at AS parent_created_at, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01' ORDER BY reply.created_at ASC;

[User] Show me the number of direct replies each top-level comment has on post 'P200'.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id;

[User] Order by reply_count descending and limit to top 5.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id ORDER BY reply_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 government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)

[User] Show the count of citizens grouped by their verification status.

[Assistant] SELECT is_verified, COUNT(*) FROM government_services.citizens GROUP BY is_verified;

[User] Now, only include citizens who registered after January 1, 2023.

[Assistant] SELECT is_verified, COUNT(*) FROM government_services.citizens WHERE registration_date >= '2023-01-01' GROUP BY is_verified;

[User] Find all pairs of citizens who share the same first name and gender but have different last names. Display the shared first name, gender, the full name of the first citizen in the pair, and the full name of the second citizen.

[Assistant] SELECT c1.first_name, c1.gender, c1.first_name || ' ' || c1.last_name AS citizen1_full_name, c2.first_name || ' ' || c2.last_name AS citizen2_full_name FROM government_services.citizens AS c1 JOIN government_services.citizens AS c2 ON c1.first_name = c2.first_name AND c1.gender = c2.gender AND c1.last_name <> c2.last_name AND c1.citizen_id < c2.citizen_id;

[User] List the first name and last name of citizens who have scheduled appointments at accessible service locations, along with the scheduled start time of the appointment and the location name.

[Assistant] SELECT c.first_name, c.last_name, a.scheduled_start_time, sl.location_name FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id JOIN government_services.service_locations AS sl ON a.location_id = sl.location_id WHERE sl.is_accessible = TRUE;

[User] Only include appointments scheduled in the year 2024.

[Assistant] SELECT c.first_name, c.last_name, a.scheduled_start_time, sl.location_name FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id JOIN government_services.service_locations AS sl ON a.location_id = sl.location_id WHERE sl.is_accessible = TRUE AND EXTRACT(YEAR FROM a.scheduled_start_time) = 2024;

[User] List pairs of verified citizens who share the same primary address city. Show the city, the full name of the first citizen, and the full name of the second citizen.

[Assistant] SELECT SPLIT_PART(c1.primary_address, ', ', 2) AS city, c1.first_name || ' ' || c1.last_name AS citizen1_full_name, c2.first_name || ' ' || c2.last_name AS citizen2_full_name FROM government_services.citizens AS c1 JOIN government_services.citizens AS c2 ON SPLIT_PART(c1.primary_address, ', ', 2) = SPLIT_PART(c2.primary_address, ', ', 2) AND c1.citizen_id < c2.citizen_id WHERE c1.is_verified = TRUE AND c2.is_verified = TRUE;

[User] Provide a count of citizens registered per calendar year.

[Assistant] SELECT CAST(EXTRACT(YEAR FROM registration_date) AS INTEGER) AS registration_year, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY 1 ORDER BY 1;

[User] Count the number of active services provided by each agency. Show the agency name and the count.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name;

[User] Only include agencies with more than 5 active services.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name HAVING COUNT(s.service_id) > 5;

[User] Also show the total standard fee for the active services provided by these agencies.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count, SUM(s.standard_fee) AS total_standard_fee FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name HAVING COUNT(s.service_id) > 5;

[User] Order the results by the total standard fee in descending order.

[Assistant] SELECT a.agency_name, COUNT(s.service_id) AS active_service_count, SUM(s.standard_fee) AS total_standard_fee FROM government_services.agencies AS a JOIN government_services.services AS s ON a.agency_id = s.agency_id WHERE s.is_active = TRUE GROUP BY a.agency_name HAVING COUNT(s.service_id) > 5 ORDER BY total_standard_fee DESC;