System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] List all insurance plans that will expire within the next 30 days, showing the patient IDs and subscriber names.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] Show me all patients who have non-primary insurance plans with expiration dates within the next 60 days, along with their policy numbers and subscriber names.

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

[User] Count how many non-primary insurance policies have a group number specified.

[Assistant] SELECT COUNT(*) FROM healthcare.patient_insurance WHERE is_primary = FALSE AND group_number IS NOT NULL;

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

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

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

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

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

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

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

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

[User] Only include policies that have not expired.

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

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

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

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

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

[User] List the patient ID, policy number, and effective date for all policies that are marked as primary.

[Assistant] SELECT patient_id, policy_number, effective_date FROM healthcare.patient_insurance WHERE is_primary = TRUE;

[User] Now, only include those policies that have an expiration date specified (expiration_date is NOT NULL).

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

[User] Further filter these to policies where the effective date is before '2023-01-01'.

[Assistant] SELECT patient_id, policy_number, effective_date FROM healthcare.patient_insurance WHERE is_primary = TRUE AND expiration_date IS NOT NULL AND effective_date < '2023-01-01';

[User] Finally, show the patient_id, policy_number, and expiration_date for these policies and order by effective date ascending.

[Assistant] SELECT patient_id, policy_number, expiration_date FROM healthcare.patient_insurance WHERE is_primary = TRUE AND expiration_date IS NOT NULL AND effective_date < '2023-01-01' ORDER BY effective_date ASC;

[User] Give me all diagnosis_id and diagnosis_codes for chronic diagnoses made using the ICD-9 code type.

[Assistant]
SELECT diagnosis_id, diagnosis_code
FROM healthcare.diagnoses
WHERE is_chronic = TRUE AND code_type = 'ICD-9';


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] 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 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] 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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )

[User] Provide a count of contracts for each unique combination of network ID and status.

[Assistant] SELECT network_id, status, COUNT(*) FROM web3.contracts GROUP BY network_id, status;

[User] Now, only show the network IDs from the previous result that have contracts in more than one distinct status.

[Assistant] SELECT network_id FROM web3.contracts GROUP BY network_id HAVING COUNT(DISTINCT status) > 1;

[User] List all contracts with status 'active' and include their deployment timestamp and network ID.

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active';

[User] Actually, I need to see only contracts deployed in the last 30 days.

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active' AND deployed_at >= NOW() - INTERVAL '30 days';

[User] There's a typo in your SQL, it should be 'deployed_at' not 'deployed_at'. Also, sort the results by deployed_at in descending order.

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active' AND deployed_at >= NOW() - INTERVAL '30 days' ORDER BY deployed_at DESC;

[User] Now filter to only show contracts on the 'polygon' network.

[Assistant] SELECT address, deployed_at, network_id FROM web3.contracts WHERE status = 'active' AND deployed_at >= NOW() - INTERVAL '30 days' AND network_id = 'polygon' ORDER BY deployed_at DESC;

[User] List the contract ID, address, and deployer address for all contracts deployed on the 'mainnet' network.

[Assistant] SELECT contract_id, address, deployer_address FROM web3.contracts WHERE network_id = 'mainnet';

[User] Show all contracts that share the same deployment date, along with their contract IDs and the corresponding deployment date.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date AND a.contract_id < b.contract_id;

[User] Actually, I only want to see such pairs where the contracts were deployed by different deployer addresses.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date
  AND a.contract_id < b.contract_id
  AND a.deployer_address <> b.deployer_address;

[User] Count the number of contracts for each network_id.

[Assistant] SELECT network_id, COUNT(*) FROM web3.contracts GROUP BY network_id;

[User] Now, only show networks with more than 100 contracts.

[Assistant] SELECT network_id, COUNT(*) FROM web3.contracts GROUP BY network_id HAVING COUNT(*) > 100;

[User] Find the deployer address that has deployed the highest number of contracts and report the address and the total count of contracts for that deployer.

[Assistant] SELECT deployer_address, COUNT(*) AS contract_count FROM web3.contracts GROUP BY deployer_address ORDER BY contract_count DESC LIMIT 1;

[User] Find all pairs of contracts that were deployed on the same network but by different deployer addresses. List the network ID, the addresses of both contracts, and the addresses of their respective deployers.

[Assistant] SELECT c1.network_id, c1.address AS contract1_address, c2.address AS contract2_address, c1.deployer_address AS contract1_deployer, c2.deployer_address AS contract2_deployer FROM web3.contracts c1 JOIN web3.contracts c2 ON c1.network_id = c2.network_id AND c1.deployer_address != c2.deployer_address WHERE c1.contract_id < c2.contract_id;

[User] List each contract along with the deployer address, and status for contracts deployed on network_id 'mainnet'.

[Assistant] SELECT contract_id, address, deployer_address, status FROM web3.contracts WHERE network_id = 'mainnet';

[User] For each network, list the deployer address and the number of contracts they have deployed, ordered from most to least.

[Assistant] SELECT network_id, deployer_address, COUNT(*) AS deployed_contracts FROM web3.contracts GROUP BY network_id, deployer_address ORDER BY network_id, deployed_contracts DESC;

[User] Show the total number of contracts grouped by their status.

[Assistant] SELECT status, COUNT(*) AS contract_count FROM web3.contracts GROUP BY status;

[User] Can you also filter to only include statuses with more than 10 contracts?

[Assistant] SELECT status, COUNT(*) AS contract_count FROM web3.contracts GROUP BY status HAVING COUNT(*) > 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Show me all failed transactions (status = 'FAILED') that involved US dollars, along with the account_id, amount, and transaction_date.

