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.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.token_transfers ( transfer_id.text, token_id.text, from_address.text, to_address.text, value.numeric, transaction_id.text, log_index.integer )
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE web3.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
##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 )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )
##Table Structure
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    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, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
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 )
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.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 healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.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 healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Show me all conversation IDs (whether group chat or not) that have at least one hashtag used in posts linked to them.

[Assistant]
SELECT DISTINCT c.conversation_id
FROM social_media.conversations c
JOIN social_media.post_hashtags ph ON c.conversation_id = ph.post_id;

[User] List the transaction IDs that have both an event and a token transfer, along with the name of the event and the value of the token transfer.

[Assistant] SELECT T1.transaction_id, T1.event_name, T2.value FROM web3.events AS T1 JOIN web3.token_transfers AS T2 ON T1.transaction_id = T2.transaction_id;

[User] List the patient ID, first name, last name, and phone number for all patients whose emergency contact name or phone number is missing.

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE emergency_contact_name IS NULL OR emergency_contact_name = '' OR emergency_contact_phone IS NULL OR emergency_contact_phone = '';

[User] Refine this to also include patients who have a listed email address and sort the results by patient_id.

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE (emergency_contact_name IS NULL OR emergency_contact_name = '' OR emergency_contact_phone IS NULL OR emergency_contact_phone = '') AND email IS NOT NULL AND email != '' ORDER BY patient_id;

[User] Show me the subjects and start times of all appointments along with the document names of any documents uploaded for the associated case.

[Assistant]
SELECT a.subject, a.start_time, d.document_name
FROM legal_services.appointments a
JOIN legal_services.documents d ON a.case_id = d.case_id;

[User] List the full names of all employees who are currently employed (i.e., have no termination date).

[Assistant] SELECT first_name || ' ' || last_name AS full_name FROM government_services.employees WHERE termination_date IS NULL;

[User] List all fuel log entries with their associated trip's route_number and the vehicle's license_plate where the total_cost exceeds 200, sorted by total_cost descending.

[Assistant]
SELECT fl.*, t.route_id, r.route_number, v.license_plate
FROM transportation.fuel_logs fl
JOIN transportation.trips t ON fl.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_id
WHERE fl.total_cost > 200
ORDER BY fl.total_cost DESC;

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

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

[User] Find all insurance plans that have both a contact phone number and a website listed, showing their provider and plan type.

[Assistant] SELECT insurance_provider, plan_type FROM healthcare.insurance_plans WHERE contact_phone IS NOT NULL AND website IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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.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.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 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 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)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.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 PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )
##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 character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
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 )

[User] Count the number of active services provided by each agency. Return the agency_name and the count of active services for each.

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

[User] List the plan_id, plan_name, and plan_type for all insurance plans where the insurance_provider is 'Humana'.

[Assistant]
SELECT
  plan_id,
  plan_name,
  plan_type
FROM healthcare.insurance_plans
WHERE
  insurance_provider = 'Humana';

[User] Get each review with the next review date for the same guest.

[Assistant]
SELECT guest_id, review_id, review_date,
       LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
FROM hospitality_technology.reviews;

[User] Exclude entries where there's no next review.

[Assistant]
SELECT guest_id, review_id, review_date, next_review_date
FROM (
  SELECT guest_id, review_id, review_date,
         LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
  FROM hospitality_technology.reviews
) t
WHERE next_review_date IS NOT NULL;

[User] Now join the table to retrieve the comment of the next review as well.

[Assistant]
WITH sequenced AS (
  SELECT guest_id, review_id, review_date,
         LEAD(review_id) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_id,
         LEAD(review_date) OVER (PARTITION BY guest_id ORDER BY review_date) AS next_review_date
  FROM hospitality_technology.reviews
)
SELECT s.guest_id,
       s.review_id,
       s.review_date,
       r2.review_id AS next_review_id,
       r2.review_date AS next_review_date,
       r2.comment AS next_comment
FROM sequenced s
JOIN hospitality_technology.reviews r2
  ON s.next_review_id = r2.review_id
WHERE s.next_review_id IS NOT NULL;

[User] List all contracts along with the username of the deployer, showing contract_id, contract address, deployed_at, and the username. Order by deployed_at descending.

[Assistant]
SELECT c.contract_id,
       c.address AS contract_address,
       c.deployed_at,
       u.username
