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.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )

[User] List policy pairs for the same customer where one policy was cancelled and another active policy started within 30 days after the cancellation. Show customer_id, cancelled policy_number, cancellation_date, active policy_number, start_date.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS cancelled_policy_number,
       p1.cancellation_date,
       p2.policy_number AS active_policy_number,
       p2.start_date
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.status = 'cancelled'
 AND p2.status = 'active'
 AND p2.start_date BETWEEN p1.cancellation_date AND p1.cancellation_date + INTERVAL '30 days';

[User] Also include the number of days between cancellation and new policy start as days_to_new.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS cancelled_policy_number,
       p1.cancellation_date,
       p2.policy_number AS active_policy_number,
       p2.start_date,
       EXTRACT(DAY FROM (p2.start_date - p1.cancellation_date)) AS days_to_new
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.status = 'cancelled'
 AND p2.status = 'active'
 AND p2.start_date BETWEEN p1.cancellation_date AND p1.cancellation_date + INTERVAL '30 days';

[User] Show me the usernames of users who have the word 'explorer' in their bio.

[Assistant]
SELECT username
FROM social_media.users
WHERE bio ILIKE '%explorer%';

[User] For each user, show their user ID and the count of unread notifications they have received.

[Assistant]
SELECT recipient_user_id, COUNT(*) AS unread_notification_count
FROM social_media.notifications
WHERE read_at IS NULL
GROUP BY recipient_user_id;

[User] Can you also show the notification types for those unread notifications?

[Assistant]
SELECT recipient_user_id, notification_type, COUNT(*) AS unread_notification_count
FROM social_media.notifications
WHERE read_at IS NULL
GROUP BY recipient_user_id, notification_type;

[User] Actually, only include users who have joined at least one conversation, and also show one conversation_id they joined.

[Assistant]
SELECT n.recipient_user_id, n.notification_type, COUNT(*) AS unread_notification_count, cp.conversation_id
FROM social_media.notifications n
JOIN social_media.conversation_participants cp ON cp.user_id = n.recipient_user_id
WHERE n.read_at IS NULL
GROUP BY n.recipient_user_id, n.notification_type, cp.conversation_id;

[User] Show all claims handled by agents who have uploaded at least one claim document. Include the claim_id, agent's uploaded document_id, and the incident date.

[Assistant]
SELECT c.claim_id, cd.document_id, c.incident_date
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_handler_id = cd.uploaded_by
WHERE cd.claim_id = c.claim_id;

[User] Can you also include the file_name and the uploaded timestamp of each document?

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

[User] Actually, only show records where the claim status is 'Open' and the document is of type 'POLICE_REPORT'.

[Assistant]
SELECT c.claim_id, cd.document_id, c.incident_date, cd.file_name, cd.uploaded_at
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_handler_id = cd.uploaded_by
WHERE cd.claim_id = c.claim_id
  AND c.status = 'Open'
  AND cd.document_type = 'POLICE_REPORT';


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 transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
##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.applications ( application_id text PRIMARY KEY, 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 text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.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 )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
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 )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Show me all pairs of routes where both routes have the same origin_location_id but different destination_location_id values. For each pair, display the first route's route_number, the second route's route_number, and their origin_location_id.

[Assistant]
SELECT r1.route_number AS first_route_number, r2.route_number AS second_route_number, r1.origin_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id <> r2.route_id
  AND r1.destination_location_id <> r2.destination_location_id;

[User] Now, restrict this to only include pairs where the route type of both routes is 'Express', and order the result by first_route_number ascending.

[Assistant]
SELECT r1.route_number AS first_route_number, r2.route_number AS second_route_number, r1.origin_location_id
FROM transportation.routes r1
JOIN transportation.routes r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id <> r2.route_id
  AND r1.destination_location_id <> r2.destination_location_id
WHERE r1.type = 'Express' AND r2.type = 'Express'
ORDER BY first_route_number ASC;

[User] Show all law firms along with their phone numbers, sorted by the founding date from oldest to newest.