[Assistant]
SELECT transaction_id, account_id, amount, transaction_date
FROM financial_services.transactions
WHERE status = 'FAILED' AND currency = 'USD';

[User] Please group the results by account_id and show the total number of failed transactions and total failed amount per account.

[Assistant]
SELECT account_id, COUNT(*) AS failed_transaction_count, SUM(amount) AS total_failed_amount
FROM financial_services.transactions
WHERE status = 'FAILED' AND currency = 'USD'
GROUP BY account_id;

[User] Now, only include accounts with more than 2 failed transactions.

[Assistant]
SELECT account_id, COUNT(*) AS failed_transaction_count, SUM(amount) AS total_failed_amount
FROM financial_services.transactions
WHERE status = 'FAILED' AND currency = 'USD'
GROUP BY account_id
HAVING COUNT(*) > 2;

[User] I want to see for each security the ticker_symbol, security_name, and the highest single-day close_price from the market_data.

[Assistant]
SELECT s.ticker_symbol, s.security_name, MAX(m.close_price) AS highest_close_price
FROM financial_services.securities s
JOIN financial_services.market_data m ON s.security_id = m.security_id
GROUP BY s.ticker_symbol, s.security_name;

[User] Also include the data_timestamp corresponding to the highest close_price for each security.

[Assistant]
SELECT s.ticker_symbol, s.security_name, m.close_price AS highest_close_price, m.data_timestamp
FROM financial_services.securities s
JOIN financial_services.market_data m
  ON s.security_id = m.security_id
WHERE (s.security_id, m.close_price) IN (
  SELECT security_id, MAX(close_price)
  FROM financial_services.market_data
  GROUP BY security_id
);

[User] Show only the results where highest_close_price is greater than 100.

[Assistant]
SELECT s.ticker_symbol, s.security_name, m.close_price AS highest_close_price, m.data_timestamp
FROM financial_services.securities s
JOIN financial_services.market_data m
  ON s.security_id = m.security_id
WHERE (s.security_id, m.close_price) IN (
  SELECT security_id, MAX(close_price)
  FROM financial_services.market_data
  GROUP BY security_id
)
AND m.close_price > 100;

[User] For each loan, show the loan_id, the account_id, the principal_amount, and the ticker_symbol and security_name of any associated collateral, if the collateral_description matches a security's ticker_symbol.

[Assistant]
SELECT l.loan_id, l.account_id, l.principal_amount, s.ticker_symbol, s.security_name
FROM financial_services.loans l
LEFT JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol;

[User] Actually, please only include loans where a matching collateral security exists.

[Assistant]
SELECT l.loan_id, l.account_id, l.principal_amount, s.ticker_symbol, s.security_name
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol;

[User] Add the security's sector and filter to only include loans with principal_amount over 20000.

[Assistant]
SELECT l.loan_id, l.account_id, l.principal_amount, s.ticker_symbol, s.security_name, s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol
WHERE l.principal_amount > 20000;

[User] Sort the result by principal_amount descending.

[Assistant]
SELECT l.loan_id, l.account_id, l.principal_amount, s.ticker_symbol, s.security_name, s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol
WHERE l.principal_amount > 20000
ORDER BY l.principal_amount DESC;

[User] Show the total number of transactions for each currency.

[Assistant] SELECT currency, COUNT(*) FROM financial_services.transactions GROUP BY currency

[User] Can you also include the total amount for each currency?

[Assistant] SELECT currency, COUNT(*), SUM(amount) FROM financial_services.transactions GROUP BY currency

[User] For each sector, could you show the sum of volume and the average close price from market_data, including the sector name?

[Assistant]
SELECT s.sector, SUM(md.volume) AS total_volume, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.sector;

[User] Could you also include the maximum high price for each sector in the result?

[Assistant]
SELECT s.sector, SUM(md.volume) AS total_volume, AVG(md.close_price) AS avg_close_price, MAX(md.high_price) AS max_high_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.sector;

[User] Now, only include sectors where the total_volume is at least 1000000, and sort by max_high_price descending.

[Assistant]
SELECT s.sector, SUM(md.volume) AS total_volume, AVG(md.close_price) AS avg_close_price, MAX(md.high_price) AS max_high_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.sector
HAVING SUM(md.volume) >= 1000000
ORDER BY max_high_price DESC;

[User] I want to see, for each security, the total number of market data points and the average adjusted_close_price, including ticker_symbol and security_name.

[Assistant]
SELECT s.ticker_symbol, s.security_name, COUNT(md.data_point_id) AS data_point_count, AVG(md.adjusted_close_price) AS avg_adjusted_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.ticker_symbol, s.security_name;

[User] Can you limit to only those securities with at least 30 market data points?

[Assistant]
SELECT s.ticker_symbol, s.security_name, COUNT(md.data_point_id) AS data_point_count, AVG(md.adjusted_close_price) AS avg_adjusted_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.ticker_symbol, s.security_name
HAVING COUNT(md.data_point_id) >= 30;

[User] Please also sort the result by avg_adjusted_close_price descending and show only the top 10.

[Assistant]
SELECT s.ticker_symbol, s.security_name, COUNT(md.data_point_id) AS data_point_count, AVG(md.adjusted_close_price) AS avg_adjusted_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.ticker_symbol, s.security_name
HAVING COUNT(md.data_point_id) >= 30
ORDER BY avg_adjusted_close_price DESC
LIMIT 10;

[User] Could you show me all securities traded on the LSE exchange using GBP currency?