FROM web3.contracts c
LEFT JOIN web3.wallets w ON c.deployer_address = w.address
LEFT JOIN web3.users u ON w.user_id = u.user_id
ORDER BY c.deployed_at 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 gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
##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 )
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, 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 int, location_id text )
CREATE TABLE transportation.bookings (
    booking_id character varying(64) NOT NULL,  -- unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- identifier of the passenger making the booking
    trip_id character varying(64) NOT NULL, -- identifier of the trip being booked
    seat_number character varying(16), -- assigned seat number (if applicable)
    booking_time timestamp with time zone NOT NULL, -- time when the booking was made
    status character varying(32) NOT NULL, -- e.g., Confirmed, Cancelled, Pending Payment
    fare numeric(10, 2) NOT NULL, -- price paid for the booking
    payment_transaction_id character varying(128), -- reference to the payment transaction
    special_requests text, -- any special requests from the passenger
    PRIMARY KEY (booking_id)
)
##Table Structure
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, 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 int, cargo_manifest_id text )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] Please list the top 5 players by number of achievements unlocked since 2023-01-01. Show each player's username and the total count of achievements they unlocked.

[Assistant]
SELECT p.username, COUNT(*) AS unlock_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
WHERE pa.unlocked_at >= '2023-01-01'
GROUP BY p.username
ORDER BY unlock_count DESC
LIMIT 5;

[User] Show all trips, including the trip ID, vehicle license plate, and the vehicle's capacity.

[Assistant] SELECT t.trip_id, v.license_plate, v.capacity FROM transportation.trips t JOIN vehicles v ON t.vehicle_id = v.vehicle_id;

[User] Show me all messages sent after July 1, 2024, including the sender_user_id, content, and sent_at.

[Assistant]
SELECT message_id, sender_user_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01';

[User] Can you also include the conversation_id and only show messages that have not been read yet?

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL;

[User] Now only show results where the message contains a media attachment and order the results by sent_at descending.

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL AND media_url IS NOT NULL AND media_url <> ''
ORDER BY sent_at DESC;

[User] Show all trips with their trip ID, route ID, the ID of their origin location, and the ID of their destination location, where the route ID starts with 'EX'.

[Assistant] SELECT trip_id, route_id, origin_location_id, destination_location_id FROM transportation.trips WHERE route_id LIKE 'EX%';

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

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

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

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

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

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

[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_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 transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##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.policies ( policy_id text, 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.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.premium_payments ( payment_id text, 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 )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text PRIMARY KEY, 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 web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone 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 character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)

[User] Find all cities that contain at least one location of type 'Depot' and at least one location of type 'Station'.

[Assistant] SELECT city FROM transportation.locations WHERE type IN ('Depot', 'Station') GROUP BY city HAVING COUNT(DISTINCT CASE WHEN type = 'Depot' THEN location_id END) > 0 AND COUNT(DISTINCT CASE WHEN type = 'Station' THEN location_id END) > 0;

[User] What is the total amount paid across all premium payments for payments marked as 'Failed'?

[Assistant] SELECT sum(amount_paid) FROM insurance.premium_payments WHERE status = 'Failed';

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

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

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

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

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

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

[User] Find token transfers within the same transaction where the recipient of an earlier transfer (based on log_index) becomes the sender of a later transfer. List the transaction ID, the earlier transfer ID, the later transfer ID, the shared address, and the value transferred in both cases.

[Assistant] SELECT t1.transaction_id, t1.transfer_id AS earlier_transfer_id, t2.transfer_id AS later_transfer_id, t1.to_address AS shared_address, t1.value AS earlier_transfer_value, t2.value AS later_transfer_value FROM web3.token_transfers AS t1 JOIN web3.token_transfers AS t2 ON t1.transaction_id = t2.transaction_id WHERE t1.to_address = t2.from_address AND t1.log_index < t2.log_index;

[User] List all pairs of vehicles with the same make and model but different manufacture years. Include each vehicle's ID, make, model, and both years.

[Assistant]
SELECT v1.vehicle_id AS vehicle1_id, v2.vehicle_id AS vehicle2_id, v1.make, v1.model, v1.year AS year1, v2.year AS year2
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model = v2.model
  AND v1.year <> v2.year
  AND v1.vehicle_id < v2.vehicle_id
ORDER BY v1.make, v1.model, v1.year;

[User] List each vehicle along with the city of the station where it had its most recent fueling and the timestamp of that fueling.

[Assistant]
SELECT v.vehicle_id,
       v.license_plate,
       l.city AS last_fuel_city,
       MAX(f.log_timestamp) AS last_fuel_time
FROM transportation.vehicles v
JOIN transportation.fuel_logs f
  ON v.vehicle_id = f.vehicle_id
JOIN transportation.locations l
  ON f.location_id = l.location_id
GROUP BY v.vehicle_id, v.license_plate, l.city
ORDER BY last_fuel_time 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 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.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 )
##Table Structure
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
##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) )
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, 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 character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.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 )
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 web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )

[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and the count of transactions they've been involved in, sorted by transaction count in descending order.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address, COUNT(t.transaction_id) AS transaction_count FROM web3.contracts c LEFT JOIN web3.transactions t ON c.address = t.to_address OR c.address = t.from_address WHERE c.network_id = 'ethereum' GROUP BY c.contract_id, c.address, c.deployer_address ORDER BY transaction_count DESC;

[User] Count the number of diagnoses for each unique diagnosis code.

[Assistant] SELECT diagnosis_code, COUNT(*) FROM healthcare.diagnoses GROUP BY diagnosis_code;

[User] Only show the diagnosis codes that have more than 10 entries.

[Assistant] SELECT diagnosis_code, COUNT(*) FROM healthcare.diagnoses GROUP BY diagnosis_code HAVING COUNT(*) > 10;

[User] List all agents whose commission rate is higher than their manager's commission rate, including the agent's full name, their commission rate, the manager's full name, and the manager's commission rate.

[Assistant] SELECT CONCAT(a.first_name, ' ', a.last_name) AS agent_full_name, a.commission_rate AS agent_commission_rate, CONCAT(m.first_name, ' ', m.last_name) AS manager_full_name, m.commission_rate AS manager_commission_rate FROM insurance.agents AS a JOIN insurance.agents AS m ON a.manager_id = m.agent_id WHERE a.commission_rate > m.commission_rate;

[User] Find all service locations that currently have no appointments scheduled. Display the location name and contact phone number.

[Assistant]
SELECT sl.location_name,
       sl.contact_phone
FROM government_services.service_locations sl
LEFT JOIN government_services.appointments ap ON sl.location_id = ap.location_id
WHERE ap.appointment_id IS NULL;

[User] Find all pairs of transactions where both transactions have the same nonce and from_address, but different transaction_id. Show both transaction IDs, the shared from_address, shared nonce, and their block numbers.

[Assistant]
SELECT t1.transaction_id AS transaction_id_1, t2.transaction_id AS transaction_id_2, t1.from_address, t1.nonce, t1.block_number AS block_number_1, t2.block_number AS block_number_2
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
 AND t1.nonce = t2.nonce
 AND t1.transaction_id < t2.transaction_id;

[User] What is the average score across all game sessions for each game? Include the game title and the average score.

[Assistant] SELECT T1.title, AVG(T2.score) FROM gaming_technology.games AS T1 JOIN gaming_technology.game_sessions AS T2 ON T1.game_id = T2.game_id GROUP BY T1.title;


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.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
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 transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
##Table Structure
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 web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
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.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
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.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
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) )

[User] Get all notifications for posts tagged with hashtag 'H123', showing notification_id and created_at.

[Assistant]
SELECT n.notification_id, n.created_at
FROM social_media.notifications n
JOIN social_media.post_hashtags ph
  ON n.target_entity_type = 'post'
  AND n.target_entity_id = ph.post_id
WHERE ph.hashtag_id = 'H123';

[User] Now filter to only include notifications of type 'comment'.

[Assistant]
SELECT n.notification_id, n.created_at
FROM social_media.notifications n
JOIN social_media.post_hashtags ph
  ON n.target_entity_type = 'post'
  AND n.target_entity_id = ph.post_id
WHERE ph.hashtag_id = 'H123'
  AND n.notification_type = 'comment';

[User] For each fuel type, list the number of unique locations where fuel refueling occurred, and also show the total quantity refueled for that fuel type and location.

[Assistant]
SELECT fuel_type, location_id, COUNT(DISTINCT location_id) AS unique_location_count, SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY fuel_type, location_id;