[Assistant]
SELECT firm_id, firm_name, phone, founded_date
FROM legal_services.law_firms
ORDER BY founded_date ASC;

[User] Actually, can you only include law firms that have a managing partner assigned?

[Assistant]
SELECT firm_id, firm_name, phone, founded_date
FROM legal_services.law_firms
WHERE managing_partner_id IS NOT NULL AND managing_partner_id <> ''
ORDER BY founded_date ASC;

[User] Also, show their website if available.

[Assistant]
SELECT firm_id, firm_name, phone, founded_date, website
FROM legal_services.law_firms
WHERE managing_partner_id IS NOT NULL AND managing_partner_id <> ''
ORDER BY founded_date ASC;

[User] Show the full names and contact emails of all citizens who have made a payment for an application that is currently in 'Pending' status.

[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
WHERE a.status = 'Pending';

[User] Show me all insurance plans that have the word 'Managed' in their plan_name, including the plan_id, plan_name, and insurance_provider.

[Assistant]
SELECT plan_id, plan_name, insurance_provider
FROM healthcare.insurance_plans
WHERE plan_name ILIKE '%Managed%';

[User] Now, only include plans where the plan type is 'PPO'.

[Assistant]
SELECT plan_id, plan_name, insurance_provider
FROM healthcare.insurance_plans
WHERE plan_name ILIKE '%Managed%'
  AND plan_type = 'PPO';

[User] For each chain, show the total token_amount and usd_value for selling transactions (type=2).

[Assistant]
SELECT chain, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain;

[User] Can you break down these results further by narrative as well?

[Assistant]
SELECT chain, narrative, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain, narrative;

[User] Retrieve all pairs of medications that share the same generic_name but have different NDC codes. Show the first medication's ID, name, the second medication's ID, name, and the shared generic_name.

[Assistant] SELECT m1.medication_id AS med1_id, m1.medication_name AS med1_name, m2.medication_id AS med2_id, m2.medication_name AS med2_name, m1.generic_name FROM healthcare.medications m1 JOIN healthcare.medications m2 ON m1.generic_name = m2.generic_name AND m1.ndc_code <> m2.ndc_code WHERE m1.medication_id < m2.medication_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 web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
##Table Structure
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) )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.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.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Count how many tokens exist for each contract_address.

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

[User] Now only include contract_address values that have more than 2 tokens.

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

[User] List the appointment_id, patient_id, and reason for all appointments where the notes mention 'urgent'.

[Assistant]
SELECT appointment_id, patient_id, reason
FROM healthcare.appointments
WHERE notes ILIKE '%urgent%';

[User] What is the average delivery time in hours for all delivered service orders?

[Assistant]
SELECT AVG(EXTRACT(EPOCH FROM (so.delivery_timestamp - so.order_timestamp)) / 3600) AS avg_delivery_hours
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered' AND so.delivery_timestamp IS NOT NULL;

[User] Now only include orders delivered after January 1, 2024.

[Assistant]
SELECT AVG(EXTRACT(EPOCH FROM (so.delivery_timestamp - so.order_timestamp)) / 3600) AS avg_delivery_hours
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered'
  AND so.delivery_timestamp >= '2024-01-01'::timestamp;

[User] List the names of employees whose job title is the same as their manager's job title. Include the employee's first name, last name, their manager's first name, last name, and their shared job title.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.first_name ,  T2.last_name ,  T1.job_title FROM employees AS T1 JOIN employees AS T2 ON T1.manager_employee_id  =  T2.employee_id WHERE T1.job_title  =  T2.job_title

[User] Show the number of UTXOs associated with each unique address in the system.

[Assistant] SELECT address, COUNT(utxo_id) FROM trading_platform.utxos GROUP BY address;

[User] What are the top 5 most recently registered verified citizens? Return the citizen ID, full name, and registration date.

[Assistant]
SELECT citizen_id,
       first_name || ' ' || last_name AS full_name,
       registration_date