[Assistant]
SELECT security_id, ticker_symbol, security_name, issuer_name
FROM financial_services.securities
WHERE exchange = 'LSE' AND currency = 'GBP';

[User] Can you add each security's sector and sort the result by issuer_name ascending?

[Assistant]
SELECT security_id, ticker_symbol, security_name, issuer_name, sector
FROM financial_services.securities
WHERE exchange = 'LSE' AND currency = 'GBP'
ORDER BY issuer_name ASC;

[User] Only include securities whose security_type is 'Equity'.

[Assistant]
SELECT security_id, ticker_symbol, security_name, issuer_name, sector
FROM financial_services.securities
WHERE exchange = 'LSE' AND currency = 'GBP' AND security_type = 'Equity'
ORDER BY issuer_name ASC;

[User] I'd like a report showing for each sector the average close_price and maximum volume from market_data for the previous quarter.

[Assistant]
SELECT s.sector, AVG(md.close_price) AS avg_close_price, MAX(md.volume) AS max_volume
FROM financial_services.market_data md
JOIN financial_services.securities s ON md.security_id = s.security_id
WHERE md.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND md.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY s.sector;

[User] Actually, only include records where source = 'Reuters'.

[Assistant]
SELECT s.sector, AVG(md.close_price) AS avg_close_price, MAX(md.volume) AS max_volume
FROM financial_services.market_data md
JOIN financial_services.securities s ON md.security_id = s.security_id
WHERE md.source = 'Reuters'
  AND md.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND md.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY s.sector;

[User] The SQL runs but it complains about ambiguous column references. Could you alias the tables properly and ensure the join is clear?

[Assistant]
SELECT sec.sector, AVG(mdk.close_price) AS avg_close_price, MAX(mdk.volume) AS max_volume
FROM financial_services.market_data AS mdk
JOIN financial_services.securities AS sec
  ON mdk.security_id = sec.security_id
WHERE mdk.source = 'Reuters'
  AND mdk.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND mdk.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY sec.sector;

[User] Additionally, please only consider data points where volume is greater than 1000000.

[Assistant]
SELECT sec.sector, AVG(mdk.close_price) AS avg_close_price, MAX(mdk.volume) AS max_volume
FROM financial_services.market_data AS mdk
JOIN financial_services.securities AS sec
  ON mdk.security_id = sec.security_id
WHERE mdk.source = 'Reuters'
  AND mdk.volume > 1000000
  AND mdk.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND mdk.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY sec.sector;

[User] How many market data points are there per day?

[Assistant]
SELECT date(md.data_timestamp) AS day, COUNT(*) AS data_point_count
FROM financial_services.market_data md
GROUP BY date(md.data_timestamp)
ORDER BY day;

[User] Now change it to monthly counts.

[Assistant]
SELECT date_trunc('month', md.data_timestamp) AS month, COUNT(*) AS data_point_count
FROM financial_services.market_data md
GROUP BY date_trunc('month', md.data_timestamp)
ORDER BY month;

[User] Finally, exclude months where the count is less than 100.

[Assistant]
SELECT date_trunc('month', md.data_timestamp) AS month, COUNT(*) AS data_point_count
FROM financial_services.market_data md
GROUP BY date_trunc('month', md.data_timestamp)
HAVING COUNT(*) >= 100
ORDER BY month;

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

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

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

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

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

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

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

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


System:
You are an 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 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 )

[User] List the top 10 narratives based on their market cap. Display the narrative name, market_cap, and token_num.

[Assistant] SELECT narrative, market_cap, token_num FROM narrative_info ORDER BY market_cap DESC LIMIT 10

[User] List all narratives with a trend rank better than 50, showing the narrative name and their listed 'Top 3 Coins'.

[Assistant] SELECT narrative, top_3_coins FROM narrative_info WHERE trend_rank < 50

[User] Could you also include the 24-hour trading volume for these narratives and only show those where the volume is greater than 10,000,000 USD?

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000

[User] Please order the results by 24-hour trading volume in descending order.

[Assistant] SELECT narrative, top_3_coins, volume_24h FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h DESC

[User] Finally, limit the output to the top 10 and add the total number of tokens for each narrative.

[Assistant] SELECT narrative, top_3_coins, volume_24h, token_num FROM narrative_info WHERE trend_rank < 50 AND volume_24h > 10000000 ORDER BY volume_24h DESC LIMIT 10

[User] Show narratives with a 24-hour trading volume greater than $10,000,000 and a positive 24-hour price change percentage. List the narrative name, volume_24h, and price_change_percentage_24h.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h FROM narrative_info WHERE volume_24h > 10000000 AND price_change_percentage_24h > 0

[User] Refine the results to only include narratives with a trend rank of 20 or better (lower number is better), and order the results by volume_24h in descending order. Also, include the trend_rank in the output.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h, trend_rank FROM narrative_info WHERE volume_24h > 10000000 AND price_change_percentage_24h > 0 AND trend_rank <= 20 ORDER BY volume_24h DESC

[User] The list is too short. Can you adjust the volume filter to be greater than $5,000,000 instead of $10,000,000?

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h, trend_rank FROM narrative_info WHERE volume_24h > 5000000 AND price_change_percentage_24h > 0 AND trend_rank <= 20 ORDER BY volume_24h DESC

[User] Okay, and also add the number of tokens (token_num) for each narrative in the results.

[Assistant] SELECT narrative, volume_24h, price_change_percentage_24h, trend_rank, token_num FROM narrative_info WHERE volume_24h > 5000000 AND price_change_percentage_24h > 0 AND trend_rank <= 20 ORDER BY volume_24h DESC