[User] Find all review comments that have a staff response, showing the comment and the staff response date.

[Assistant] SELECT comment, response_date FROM reviews WHERE response_date IS NOT NULL;

[User] Now, also include the name of the staff member who responded.

[Assistant] SELECT T1.comment, T1.response_date, T2.first_name, T2.last_name FROM reviews AS T1 JOIN staff AS T2 ON T1.response_staff_id = T2.staff_id WHERE T1.response_date IS NOT NULL;

[User] Further filter this list to only show responses made more than 24 hours after the review was submitted, and include the review date and the reservation ID.

[Assistant] SELECT T1.comment, T1.response_date, T2.first_name, T2.last_name, T1.review_date, T1.reservation_id FROM reviews AS T1 JOIN staff AS T2 ON T1.response_staff_id = T2.staff_id WHERE T1.response_date IS NOT NULL AND T1.response_date > T1.review_date + INTERVAL '24 hours';

[User] Count the number of users for each email domain.

[Assistant]
SELECT split_part(email, '@', 2) AS domain, COUNT(*) AS user_count
FROM web3.users
GROUP BY domain;

[User] Filter to domains with more than 5 users.

[Assistant]
SELECT split_part(email, '@', 2) AS domain, COUNT(*) AS user_count
FROM web3.users
GROUP BY domain
HAVING COUNT(*) > 5;

[User] Can you provide the total number of fuel refueling events and the sum of total_cost at each fueling location, including the location name and city?

[Assistant]
SELECT l.location_id, l.name, l.city, COUNT(fl.fuel_log_id) AS num_refuels, SUM(fl.total_cost) AS total_cost
FROM transportation.fuel_logs fl
JOIN transportation.locations l ON fl.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city;

[User] For each user, what is the average time difference in days between their wallet creations? Return user_id and avg_diff_days.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id;

[User] Actually, only include users who have created more than 2 wallets.

[Assistant]
WITH diffs AS (
  SELECT
    user_id,
    EXTRACT(EPOCH FROM (created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at))) / 86400 AS diff_days
  FROM web3.wallets
)
SELECT
  user_id,
  AVG(diff_days) AS avg_diff_days
FROM diffs
WHERE diff_days IS NOT NULL
GROUP BY user_id
HAVING COUNT(diff_days) > 1;

[User] List all available services along with the property name where they are offered.

[Assistant]
SELECT s.service_id, s.service_name, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_available = 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 government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
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.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 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 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.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.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.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.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.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 )
##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) )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
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.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, 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 int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone 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.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
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 )

[User] List documents uploaded for applications that have received payments. Display the document ID, document type, associated application ID, and the payment amount.

[Assistant] SELECT T1.document_id, T1.document_type, T1.application_id, T2.amount FROM government_services.documents AS T1 JOIN government_services.payments AS T2 ON T1.application_id = T2.application_id;

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

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

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

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

[User] Retrieve the service name and the count of applications currently in 'Under Review' status for each service.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS under_review_count
FROM government_services.services s
LEFT JOIN government_services.applications a ON s.service_id = a.service_id AND a.status = 'Under Review'
GROUP BY s.service_name;

[User] Show me every unique combination of mechanic and service type that has performed maintenance, and the total number of such services per combination.

[Assistant] SELECT mechanic_name, service_type, COUNT(*) AS total_services FROM transportation.maintenance_logs GROUP BY mechanic_name, service_type;

[User] Now, only display combinations where the total number of services equals or exceeds 3.

[Assistant] SELECT mechanic_name, service_type, COUNT(*) AS total_services FROM transportation.maintenance_logs GROUP BY mechanic_name, service_type HAVING COUNT(*) >= 3;

[User] Which agents have sold policies with a coverage limit over 1,000,000, and what are the policy numbers and their respective coverage limits?

[Assistant] SELECT agent_id, policy_number, coverage_limit FROM insurance.policies WHERE coverage_limit > 1000000;

[User] List maintenance logs including vehicle make, model, service_date, cost, and next_service_due_date for vehicles that are currently 'Active'.

[Assistant]
SELECT ml.log_id,
       v.make,
       v.model,
       ml.service_date,
       ml.cost,
       ml.next_service_due_date
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.status = 'Active';

[User] Show the full name, job title, and termination date for all employees whose job title includes the word 'Specialist' and who are no longer employed.