FROM government_services.citizens
WHERE is_verified = TRUE
ORDER BY registration_date DESC
LIMIT 5;

[User] List the product ID and product name for all insurance products where the coverage details mention 'warranty'.

[Assistant] SELECT product_id, product_name FROM insurance.insurance_products WHERE coverage_details LIKE '%warranty%';

[User] Please also include the product type and base premium, and only show products that are currently active.

[Assistant] SELECT product_id, product_name, product_type, base_premium FROM insurance.insurance_products WHERE coverage_details LIKE '%warranty%' AND is_active = TRUE;

[User] Show the medication ID, medication name, and manufacturer for all entries where the generic name is not listed.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] For all medications, list the medication name, generic name, and the length of the description, but only for descriptions longer than 50 characters.

[Assistant] SELECT medication_name, generic_name, LENGTH(description) AS description_length FROM healthcare.medications WHERE LENGTH(description) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
##Table Structure
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
##Table Structure
Collection 'inspections'. Document structure: { _id: <ObjectId (or inspection_id)>, inspection_id: String, build_id: String (reference), component_id: String (reference, optional), step_id: String (reference, optional), inspection_type: String, inspector_employee_id: String (reference), inspection_timestamp: ISODate, result: String, remarks: String }. Required: inspection_id, build_id, inspection_type, inspector_employee_id, inspection_timestamp, result. Indexes on build_id, component_id, step_id, inspector_employee_id, result.
##Table Structure
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me all time entries from the last 90 days, including the entry description, hours spent, the name of the case, and the name of the client.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name, T3.first_name, T3.last_name FROM legal_services.time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id JOIN clients AS T3 ON T2.client_id = T3.client_id WHERE T1.date_worked >= CURRENT_DATE - INTERVAL '90 days';

[User] List all posts where the content mentions 'meeting'.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%'

[User] Also, only include those posts that are public.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%' AND visibility = 'public'

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

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

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

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

[User] How many smart money addresses are in the top 100 rank?

[Assistant] SELECT count(address) FROM smart_money_profit WHERE rank <= 100

[User] Okay, can you break that down by `chain`? Show the count for each chain where the rank is 100 or better.

[Assistant] SELECT chain, count(address) FROM smart_money_profit WHERE rank <= 100 GROUP BY chain

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

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

[User] Find the average settlement_amount of closed claims for each claim handler. Return claim_handler_id and avg_settlement_amount.

[Assistant]
SELECT c.claim_handler_id, AVG(c.settlement_amount) AS avg_settlement_amount
FROM insurance.claims c
WHERE c.status = 'Closed'
  AND c.settlement_amount IS NOT NULL
GROUP BY c.claim_handler_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, 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.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )
##Table Structure
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] Count the total number of employees who have a direct manager assigned.

[Assistant] SELECT COUNT(employee_id) FROM government_services.employees WHERE manager_employee_id IS NOT NULL;

[User] List the document ID, document type, and the full name of the citizen who submitted the document, but only for documents submitted for applications with a status of 'Approved'.

[Assistant] SELECT T1.document_id, T1.document_type, T3.first_name, T3.last_name FROM government_services.documents AS T1 JOIN government_services.applications AS T2 ON T1.application_id = T2.application_id JOIN government_services.citizens AS T3 ON T1.citizen_id = T3.citizen_id WHERE T2.status = 'Approved';

[User] List all token symbols related to the 'Gaming' narrative that had a net positive token inflow.

[Assistant] SELECT token_symbol FROM smart_money_token_inflow WHERE narrative = 'Gaming' AND usd_value > 0 GROUP BY token_symbol;

[User] List all CEX addresses on the BSC chain that hold more than $1 million USD value in total.

[Assistant] SELECT address, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'BSC' GROUP BY address HAVING SUM(usd_value) > 1000000;

[User] Provide every combination of medication name and insurance plan name.

[Assistant]
SELECT m.medication_name, p.plan_name
FROM healthcare.medications AS m
CROSS JOIN healthcare.insurance_plans AS p;