[User] List all pairs of narratives where the first narrative has a higher market_cap than the second. Display narrative1, narrative2, cap1, cap2.

[Assistant] SELECT n1.narrative AS narrative1, n2.narrative AS narrative2, n1.market_cap AS cap1, n2.market_cap AS cap2 FROM narrative_info n1 JOIN narrative_info n2 ON n1.market_cap > n2.market_cap;

[User] Filter the result to only include pairs where the difference in market_cap is over 100000000 and order by the difference descending, limit to 10.

[Assistant] SELECT n1.narrative AS narrative1, n2.narrative AS narrative2, n1.market_cap AS cap1, n2.market_cap AS cap2, (n1.market_cap - n2.market_cap) AS diff FROM narrative_info n1 JOIN narrative_info n2 ON n1.market_cap > n2.market_cap WHERE (n1.market_cap - n2.market_cap) > 100000000 ORDER BY diff DESC LIMIT 10;

[User] Show the top 5 narratives by 24h volume, displaying narrative and volume_24h.

[Assistant] SELECT narrative, volume_24h FROM narrative_info ORDER BY volume_24h DESC LIMIT 5;

[User] Find narrative pairs where the sum of their price_change_percentage_1h is greater than 5. Show narrative1, change1, narrative2, change2, and the sum as total_change.

[Assistant] SELECT n1.narrative AS narrative1, n1.price_change_percentage_1h AS change1, n2.narrative AS narrative2, n2.price_change_percentage_1h AS change2, (n1.price_change_percentage_1h + n2.price_change_percentage_1h) AS total_change FROM narrative_info n1 JOIN narrative_info n2 ON n1.narrative <> n2.narrative WHERE (n1.price_change_percentage_1h + n2.price_change_percentage_1h) > 5;

[User] Now only include pairs where both have token_num greater than 10 and order by total_change descending.

[Assistant] SELECT n1.narrative AS narrative1, n1.price_change_percentage_1h AS change1, n2.narrative AS narrative2, n2.price_change_percentage_1h AS change2, (n1.price_change_percentage_1h + n2.price_change_percentage_1h) AS total_change FROM narrative_info n1 JOIN narrative_info n2 ON n1.narrative <> n2.narrative WHERE (n1.price_change_percentage_1h + n2.price_change_percentage_1h) > 5 AND n1.token_num > 10 AND n2.token_num > 10 ORDER BY total_change DESC;

[User] List all narratives that have a market cap between 500,000,000 and 5,000,000,000 USD and a positive price change over the last 7 days. Show the narrative name, market cap, and price change percentage for the last 7 days.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0

[User] Thanks, can you also include the number of tokens for each of these narratives and filter to only include those with a trend rank better than 25?

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, token_num FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0 AND trend_rank < 25

[User] Okay, please order the results by market cap in descending order.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, token_num FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0 AND trend_rank < 25 ORDER BY market_cap DESC

[User] Finally, limit the results to the top 10.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, token_num FROM narrative_info WHERE market_cap BETWEEN 500000000 AND 5000000000 AND price_change_percentage_7d > 0 AND trend_rank < 25 ORDER BY market_cap DESC LIMIT 10

[User] Find narratives with a market cap greater than $500,000,000 and a 7-day price change percentage above 5%. Show the narrative, market_cap, and price_change_percentage_7d.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d FROM narrative_info WHERE market_cap > 500000000 AND price_change_percentage_7d > 5

[User] Can you also include the 1-hour price change percentage and the trend_rank for these narratives?

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, price_change_percentage_1h, trend_rank FROM narrative_info WHERE market_cap > 500000000 AND price_change_percentage_7d > 5

[User] Please add the 'top_3_coins' column to the result set.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, price_change_percentage_1h, trend_rank, top_3_coins FROM narrative_info WHERE market_cap > 500000000 AND price_change_percentage_7d > 5

[User] Finally, order the results by market cap descending.

[Assistant] SELECT narrative, market_cap, price_change_percentage_7d, price_change_percentage_1h, trend_rank, top_3_coins FROM narrative_info WHERE market_cap > 500000000 AND price_change_percentage_7d > 5 ORDER BY market_cap DESC

[User] Show the top 5 narratives ranked by trend_rank (lowest is better). Include the narrative, trend rank, and number of tokens.

[Assistant] SELECT narrative, trend_rank, token_num FROM narrative_info ORDER BY trend_rank ASC LIMIT 5;

[User] Can you also add their 24h and 7d price change percentages in the output?

[Assistant] SELECT narrative, trend_rank, token_num, price_change_percentage_24h, price_change_percentage_7d FROM narrative_info ORDER BY trend_rank ASC LIMIT 5;

[User] Now, I want to see only those narratives where the total 24h trading volume is above $10 million.

[Assistant] SELECT narrative, trend_rank, token_num, price_change_percentage_24h, price_change_percentage_7d, volume_24h FROM narrative_info WHERE volume_24h > 10000000 ORDER BY trend_rank ASC LIMIT 5;

[User] Can you show trend_rank as the last column?

[Assistant] SELECT narrative, token_num, price_change_percentage_24h, price_change_percentage_7d, volume_24h, trend_rank FROM narrative_info WHERE volume_24h > 10000000 ORDER BY trend_rank ASC LIMIT 5;

[User] List narratives with a market cap over $1,000,000,000, ordered by market cap descending.

[Assistant] SELECT narrative, market_cap FROM narrative_info WHERE market_cap > 1000000000 ORDER BY market_cap DESC;