[Assistant] SELECT first_name, last_name, job_title, termination_date FROM government_services.employees WHERE job_title LIKE '%Specialist%' AND termination_date IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
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.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 )
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.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
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.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, 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 financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )
##Table Structure
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.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.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 )
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )

[User] For each route type, count the distinct vehicles that have completed trips on those routes. Return type and vehicle_count, sorted by vehicle_count descending.

[Assistant]
SELECT r.type,
       COUNT(DISTINCT t.vehicle_id) AS vehicle_count
FROM transportation.routes r
JOIN transportation.trips t ON r.route_id = t.route_id
WHERE t.status = 'Completed'
GROUP BY r.type
ORDER BY vehicle_count DESC;

[User] Find the total unbilled but billable hours for each lawyer. Only include lawyers with more than 10 such hours, and sort by total hours descending.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_unbilled_hours FROM legal_services.time_entries WHERE is_billable = TRUE AND is_billed = FALSE GROUP BY lawyer_id HAVING SUM(hours_spent) > 10 ORDER BY total_unbilled_hours DESC;

[User] List all cancelled policies along with any active policy for the same customer. Show cancelled policy number, cancellation_date, and active policy number.

[Assistant] SELECT p_cancel.policy_number AS cancelled_policy_number, p_cancel.cancellation_date, p_active.policy_number AS active_policy_number FROM insurance.policies p_cancel JOIN insurance.policies p_active ON p_cancel.customer_id = p_active.customer_id WHERE p_cancel.status = 'cancelled' AND p_active.status = 'active';

[User] Also restrict to pairs where the active policy started within 30 days after the cancellation date.

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

[User] Show me all transactions along with the related account IDs where the transaction type is 'Transfer'.

[Assistant] SELECT transaction_id, account_id, related_account_id, transaction_type, amount, currency, transaction_date, status FROM financial_services.transactions WHERE transaction_type = 'Transfer';

[User] Further, only include transactions where the currency is 'USD'.

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

[User] Calculate the total amount billed for each client, showing their first name, last name, and the total amount.

[Assistant] SELECT c.first_name, c.last_name, SUM(i.total_amount) FROM legal_services.clients c JOIN legal_services.invoices i ON c.client_id = i.client_id GROUP BY c.client_id, c.first_name, c.last_name;

[User] Show the number of inactive services offered by agencies in each jurisdiction level.

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


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 transportation.drivers ( driver_id text PRIMARY KEY, 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.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 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 legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_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.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 transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
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.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 )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
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 healthcare.doctors ( doctor_id.text, first_name.text, last_name.text, specialty.text, license_number.text, phone_number.text, email.text, hospital_affiliation_id.text, created_at.timestamp, updated_at.timestamp )
##Table Structure
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.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 )

[User] List the first and last names of all drivers with status 'Active' along with the route number and type of all Express routes.

[Assistant]
SELECT d.first_name, d.last_name, r.route_number, r.type
FROM transportation.drivers d
CROSS JOIN transportation.routes r
WHERE d.status = 'Active' AND r.type = 'Express';

[User] Now, only include drivers hired after '2023-01-01'.

[Assistant]
SELECT d.first_name, d.last_name, r.route_number, r.type
FROM transportation.drivers d
CROSS JOIN transportation.routes r
WHERE d.status = 'Active'
  AND r.type = 'Express'
  AND d.hire_date > '2023-01-01';

[User] What is the total balance and the number of accounts for each currency, including only accounts opened in the last 2 years?

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency

[User] Please exclude currencies where the total balance is less than 100000.

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency HAVING SUM(balance)  >=  100000

[User] Can you also include the average interest rate for the remaining currencies, considering only accounts with 'ACTIVE' status?

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count ,  AVG(CASE WHEN status  =  'ACTIVE' THEN interest_rate ELSE NULL END) AS avg_active_interest_rate FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency HAVING SUM(balance)  >=  100000

[User] Find all clients who do not have a company name listed and show their full name and email.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE company_name IS NULL;

[User] Show the full name and job title of employees whose job title includes 'Manager' and who do not have a listed manager.

[Assistant] SELECT first_name, last_name, job_title FROM government_services.employees WHERE job_title LIKE '%Manager%' AND manager_employee_id IS NULL;

[User] Show the average maintenance cost for vehicles of each make, including only vehicles that have had at least one maintenance log.