[User] List all smart money addresses that have a negative PNL but a positive Realized Ratio. Show the address, chain, PNL, and Realized Ratio.

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < 0 AND realized_ratio > 0

[User] Can you refine the results to only include addresses where the absolute value of PNL is greater than 1000?

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < -1000 AND realized_ratio > 0

[User] List all pairs of token transfers where the sender is the same but the recipients differ. Show both transfer IDs and the common sender address.

[Assistant]
SELECT t1.transfer_id AS transfer_id_1, t2.transfer_id AS transfer_id_2, t1.from_address AS common_from_address
FROM web3.token_transfers t1
JOIN web3.token_transfers t2
  ON t1.from_address = t2.from_address
    AND t1.to_address <> t2.to_address
    AND t1.transfer_id < t2.transfer_id;

[User] How many conversations are there where the last message was sent before January 1, 2024?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE last_message_at < '2024-01-01';


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.agencies ( agency_id text PRIMARY KEY, 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.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 )
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 )
##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) )
CREATE TABLE web3.transactions ( transaction_id.text, from_address.text, to_address.text, value.numeric, gas_used.integer, gas_price.numeric, block_number.integer, timestamp.timestamp, input_data.text, status.text, nonce.integer )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
##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 text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )

[User] Provide the message_subject and agency_name for all notifications that are related to agencies and have a status of 'Sent'.

[Assistant]
SELECT n.message_subject, a.agency_name
FROM government_services.notifications n
JOIN government_services.agencies a ON n.related_entity_id = a.agency_id
WHERE n.related_entity_type = 'agency' AND n.status = 'Sent';

[User] Find all tokens with their contract addresses and the number of wallets that hold each token, sorted by wallet count in descending order.

[Assistant] SELECT t.token_id, t.contract_address, COUNT(DISTINCT w.wallet_id) AS wallet_count FROM web3.tokens t LEFT JOIN web3.transactions tr ON t.contract_address = tr.to_address OR t.contract_address = tr.from_address JOIN web3.wallets w ON tr.from_address = w.address OR tr.to_address = w.address GROUP BY t.token_id, t.contract_address ORDER BY wallet_count DESC;

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

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

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

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

[User] Find pairs of wallets that were created at the exact same timestamp but are owned by different users. List the IDs of both wallets and the shared creation timestamp.

[Assistant]
SELECT
    w1.wallet_id AS wallet1_id,
    w2.wallet_id AS wallet2_id,
    w1.created_at
FROM
    web3.wallets w1
JOIN
    web3.wallets w2 ON w1.created_at = w2.created_at
WHERE
    w1.wallet_id < w2.wallet_id
    AND w1.user_id != w2.user_id;

[User] Provide a list of all email addresses used by citizens whose national ID number starts with 'X'.

[Assistant] SELECT contact_email FROM government_services.citizens WHERE national_id_number LIKE 'X%';

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

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

[User] List all unavailable services along with their names, prices, and the departments they belong to.

[Assistant] SELECT service_name, price, department FROM hospitality_technology.services WHERE is_available = false;

[User] Only include services that are priced below 30 and belong to the 'Laundry' or 'Housekeeping' departments.

[Assistant] SELECT service_name, price, department FROM hospitality_technology.services WHERE is_available = false AND price < 30 AND department IN ('Laundry', 'Housekeeping');

[User] Count how many assets have metadata entries for each metadata key, and list the metadata key and asset_count ordered by asset_count descending.

[Assistant]
SELECT key,
       COUNT(DISTINCT asset_id) AS asset_count
FROM trading_platform.metadata
GROUP BY key
ORDER BY asset_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
##Table Structure
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )

[User] Get the total_quantity and total_revenue (sum of total_price) for each staff member who placed orders (staff_id_ordered).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
GROUP BY staff_id_ordered;

[User] Filter to staff who have delivered at least one order (staff_id_delivered is not null).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
WHERE staff_id_delivered IS NOT NULL
GROUP BY staff_id_ordered;