[User] Can you also include the 24-hour trading volume and the number of tokens for each of these narratives?

[Assistant] SELECT narrative, market_cap, volume_24h, token_num FROM narrative_info WHERE market_cap > 1000000000 ORDER BY market_cap DESC;

[User] Okay, now filter those results further to only include narratives where the 24-hour trading volume is also over $50,000,000.

[Assistant] SELECT narrative, market_cap, volume_24h, token_num FROM narrative_info WHERE market_cap > 1000000000 AND volume_24h > 50000000 ORDER BY market_cap DESC;

[User] Could you order the final results by 24-hour trading volume descending instead of market cap?

[Assistant] SELECT narrative, market_cap, volume_24h, token_num FROM narrative_info WHERE market_cap > 1000000000 AND volume_24h > 50000000 ORDER BY volume_24h DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )

[User] Get the number of service locations per state.

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state;

[User] Now only include states that have more than 5 service locations.

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state
HAVING location_count > 5;

[User] I got an error: column "location_count" does not exist in HAVING. Correct the query.

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state
HAVING COUNT(*) > 5;

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

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state
HAVING COUNT(*) > 5
ORDER BY COUNT(*) DESC;

[User] For each service location, find the nearest accessible service location. Show the location_id, location_name, nearest_location_id, and the distance.

[Assistant]
SELECT l.location_id,
       l.location_name,
       nearest.location_id AS nearest_location_id,
       SQRT(POWER(l.latitude - nearest.latitude, 2) + POWER(l.longitude - nearest.longitude, 2)) AS distance
FROM service_locations l
JOIN LATERAL (
  SELECT sl.location_id, sl.latitude, sl.longitude
  FROM service_locations sl
  WHERE sl.location_id <> l.location_id
    AND sl.is_accessible = TRUE
  ORDER BY POWER(l.latitude - sl.latitude, 2) + POWER(l.longitude - sl.longitude, 2)
  LIMIT 1
) AS nearest ON TRUE;

[User] For each service location, find its nearest accessible location by geographic distance.

[Assistant]
SELECT sl.location_id,
       sl.location_name,
       nearest.location_id   AS nearest_location_id,
       nearest.location_name AS nearest_location_name
FROM government_services.service_locations sl
JOIN LATERAL (
  SELECT sl2.location_id,
         sl2.location_name
  FROM government_services.service_locations sl2
  WHERE sl2.is_accessible = TRUE
    AND sl2.location_id <> sl.location_id
  ORDER BY ((sl.latitude - sl2.latitude)^2 + (sl.longitude - sl2.longitude)^2) ASC
  LIMIT 1
) AS nearest ON TRUE;

[User] Could you retrieve pairs of accessible service locations in the same city but with different postal codes?

[Assistant]
SELECT sl1.location_id AS location1_id,
       sl2.location_id AS location2_id,
       sl1.city
FROM government_services.service_locations sl1
JOIN government_services.service_locations sl2
  ON sl1.city = sl2.city
 AND sl1.location_id < sl2.location_id
WHERE sl1.is_accessible = TRUE
  AND sl2.is_accessible = TRUE;

[User] Now restrict these pairs to those in the state of 'California'.

[Assistant]
SELECT sl1.location_id AS location1_id,
       sl2.location_id AS location2_id,
       sl1.city
FROM government_services.service_locations sl1
JOIN government_services.service_locations sl2
  ON sl1.city = sl2.city
 AND sl1.location_id < sl2.location_id
WHERE sl1.is_accessible = TRUE
  AND sl2.is_accessible = TRUE
  AND sl1.state = 'California'
  AND sl2.state = 'California';

[User] List the location name and contact phone number for all service locations situated in the city of 'New York'.

[Assistant] SELECT location_name, contact_phone FROM government_services.service_locations WHERE city = 'New York';

[User] List all service locations with their IDs, names, latitude, and longitude.

[Assistant]
SELECT location_id,
       location_name,
       latitude,
       longitude
FROM government_services.service_locations;

[User] Also only include locations whose postal code starts with '90'.

[Assistant]
SELECT location_id,
       location_name,
       latitude,
       longitude
FROM government_services.service_locations
WHERE postal_code LIKE '90%';

[User] Exclude entries without operating hours specified.

[Assistant]
SELECT location_id,
       location_name,
       latitude,
       longitude
FROM government_services.service_locations
WHERE postal_code LIKE '90%'
  AND operating_hours IS NOT NULL;

[User] Order the output by city and limit to 10 results.

[Assistant]
SELECT location_id,
       location_name,
       latitude,
       longitude
FROM government_services.service_locations
WHERE postal_code LIKE '90%'
  AND operating_hours IS NOT NULL
ORDER BY city ASC
LIMIT 10;

[User] How many service locations are accessible in each state? Provide the state and the count of accessible locations.

[Assistant] SELECT state, COUNT(*) FROM government_services.service_locations WHERE is_accessible = TRUE GROUP BY state;

[User] Find the service locations that are not accessible and located in the state of 'California'. List their name, address, and city.

[Assistant] SELECT location_name ,  address ,  city FROM government_services.service_locations WHERE is_accessible = false AND state = 'California'

[User] List the latitude and longitude coordinates for all service locations located in a city named 'Seattle'.

[Assistant] SELECT latitude ,  longitude FROM government_services.service_locations WHERE city = 'Seattle'

[User] How many service locations are there for each agency? List the agency ID and the count of locations.

[Assistant] SELECT agency_id ,  count(*) FROM government_services.service_locations GROUP BY 1


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_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.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.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_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] 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] Show all peers, listing their ID, IP address, and port.

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