[Assistant] SELECT v.make, AVG(ml.cost) AS average_maintenance_cost FROM transportation.vehicles AS v JOIN transportation.maintenance_logs AS ml ON v.vehicle_id = ml.vehicle_id GROUP BY v.make ORDER BY average_maintenance_cost DESC;

[User] List all doctors whose last name begins with 'B', showing their doctor ID, full name, and their hospital affiliation ID.

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id FROM healthcare.doctors WHERE last_name LIKE 'B%';

[User] Could you refine the query to only include doctors whose phone_number ends with '99'?

[Assistant] SELECT doctor_id, first_name, last_name, hospital_affiliation_id FROM healthcare.doctors WHERE last_name LIKE 'B%' AND phone_number LIKE '%99';

[User] Which agencies offer services in the 'Social Assistance' category? Show the agency name and the service name.

[Assistant]
SELECT a.agency_name, s.service_name
FROM government_services.services s
JOIN government_services.agencies a ON s.agency_id = a.agency_id
WHERE s.category = 'Social Assistance';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.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 gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)

[User] Calculate the total price for all service orders, grouped by their status.

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

[User] Now, only include the statuses 'Delivered' and 'Completed'.

[Assistant] SELECT status, SUM(total_price) AS total_revenue FROM hospitality_technology.service_orders WHERE status IN ('Delivered', 'Completed') GROUP BY status;

[User] For each achievement, show its name, the game_id it belongs to, and the number of distinct players who have played a session for that game.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id;

[User] Now, filter to only include achievements for games that have at least 50 players who have played a session.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] Please also include the number of times each achievement has been unlocked by unique players, labeled as unique_unlocks.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions,
       (SELECT COUNT(DISTINCT gs2.player_id)
        FROM gaming_technology.game_sessions gs2
        WHERE gs2.game_id = a.game_id) AS unique_unlocks
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] I think unique_unlocks should be the count of distinct players who have unlocked each specific achievement, not just played a session. Can you correct that?

[Assistant] -- With the provided tables, there is no direct record of players unlocking a specific achievement, unless unlocking is inferred elsewhere. If you have an achievement unlocks table, you could join it here. Otherwise, only possible to count sessions per game.

[User] Show all cities in the USA that have more than one distinct location type represented. List the city, country, and number of distinct location types.

[Assistant]
SELECT city, country, COUNT(DISTINCT type) AS distinct_location_types
FROM transportation.locations
WHERE country = 'USA'
GROUP BY city, country
HAVING COUNT(DISTINCT type) > 1;

[User] Show all peers whose last_seen timestamp is before '2023-01-01' and whose port number is less than 1000, listing their peer_id and ip_address.

[Assistant] SELECT peer_id, ip_address FROM trading_platform.peers WHERE last_seen < '2023-01-01' AND port < 1000;

[User] I need the average capacity of vehicles for each fuel_type.

[Assistant]
SELECT fuel_type,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type;

[User] Only include fuel types where the vehicle count is at least 10.

[Assistant]
SELECT fuel_type,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] Also show the number of vehicles for each of these fuel types.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS vehicle_count,
       AVG(capacity) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] Please round avg_capacity to one decimal place.

[Assistant]
SELECT fuel_type,
       COUNT(*) AS vehicle_count,
       ROUND(AVG(capacity)::numeric, 1) AS avg_capacity
FROM transportation.vehicles
GROUP BY fuel_type
HAVING COUNT(*) >= 10;

[User] List all appointments that have a location specified and their status is not 'Cancelled'. Show the appointment ID, subject, and location.

[Assistant] SELECT appointment_id, subject, location FROM legal_services.appointments WHERE location IS NOT NULL AND status <> 'Cancelled';

[User] Also, include appointments that have a case ID assigned. Order the final list by start time ascending.

[Assistant] SELECT appointment_id, subject, location FROM legal_services.appointments WHERE (location IS NOT NULL AND status <> 'Cancelled') OR case_id IS NOT NULL ORDER BY start_time ASC;

[User] Show me the email and full name of passengers who are enrolled in a loyalty program, along with the date they joined, ordered by most recent sign-up.

[Assistant] SELECT email, CONCAT(first_name, ' ', last_name) AS full_name, created_at FROM transportation.passengers WHERE loyalty_program_id IS NOT NULL ORDER BY created_at DESC;