[User] For these staff members, list each order along with the previous order they placed, including first_order_timestamp and second_order_timestamp, and the time difference in hours.

[Assistant]
SELECT t1.staff_id_ordered,
       t1.order_id AS first_order_id,
       t2.order_id AS second_order_id,
       t1.order_timestamp AS first_order_timestamp,
       t2.order_timestamp AS second_order_timestamp,
       EXTRACT(EPOCH FROM (t2.order_timestamp - t1.order_timestamp)) / 3600 AS hours_diff
FROM hospitality_technology.service_orders t1
JOIN hospitality_technology.service_orders t2
  ON t1.staff_id_ordered = t2.staff_id_ordered
 AND t2.order_timestamp > t1.order_timestamp
 AND NOT EXISTS (
       SELECT 1 FROM hospitality_technology.service_orders t3
       WHERE t3.staff_id_ordered = t1.staff_id_ordered
         AND t3.order_timestamp > t1.order_timestamp
         AND t3.order_timestamp < t2.order_timestamp
   )
WHERE t1.staff_id_delivered IS NOT NULL
  AND t2.staff_id_delivered IS NOT NULL
ORDER BY t1.staff_id_ordered, t1.order_timestamp;

[User] Find all patients along with the number of unique diagnoses each has received. Only include patients who have at least two diagnoses.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, COUNT(DISTINCT d.diagnosis_id) AS num_diagnoses
FROM healthcare.patients p
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
GROUP BY p.patient_id, p.first_name, p.last_name
HAVING COUNT(DISTINCT d.diagnosis_id) >= 2;

[User] List the user IDs and the date they joined their most recent conversation.

[Assistant]
SELECT user_id, MAX(joined_at) AS most_recent_joined_at
FROM social_media.conversation_participants
GROUP BY user_id;

[User] Can you also include the setting ID and last time they updated their user settings?

[Assistant]
SELECT cp.user_id, MAX(cp.joined_at) AS most_recent_joined_at, us.setting_id, us.updated_at AS last_settings_update
FROM social_media.conversation_participants cp
LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id
GROUP BY cp.user_id, us.setting_id, us.updated_at;

[User] Only show users who joined their most recent conversation after June 1, 2024 and have push notifications enabled.

[Assistant]
SELECT cp.user_id, MAX(cp.joined_at) AS most_recent_joined_at, us.setting_id, us.updated_at AS last_settings_update
FROM social_media.conversation_participants cp
LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id
WHERE us.push_notifications_enabled = true
GROUP BY cp.user_id, us.setting_id, us.updated_at
HAVING MAX(cp.joined_at) > '2024-06-01';

[User] Which citizens have scheduled appointments at locations located in 'New York'? Show their first and last name as well as the location name.

[Assistant]
SELECT DISTINCT c.first_name, c.last_name, sl.location_name
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.service_locations sl ON a.location_id = sl.location_id
WHERE sl.state = 'New York';

[User] For each fueling event, show the fuel_log_id, vehicle_id, the full name of the assigned driver for the trip during that fueling event, and the log_timestamp.

[Assistant]
SELECT fl.fuel_log_id, fl.vehicle_id, d.first_name || ' ' || d.last_name AS driver_full_name, fl.log_timestamp
FROM transportation.fuel_logs fl
JOIN transportation.trips t ON fl.trip_id = t.trip_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id;

[User] List all room types that have a King bed and include their maximum occupancy and amenities.

[Assistant] SELECT type_name, max_occupancy, amenities FROM hospitality_technology.room_types WHERE bed_type = 'King';

[User] Please sort them by maximum occupancy in ascending order.

[Assistant] SELECT type_name, max_occupancy, amenities FROM hospitality_technology.room_types WHERE bed_type = 'King' ORDER BY max_occupancy 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 gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
##Table Structure
CREATE TABLE financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, 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.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] I need to find every offline server alongside an online server in the same region.