[User] Show me the top 5 users who have created the most wallets, along with their email addresses and the total number of wallets they created.

[Assistant] SELECT u.user_id, u.email, 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.email ORDER BY wallet_count DESC LIMIT 5;

[User] Now modify the query to only include wallets created in the last 6 months and show the creation date of their most recent wallet.

[Assistant] SELECT u.user_id, u.email, COUNT(w.wallet_id) AS wallet_count, MAX(w.created_at) AS latest_wallet_created_at FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[User] Actually, I want to see the average time between wallet creations for these users as well.

[Assistant] SELECT u.user_id, u.email, COUNT(w.wallet_id) AS wallet_count, MAX(w.created_at) AS latest_wallet_created_at, (EXTRACT(EPOCH FROM (MAX(w.created_at) - MIN(w.created_at)))/COUNT(w.wallet_id)/86400 AS avg_days_between_creations FROM trading_platform.users u JOIN trading_platform.wallets w ON u.user_id = w.user_id WHERE w.created_at >= NOW() - INTERVAL '6 months' GROUP BY u.user_id, u.email ORDER BY wallet_count DESC LIMIT 5;

[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] For each user, show their username and the total number of 'sell' orders they've placed, including users who haven't placed any.

[Assistant]
SELECT u.username,
       COUNT(o.order_id) FILTER (WHERE o.order_type = 'sell') AS sell_order_count
FROM trading_platform.users u
LEFT JOIN trading_platform.orders o
  ON u.user_id = o.user_id
GROUP BY u.username;

[User] Only include users who have placed at least 2 sell orders, and also display their email address.

[Assistant]
SELECT u.username,
       u.email,
       COUNT(o.order_id) FILTER (WHERE o.order_type = 'sell') AS sell_order_count
FROM trading_platform.users u
LEFT JOIN trading_platform.orders o
  ON u.user_id = o.user_id
GROUP BY u.username, u.email
HAVING COUNT(o.order_id) FILTER (WHERE o.order_type = 'sell') >= 2;

[User] Now, consider only sell orders created after '2024-06-01', and for each user include the total quantity of such orders.

[Assistant]
SELECT u.username,
       u.email,
       COUNT(o.order_id) AS sell_order_count,
       SUM(o.quantity) AS total_quantity
FROM trading_platform.users u
LEFT JOIN trading_platform.orders o
  ON u.user_id = o.user_id
  AND o.order_type = 'sell'
  AND o.created_at > '2024-06-01'
GROUP BY u.username, u.email;

[User] Finally, order the results by total_quantity descending and limit it to the top 10 users.

[Assistant]
SELECT u.username,
       u.email,
       COUNT(o.order_id) AS sell_order_count,
       SUM(o.quantity) AS total_quantity
FROM trading_platform.users u
LEFT JOIN trading_platform.orders o
  ON u.user_id = o.user_id
  AND o.order_type = 'sell'
  AND o.created_at > '2024-06-01'
GROUP BY u.username, u.email
ORDER BY total_quantity DESC
LIMIT 10;

[User] List the username and the total number of notifications each user has received, and also count how many of those are still unread.

[Assistant]
SELECT u.username,
       COUNT(n.notification_id) AS total_notifications,
       SUM(CASE WHEN n.read_at IS NULL THEN 1 ELSE 0 END) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.notifications n
  ON u.user_id = n.user_id
GROUP BY u.username;

[User] Actually, limit it to notifications sent in the last 7 days and only show users with at least 1 unread notification.

[Assistant]
SELECT u.username,
       COUNT(n.notification_id) AS total_notifications,
       SUM(CASE WHEN n.read_at IS NULL THEN 1 ELSE 0 END) AS unread_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.notifications n
  ON u.user_id = n.user_id
  AND n.sent_at >= NOW() - INTERVAL '7 days'
GROUP BY u.username
HAVING SUM(CASE WHEN n.read_at IS NULL THEN 1 ELSE 0 END) > 0;

[User] How many DApps have names that start with the letter 'A'?

[Assistant]
SELECT COUNT(*) AS dapp_count
FROM trading_platform.dapps
WHERE name LIKE 'A%';

[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 healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Can you provide a list of all medical records created by doctors for patients who are associated with 'PPO' type insurance plans? I need the record ID, patient ID, doctor ID, record date, and insurance plan name.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.doctor_id, mr.record_date, ip.plan_name
FROM healthcare.medical_records mr
JOIN healthcare.insurance_plans ip ON mr.patient_id IS NOT NULL -- placeholder JOIN, fix below if you have a patient-insurance mapping table
WHERE ip.plan_type = 'PPO';

[User] The SQL seems off because there's no direct mapping between patients and insurance_plans in the schema. Can you adjust the query so that it only lists medical records with the plan details if the doctor creating the record has a contact phone number that matches the plan's contact_phone? Still need the same output columns.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.doctor_id, mr.record_date, ip.plan_name
FROM healthcare.medical_records mr
JOIN healthcare.insurance_plans ip ON mr.doctor_id IS NOT NULL -- placeholder JOIN, fix below if you have a doctors table with contact_phone
WHERE ip.plan_type = 'PPO' AND ip.contact_phone IS NOT NULL;

[User] Actually, please sort the results by record_date in descending order and return only the latest 20 records.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.doctor_id, mr.record_date, ip.plan_name
FROM healthcare.medical_records mr
JOIN healthcare.insurance_plans ip ON mr.doctor_id IS NOT NULL -- placeholder JOIN, fix below if you have a doctors table with contact_phone
WHERE ip.plan_type = 'PPO' AND ip.contact_phone IS NOT NULL
ORDER BY mr.record_date DESC
LIMIT 20;

[User] List each patient's first and last medical record entries, showing patient_id, earliest_record_id, earliest_record_date, latest_record_id, and latest_record_date.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date
        FROM healthcare.medical_records
        GROUP BY patient_id
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] Filter to include only patients who have at least three medical record entries.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date,
            COUNT(*) AS total_records
        FROM healthcare.medical_records
        GROUP BY patient_id
        HAVING COUNT(*) >= 3
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] Also include for each patient the count of distinct days on which records were made, labeled active_days.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date,
    fl.active_days
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date,
            COUNT(*) AS total_records,
            COUNT(DISTINCT date_trunc('day', record_date)) AS active_days
        FROM healthcare.medical_records
        GROUP BY patient_id
        HAVING COUNT(*) >= 3
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] Can you show me the details of all medical records for patients that had their vitals recorded with a temperature above 38 degrees Celsius, along with any medication descriptions that mention 'antipyretic'?

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38 AND m.description ILIKE '%antipyretic%';