[Assistant]
SELECT s_off.server_id AS offline_id,
       s_on.server_id AS online_id
FROM gaming_technology.servers s_off
JOIN gaming_technology.servers s_on
  ON s_off.region = s_on.region
WHERE s_off.status = 'offline'
  AND s_on.status = 'online';

[User] Include the names of both servers, labeling them offline_server and online_server.

[Assistant]
SELECT s_off.server_name AS offline_server,
       s_on.server_name AS online_server
FROM gaming_technology.servers s_off
JOIN gaming_technology.servers s_on
  ON s_off.region = s_on.region
WHERE s_off.status = 'offline'
  AND s_on.status = 'online';

[User] Also add the online server's current_players and status.

[Assistant]
SELECT s_off.server_name AS offline_server,
       s_on.server_name AS online_server,
       s_on.current_players,
       s_on.status AS online_status
FROM gaming_technology.servers s_off
JOIN gaming_technology.servers s_on
  ON s_off.region = s_on.region
WHERE s_off.status = 'offline'
  AND s_on.status = 'online';

[User] Order the results by offline_server ascending.

[Assistant]
SELECT s_off.server_name AS offline_server,
       s_on.server_name AS online_server,
       s_on.current_players,
       s_on.status AS online_status
FROM gaming_technology.servers s_off
JOIN gaming_technology.servers s_on
  ON s_off.region = s_on.region
WHERE s_off.status = 'offline'
  AND s_on.status = 'online'
ORDER BY offline_server ASC;

[User] List all pairs of customers who have the same last name but live in different states. Show both customer ids, their full names, and their states.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name AS first_name_a, a.last_name AS last_name, a.state AS state_a, b.customer_id AS customer_id_b, b.first_name AS first_name_b, b.state AS state_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.last_name = b.last_name
  AND a.customer_id < b.customer_id
  AND a.state <> b.state;

[User] Also, show the city for each customer in the result.

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

[User] Show each user's username along with their KYC status and the date of their latest KYC review.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
);

[User] Also filter to only include those whose latest status is 'approved'.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
)
  AND ka.status = 'approved';

[User] List each property_name along with the count of rooms that are currently marked as 'Available'.

[Assistant]
SELECT p.property_name, COUNT(r.room_id) AS available_room_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r
  ON p.property_id = r.property_id AND r.status = 'Available'
GROUP BY p.property_name;

[User] Only include properties with more than 10 available rooms and order by available_room_count descending.

[Assistant]
SELECT p.property_name, COUNT(r.room_id) AS available_room_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r
  ON p.property_id = r.property_id AND r.status = 'Available'
GROUP BY p.property_name
HAVING COUNT(r.room_id) > 10
ORDER BY available_room_count DESC;

[User] Which staff members have never been assigned a manager? List their full names and property IDs.

[Assistant]
SELECT staff_id, first_name, last_name, property_id
FROM hospitality_technology.staff
WHERE manager_id IS NULL;

[User] Also include their work email and only show currently active staff.

[Assistant]
SELECT staff_id, first_name, last_name, property_id, work_email
FROM hospitality_technology.staff
WHERE manager_id IS NULL AND is_active = true;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )
##Table Structure
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    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, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )
##Table Structure
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)

[User] For hashtag ID 'H789', get each post ID and the number of distinct comments that have been made on those posts.

[Assistant]
SELECT ph.post_id,
       COUNT(DISTINCT c.comment_id) AS comment_count
FROM social_media.post_hashtags ph
JOIN social_media.comments c ON ph.post_id = c.post_id
WHERE ph.hashtag_id = 'H789'
GROUP BY ph.post_id;

[User] List the names and cities of all service locations, along with the agency ID, where the locations are marked as accessible.

[Assistant] SELECT location_name, city, agency_id FROM government_services.service_locations WHERE is_accessible = TRUE;

[User] Can you also include the state for each location and sort the results by city alphabetically?