[User] Refine the query to only include records created after January 1st, 2024.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38
  AND m.description ILIKE '%antipyretic%'
  AND mr.record_date >= '2024-01-01';

[User] Actually, could you also include the doctor's ID who created each medical record?

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.doctor_id, mr.record_date, mr.chief_complaint, mr.treatment_plan, m.medication_name, m.description
FROM healthcare.medical_records mr
JOIN healthcare.medications m ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE (mr.vitals->>'Temp')::numeric > 38
  AND m.description ILIKE '%antipyretic%'
  AND mr.record_date >= '2024-01-01';

[User] What is the total count of medical records created in the year 2023 where the assessment field is not empty?

[Assistant] SELECT COUNT(*) FROM healthcare.medical_records mr WHERE (mr.assessment IS NOT NULL AND mr.assessment != '') AND EXTRACT(YEAR FROM mr.record_date) = 2023;

[User] Now, break down this count by the doctor who created the record. Show the doctor_id and the count.

[Assistant] SELECT mr.doctor_id, COUNT(*) FROM healthcare.medical_records mr WHERE (mr.assessment IS NOT NULL AND mr.assessment != '') AND EXTRACT(YEAR FROM mr.record_date) = 2023 GROUP BY mr.doctor_id;

[User] List the record ID, record date, patient ID, and chief complaint for medical records belonging to patients whose last name is 'Smith'. Also include the patient's last name in the results.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith';

[User] Refine this list to only show records where the record date is in 2024 and the chief complaint is not null. Sort by record_date in ascending order.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith' AND EXTRACT(YEAR FROM mr.record_date) = 2024 AND (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') ORDER BY mr.record_date ASC;

[User] Show the record_id, patient_id, record_date and systolic blood pressure from vitals for all medical records where the systolic blood pressure is above 140.

[Assistant]
SELECT record_id, patient_id, record_date, (vitals->>'systolic')::INT AS systolic
FROM healthcare.medical_records
WHERE (vitals->>'systolic')::INT > 140;

[User] Only include those records for patients who currently have a primary insurance that is active.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, (mr.vitals->>'systolic')::INT AS systolic
FROM healthcare.medical_records mr
JOIN healthcare.patient_insurance pi ON mr.patient_id = pi.patient_id
WHERE (mr.vitals->>'systolic')::INT > 140
  AND pi.is_primary = TRUE
  AND pi.effective_date <= CURRENT_DATE
  AND (pi.expiration_date IS NULL OR pi.expiration_date > CURRENT_DATE);

[User] List all pairs of record_id for the same patient that were created on the same day. Show the two record_ids, patient_id, and the date.

[Assistant]
SELECT
    mr1.patient_id,
    date_trunc('day', mr1.record_date) AS record_day,
    mr1.record_id AS record_id_1,
    mr2.record_id AS record_id_2
FROM healthcare.medical_records mr1
JOIN healthcare.medical_records mr2
  ON mr1.patient_id = mr2.patient_id
 AND date_trunc('day', mr1.record_date) = date_trunc('day', mr2.record_date)
 AND mr1.record_id < mr2.record_id;

[User] Only include pairs where both records have a heart rate over 100 in their vitals.

[Assistant]
SELECT
    mr1.patient_id,
    date_trunc('day', mr1.record_date) AS record_day,
    mr1.record_id AS record_id_1,
    mr2.record_id AS record_id_2
FROM healthcare.medical_records mr1
JOIN healthcare.medical_records mr2
  ON mr1.patient_id = mr2.patient_id
 AND date_trunc('day', mr1.record_date) = date_trunc('day', mr2.record_date)
 AND mr1.record_id < mr2.record_id
WHERE (mr1.vitals->>'HR')::int > 100
  AND (mr2.vitals->>'HR')::int > 100;

[User] Show all patients who have received a prescription for medication ID 'med123' and also have a diagnosis code of 'I10'. Include patient ID, prescription ID, and diagnosis date.

[Assistant]
SELECT DISTINCT p.patient_id, p.prescription_id, d.diagnosis_date
FROM healthcare.prescriptions p
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.medication_id = 'med123' AND d.diagnosis_code = 'I10';

[User] Include the prescription date and only show those prescriptions written on or after the diagnosis date.

[Assistant]
SELECT DISTINCT p.patient_id, p.prescription_id, d.diagnosis_date, p.prescription_date
FROM healthcare.prescriptions p
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.medication_id = 'med123' AND d.diagnosis_code = 'I10' AND p.prescription_date >= d.diagnosis_date;