[Assistant] SELECT location_name, city, state, agency_id FROM government_services.service_locations WHERE is_accessible = TRUE ORDER BY city ASC;

[User] Show the total and average balance for each account_type.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type;

[User] Exclude any account types where the total balance is zero or negative.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 0;

[User] Sort the output by average balance in descending order.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 0 ORDER BY avg_balance DESC;

[User] List all staff members who processed payments for guest ID 'G123', including their first name, last name, and the payment ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.payment_id FROM staff AS T1 JOIN payments AS T2 ON T1.staff_id = T2.staff_id_processed WHERE T2.guest_id = 'G123';

[User] List the case ID, case number, and case name for all cases with status 'Open'.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open';

[User] Now, only show those cases opened in the year 2023.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023;

[User] Great, could you also show the lead lawyer ID and count how many open cases each of those lawyers has opened in 2023, displaying this count alongside the case details for each case? Order the results by date opened ascending.

[Assistant] SELECT c.case_id, c.case_number, c.case_name, c.lead_lawyer_id, lawyer_case_counts.case_count FROM legal_services.cases AS c JOIN ( SELECT lead_lawyer_id, COUNT(*) AS case_count FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023 GROUP BY lead_lawyer_id ) AS lawyer_case_counts ON c.lead_lawyer_id = lawyer_case_counts.lead_lawyer_id WHERE c.status = 'Open' AND EXTRACT(YEAR FROM c.date_opened) = 2023 ORDER BY c.date_opened 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 legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text 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 )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )

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

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

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

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

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

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

[User] List the application ID, citizen ID, assigned employee's full name, and total amount paid for each approved application.

[Assistant]
SELECT a.application_id,
       a.citizen_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       COALESCE(SUM(p.amount), 0) AS total_paid
FROM government_services.applications a
LEFT JOIN government_services.employees e
  ON a.assigned_employee_id = e.employee_id
LEFT JOIN government_services.payments p
  ON a.application_id = p.application_id
WHERE a.status = 'Approved'
GROUP BY a.application_id, a.citizen_id, e.first_name, e.last_name;

[User] List all room types along with their property name, bed type, and base rate for properties located in Canada, ordered by base rate descending.

[Assistant]
SELECT rt.type_name, p.property_name, rt.bed_type, rt.base_rate
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p
  ON rt.property_id = p.property_id
WHERE p.country_code = 'CA'
ORDER BY rt.base_rate DESC;

[User] Calculate the total and average premium amounts for policies that are currently Active.

[Assistant]
SELECT SUM(premium_amount) AS total_premium,
       AVG(premium_amount) AS average_premium
FROM insurance.policies
WHERE status = 'Active';

[User] List the full names and contact email of agents whose agency name contains 'Insurance'.

[Assistant] SELECT first_name, last_name, contact_email FROM insurance.agents WHERE agency_name LIKE '%Insurance%'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.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) )
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
##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 the asset names and symbols for all assets of type 'token'.

[Assistant] SELECT name, symbol FROM trading_platform.assets WHERE type = 'token';

[User] Find all pairs of achievement unlocks and item acquisitions by the same player where the item was acquired after the achievement was unlocked. List player_id, achievement_id, unlocked_at, item_id, and acquired_at.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at;

[User] Only include pairs where the item acquisition happened within 24 hours after the achievement unlock.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at AND pi.acquired_at <= pa.unlocked_at + INTERVAL '24 hours';

[User] List all insurance products along with their product type and creation date.

[Assistant]
SELECT product_name, product_type, created_at
FROM insurance.insurance_products;

[User] Show me pairs of invoice numbers for the same case.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id ORDER BY T1.case_id, T1.invoice_number, T2.invoice_number

[User] Only include pairs where the total amount of one invoice is greater than the other.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount ORDER BY T1.case_id, invoice1_amount DESC

[User] Exclude pairs where the issue dates are more than 90 days apart.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount, ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) AS days_apart FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount AND ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) <= 90 ORDER BY T1.case_id, days_apart ASC

[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;