[User] List the record_id, record_date, and treatment_plan for all medical records where the treatment_plan field is not null.

[Assistant]
SELECT record_id, record_date, treatment_plan
FROM healthcare.medical_records
WHERE treatment_plan IS NOT NULL;

[User] For each doctor, count how many medical record entries they have created and show the doctor_id alongside the record count.

[Assistant]
SELECT doctor_id, COUNT(*) AS record_count
FROM healthcare.medical_records
GROUP BY doctor_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] List the full names of citizens who have made payments for services that are currently inactive. Also show the service name and payment amount.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, s.service_name, p.amount
FROM government_services.payments p
JOIN government_services.citizens c ON p.citizen_id = c.citizen_id
JOIN government_services.services s ON p.service_id = s.service_id
WHERE s.is_active = FALSE;

[User] List the appointment IDs and statuses for all appointments scheduled at locations in the city of 'San Francisco'.

[Assistant]
SELECT a.appointment_id, a.status
FROM government_services.appointments a
JOIN government_services.service_locations l ON a.location_id = l.location_id
WHERE l.city = 'San Francisco';

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

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

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

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

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

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

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

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

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

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

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

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

[User] Show the job title, first name, and last name of all employees who were hired before 2010-01-01.

[Assistant]
SELECT job_title, first_name, last_name
FROM government_services.employees
WHERE hire_date < '2010-01-01';

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

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

[User] List the service names, agency names, and standard fees for all services that are active and have a standard fee between 50 and 100 inclusive.

[Assistant]
SELECT s.service_name, ag.agency_name, s.standard_fee
FROM government_services.services s
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE s.is_active = TRUE AND s.standard_fee BETWEEN 50 AND 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 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;

[User] For each claim, retrieve the earliest uploaded document and the latest uploaded document filenames. Return claim_id, earliest_file_name, latest_file_name.

[Assistant]
SELECT e.claim_id,
       e.file_name AS earliest_file_name,
       l.file_name AS latest_file_name
FROM insurance.claim_documents e
JOIN insurance.claim_documents l
  ON e.claim_id = l.claim_id
WHERE e.uploaded_at = (
        SELECT MIN(uploaded_at)
        FROM insurance.claim_documents
        WHERE claim_id = e.claim_id
      )
  AND l.uploaded_at = (
        SELECT MAX(uploaded_at)
        FROM insurance.claim_documents
        WHERE claim_id = l.claim_id
      );

[User] Show me all PDF documents uploaded by agent 'AG456', along with their claim IDs and file sizes.

[Assistant] SELECT claim_id, file_size_bytes FROM insurance.claim_documents WHERE mime_type = 'application/pdf' AND uploaded_by = 'AG456';

[User] Now filter these to only show documents uploaded in the last 6 months that are between 1MB and 10MB in size.

[Assistant] SELECT claim_id, file_size_bytes FROM insurance.claim_documents WHERE mime_type = 'application/pdf' AND uploaded_by = 'AG456' AND uploaded_at >= CURRENT_DATE - INTERVAL '6 months' AND file_size_bytes BETWEEN 1 * 1024 * 1024 AND 10 * 1024 * 1024;

[User] I also want to see the count of such PDF documents per claim.

[Assistant] SELECT claim_id, COUNT(*) AS document_count FROM insurance.claim_documents WHERE mime_type = 'application/pdf' AND uploaded_by = 'AG456' AND uploaded_at >= CURRENT_DATE - INTERVAL '6 months' AND file_size_bytes BETWEEN 1 * 1024 * 1024 AND 10 * 1024 * 1024 GROUP BY claim_id;

[User] Finally, show me the average file size of these filtered PDF documents grouped by claim ID, ordered by average size descending.

[Assistant] SELECT claim_id, AVG(file_size_bytes) AS avg_file_size FROM insurance.claim_documents WHERE mime_type = 'application/pdf' AND uploaded_by = 'AG456' AND uploaded_at >= CURRENT_DATE - INTERVAL '6 months' AND file_size_bytes BETWEEN 1 * 1024 * 1024 AND 10 * 1024 * 1024 GROUP BY claim_id ORDER BY avg_file_size DESC;

[User] List all claim documents for claims handled by the claim handler with ID 'HANDLER_007'. Show document ID, file name, upload time, and claim ID.

[Assistant] SELECT cd.document_id, cd.file_name, cd.uploaded_at, cd.claim_id FROM insurance.claim_documents cd JOIN claims c ON cd.claim_id = c.claim_id WHERE c.claim_handler_id = 'HANDLER_007';

[User] Refine this to only show documents uploaded after January 1st, 2024.

[Assistant] SELECT cd.document_id, cd.file_name, cd.uploaded_at, cd.claim_id FROM insurance.claim_documents cd JOIN claims c ON cd.claim_id = c.claim_id WHERE c.claim_handler_id = 'HANDLER_007' AND cd.uploaded_at > '2024-01-01';

[User] Find the earliest uploaded document for each claim. Show the claim_id, document_id, file_name, and uploaded_at.

[Assistant]
SELECT cd.claim_id, cd.document_id, cd.file_name, cd.uploaded_at
FROM insurance.claim_documents cd
INNER JOIN (
  SELECT claim_id, MIN(uploaded_at) AS min_uploaded_at
  FROM insurance.claim_documents
  GROUP BY claim_id
) latest_docs
ON cd.claim_id = latest_docs.claim_id AND cd.uploaded_at = latest_docs.min_uploaded_at;