System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- 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 gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
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) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
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 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.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
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 )

[User] List all users whose usernames start with the letter 'B'.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username LIKE 'B%';

[User] Can you make it case-insensitive, so usernames starting with either upper or lower case 'b' are included?

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username ILIKE 'b%';

[User] Instead of showing all details, just display the usernames in alphabetical order.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC;

[User] Limit the result to only the first 3 usernames.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC LIMIT 3;

[User] For each player, list the total number of 'Legendary' rarity items they have in their inventory, along with the titles of the respective games those items belong to.

[Assistant]
SELECT pi.player_id, g.game_id, g.title, COUNT(*) AS legendary_item_count
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'Legendary'
GROUP BY pi.player_id, g.game_id, g.title;

[User] Please modify the query to only include players who have more than 2 'Legendary' items per game.

[Assistant]
SELECT pi.player_id, g.game_id, g.title, COUNT(*) AS legendary_item_count
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'Legendary'
GROUP BY pi.player_id, g.game_id, g.title
HAVING COUNT(*) > 2;

[User] List the accessible service locations and active services offered by the same agency where the service's average processing time is under 5 days. Include the location name, city, state, service name, and processing time.

[Assistant]
SELECT
  sl.location_name,
  sl.city,
  sl.state,
  s.service_name,
  s.average_processing_time_days
FROM
  government_services.service_locations sl
  JOIN government_services.services s
    ON sl.agency_id = s.agency_id
WHERE
  sl.is_accessible = TRUE
  AND s.is_active = TRUE
  AND s.average_processing_time_days < 5;

[User] List all future reservations (where check_in_date > current_date) including guest full name, room_id, property_id, and the number of days until check-in.

[Assistant]
SELECT r.reservation_id, r.property_id, r.room_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       (r.check_in_date - CURRENT_DATE) AS days_until_check_in
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
WHERE r.check_in_date > CURRENT_DATE;

[User] Show the total number of maintenance logs for each vehicle along with the vehicle's make and model.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(m.log_id) AS maintenance_count
FROM transportation.vehicles v
LEFT JOIN transportation.maintenance_logs m ON v.vehicle_id = m.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.documents ( document_id.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 )
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
##Table Structure
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )

[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] For each group chat, list its ID, name, creation time, and the creation time of the next group chat created after it, ordered by creation time.

[Assistant] SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ORDER BY created_at;

[User] Only show pairs where the next group chat was created within 48 hours of the current one, and also include the time difference in hours.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 ORDER BY created_at;

[User] Further refine: Only include group chats whose names contain 'Discuss'.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 AND group_name LIKE '%Discuss%' ORDER BY created_at;

[User] List all locations that serve as either an origin or a destination in any route, including the location name, city, number of routes starting there (origin_count), and number of routes ending there (destination_count).

[Assistant] SELECT l.location_id, l.name, l.city, COALESCE(o.origin_count, 0) AS origin_count, COALESCE(d.dest_count, 0) AS destination_count FROM transportation.locations l LEFT JOIN (SELECT origin_location_id AS location_id, COUNT(*) AS origin_count FROM transportation.routes GROUP BY origin_location_id) o ON l.location_id = o.location_id LEFT JOIN (SELECT destination_location_id AS location_id, COUNT(*) AS dest_count FROM transportation.routes GROUP BY destination_location_id) d ON l.location_id = d.location_id WHERE COALESCE(o.origin_count, 0) > 0 OR COALESCE(d.dest_count, 0) > 0;

[User] Which users have disabled both email and push notifications? Please provide their user IDs and whether their profiles are private.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE;

[User] Also, only include those users who have updated their settings in the last 60 days.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE AND updated_at >= NOW() - INTERVAL '60 days';

[User] Count the total number of medical records where both assessment and treatment_plan fields are provided.

[Assistant]
SELECT COUNT(*) AS total_records
FROM healthcare.medical_records
WHERE assessment IS NOT NULL AND treatment_plan 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.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.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.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, 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 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 )

[User] List the service_id, service_name, and agency_id for all active services that have an online application URL provided.

[Assistant]
SELECT service_id,
       service_name,
       agency_id
FROM government_services.services
WHERE is_active = TRUE
  AND online_application_url IS NOT NULL;

[User] Which customers have accounts in more than one state? Please show their customer_id, full name, and the list of states where they hold accounts.

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, STRING_AGG(DISTINCT c.state, ', ') AS states
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT c.state) > 1;

[User] Can you also include the total number of accounts each customer has?

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, STRING_AGG(DISTINCT c.state, ', ') AS states, COUNT(a.account_id) AS total_accounts
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT c.state) > 1;

[User] It seems like it's listing the customer state info rather than the account's. Can you instead show which states are associated with their accounts' addresses?

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, STRING_AGG(DISTINCT ca.state, ', ') AS account_states, COUNT(a.account_id) AS total_accounts
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.customers ca ON ca.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT ca.state) > 1;

[User] Actually, can you pull the state value from the accounts table instead if possible?

[Assistant]
-- Assuming accounts table has a 'state' field, otherwise this cannot be done directly as accounts does not have state info per schema.
-- If not, we must take it from customers as previously, since only customers has 'state'.

[User] Show me the average interest rate for each account_type.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate
FROM financial_services.accounts
GROUP BY account_type;

[User] Only include account types with at least 5 accounts and order by average_interest_rate ascending.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate, COUNT(*) AS account_count
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] Add the minimum and maximum interest rate for each account_type to the result.

[Assistant]
SELECT account_type, COUNT(*) AS account_count, AVG(interest_rate) AS average_interest_rate,
       MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] Show all applications for citizen 'cit789' that were last updated in March 2024, including their reference_number, status, and last_updated_at.

[Assistant] SELECT reference_number, status, last_updated_at FROM government_services.applications WHERE citizen_id = 'cit789' AND last_updated_at >= '2024-03-01' AND last_updated_at < '2024-04-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.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.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
##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 social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
##Table Structure
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE healthcare.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.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.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 )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Retrieve the product_id, product_name, base_premium, and created_at for all active insurance products with a base_premium greater than 1000, ordered by base_premium descending.

[Assistant]
SELECT
  product_id,
  product_name,
  base_premium,
  created_at
FROM insurance.insurance_products
WHERE is_active = true
  AND base_premium > 1000
ORDER BY base_premium DESC;

[User] Find all pairs of law firms founded in the same year, showing both firm names and the shared founding year.

[Assistant]
SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS founding_year
FROM legal_services.law_firms f1
JOIN legal_services.law_firms f2
  ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date)
  AND f1.firm_id < f2.firm_id;

[User] How many unique customers are there in the system?

[Assistant]
SELECT COUNT(DISTINCT customer_id) AS unique_customer_count
FROM insurance.customers;

[User] Find all distinct pairs of locations that are located in the same city. List their IDs, names, and the shared city.

[Assistant] SELECT l1.location_id AS location1_id, l1.name AS location1_name, l2.location_id AS location2_id, l2.name AS location2_name, l1.city FROM transportation.locations AS l1 JOIN transportation.locations AS l2 ON l1.city = l2.city AND l1.location_id < l2.location_id;

[User] Show the usernames and their profile picture URLs for users who have a profile picture set and are also verified.

[Assistant] SELECT username, profile_picture_url FROM social_media.users WHERE profile_picture_url IS NOT NULL AND profile_picture_url != '' AND is_verified = TRUE;

[User] Calculate the average number of days between when an incident occurred and when the claim was reported, but only for claims that were settled in the year 2023.

[Assistant]
SELECT
  AVG(EXTRACT(EPOCH FROM (reported_date - incident_date)) / 86400.0)::numeric(10, 2)
FROM
  insurance.claims
WHERE
  settlement_date IS NOT NULL AND EXTRACT(YEAR FROM settlement_date) = 2023;

[User] List the first_name, last_name, and registration_date of citizens who registered in 2023 but are still not verified.

[Assistant]
SELECT first_name,
       last_name,
       registration_date
FROM government_services.citizens
WHERE registration_date >= '2023-01-01'
  AND registration_date <  '2024-01-01'
  AND is_verified = FALSE;

[User] For each diagnosis code_type, calculate the average number of refills_allowed for prescriptions linked to chronic diagnoses.

[Assistant]
SELECT
  d.code_type,
  AVG(p.refills_allowed) AS avg_refills_allowed
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p
  ON d.record_id = p.record_id
WHERE d.is_chronic = TRUE
GROUP BY d.code_type;

[User] List the names and contact phone numbers of all insurance plans whose website is not null.

[Assistant]
SELECT plan_name, contact_phone
FROM healthcare.insurance_plans
WHERE 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 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) )
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
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 social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
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.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
Index 'component_inventory'. Mapping: { properties: { inventory_record_id: { type: 'keyword' }, component_id: { type: 'keyword' }, quantity: { type: 'integer' }, location_warehouse: { type: 'keyword' }, location_bin: { type: 'keyword' }, received_date: { type: 'date' }, expiry_date: { type: 'date' }, batch_number: { type: 'keyword' }, last_updated: { type: 'date' } } }. Document _id can be inventory_record_id.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )

[User] Give me a breakdown of available services by unit, with the count of services and the average price, grouped by property.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit;

[User] I only want results where the average price is above 50.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit HAVING AVG(price) > 50;

[User] Actually, also include the department for each unit in the result.

[Assistant] SELECT property_id, unit, department, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit, department HAVING AVG(price) > 50;

[User] For each player, show the total number of achievements they have unlocked and their total game session count.

[Assistant]
SELECT p.player_id, COUNT(pa.achievement_id) AS total_achievements_unlocked, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.player_achievements pa
FULL JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id
RIGHT JOIN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
    UNION
    SELECT DISTINCT player_id FROM gaming_technology.game_sessions
) p ON pa.player_id = p.player_id OR gs.player_id = p.player_id
GROUP BY p.player_id;

[User] Can you modify it to only include players who have unlocked at least 3 achievements and played at least 2 sessions?

[Assistant]
SELECT p.player_id, COUNT(pa.achievement_id) AS total_achievements_unlocked, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.player_achievements pa
FULL JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id
RIGHT JOIN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
    UNION
    SELECT DISTINCT player_id FROM gaming_technology.game_sessions
) p ON pa.player_id = p.player_id OR gs.player_id = p.player_id
GROUP BY p.player_id
HAVING COUNT(pa.achievement_id) >= 3 AND COUNT(gs.session_id) >= 2;

[User] How many unique conversations have messages?

[Assistant] SELECT COUNT(DISTINCT conversation_id) FROM social_media.messages;

[User] 特定のコンポーネントの在庫情報を取得したいです。コンポーネントIDと在庫数量、倉庫の場所を含めてください。

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id';

[User] さらに、受け取り日が2022年以降の記録だけを表示するようにできますか？

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id' AND received_date >= '2022-01-01';

[User] 在庫数量が100未満のものだけに絞り込むことは可能ですか？

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id' AND received_date >= '2022-01-01' AND quantity < 100;

[User] 最後に、受け取り日を新しい順に並べ替えてください。

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id' AND received_date >= '2022-01-01' AND quantity < 100 ORDER BY received_date DESC;

[User] What is the average balance for each account_type among accounts with status 'Open'?

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type;

[User] Exclude account types with fewer than 3 accounts.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3;

[User] Sort the results by average balance descending.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3 ORDER BY avg_balance DESC;

[User] Show me the type name, base rate, and description for all room types together with the property ID, but only for rooms with an area greater than 400 square feet.

[Assistant] SELECT room_type_id, property_id, type_name, base_rate, description FROM hospitality_technology.room_types WHERE area_sqft > 400;

[User] Now, only include those with a maximum occupancy of at least 3 people and order them by base rate descending.

[Assistant] SELECT room_type_id, property_id, type_name, base_rate, description FROM hospitality_technology.room_types WHERE area_sqft > 400 AND max_occupancy >= 3 ORDER BY base_rate DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)
##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.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
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 )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed int, prescription_date timestamp )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
##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.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )

[User] Find all doctors who have a hospital affiliation and include their full names (concatenated), specialties, and affiliation IDs.

[Assistant] SELECT CONCAT(first_name, ' ', last_name) AS full_name, specialty, hospital_affiliation_id FROM healthcare.doctors WHERE hospital_affiliation_id IS NOT NULL;

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

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

[User] List all events and any token transfers that occurred in the same transaction, showing event_id, event_name, transfer_id, and token_symbol.

[Assistant]
SELECT
  e.event_id,
  e.event_name,
  tt.transfer_id,
  tk.token_symbol
FROM web3.events e
LEFT JOIN web3.token_transfers tt
  ON e.transaction_id = tt.transaction_id
LEFT JOIN web3.tokens tk
  ON tt.token_id = tk.token_id
ORDER BY e.transaction_id, e.log_index;

[User] List all achievements with their name, points, and the title of the game they belong to.

[Assistant] SELECT a.name AS achievement_name, a.points, g.title AS game_title FROM gaming_technology.achievements a JOIN games g ON a.game_id = g.game_id;

[User] Filter this list to only show achievements with more than 50 points.

[Assistant] SELECT a.name AS achievement_name, a.points, g.title AS game_title FROM gaming_technology.achievements a JOIN games g ON a.game_id = g.game_id WHERE a.points > 50;

[User] List all distinct medication IDs that have been prescribed with more than 5 refills allowed.

[Assistant] SELECT DISTINCT medication_id FROM healthcare.prescriptions WHERE refills_allowed > 5;

[User] Find all users who have at least two wallets with different private keys. Show user_id and the count of distinct private keys for those users.

[Assistant]
SELECT user_id, COUNT(DISTINCT private_key) AS distinct_private_key_count
FROM web3.wallets
GROUP BY user_id
HAVING COUNT(DISTINCT private_key) >= 2;

[User] List the transaction IDs which have had more than one unique event emitted inside them.

[Assistant] SELECT transaction_id FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Actually, can you also list the names of these unique events for each transaction ID?

[Assistant] SELECT transaction_id, STRING_AGG(DISTINCT event_name, ', ') AS unique_event_names FROM web3.events GROUP BY transaction_id HAVING COUNT(DISTINCT event_name) > 1;

[User] Count how many diagnoses entries are currently marked as 'Resolved'.

[Assistant] SELECT COUNT(*) FROM healthcare.diagnoses WHERE status = 'Resolved';

[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.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 WHERE c.network_id = 'ethereum' GROUP BY c.address, c.deployer_address ORDER BY transaction_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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, 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.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)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, 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 gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
##Table Structure
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 )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.text, asset_id.text, key.text, value.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )

[User] For each passenger, show their passenger_id, first_name, last_name, the date and time of their earliest booking, and the date and time of their latest booking.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       MIN(b.booking_time) AS earliest_booking_time,
       MAX(b.booking_time) AS latest_booking_time
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name;

[User] Show each pair of passengers who share the same loyalty_program_id but have different registration times. Return p1.first_name AS earlier, p2.first_name AS later, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Actually, only include pairs where the earlier registration happened before '2023-01-01'.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.created_at < '2023-01-01';

[User] Could you list all pairs of developers in the same country but different companies? Return developer1, developer2, and country.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id;

[User] Now restrict pairs to only those in country 'USA' or 'Canada'.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada');

[User] Sort the pairs by developer1 name ascending.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada')
ORDER BY d1.name ASC;

[User] List all insurance products along with their type and base premium. Also, show whether each product is active.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products;

[User] Can you filter the results to only show insurance products of type 'auto'?

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products WHERE product_type = 'auto';

[User] Also, sort these results by the base premium in ascending order.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products WHERE product_type = 'auto' ORDER BY base_premium ASC;

[User] Show me the usernames of users who have bought or sold assets classified as 'token', along with the name and symbol of the asset they traded.

[Assistant] SELECT DISTINCT T1.username, T3.name, T3.symbol FROM users AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id JOIN assets AS T3 ON T2.asset_id = T3.asset_id WHERE T3.type = 'token';

[User] Instead of listing, count how many unique 'token' assets each user has traded. Show the username and the count, ordered by count descending.

[Assistant] SELECT T1.username, COUNT(DISTINCT T2.asset_id) FROM users AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id JOIN assets AS T3 ON T2.asset_id = T3.asset_id WHERE T3.type = 'token' GROUP BY 1 ORDER BY 2 DESC;

[User] Which drivers have licenses expiring before 2025-01-01, and what are their first and last names along with the license expiry date?

[Assistant] SELECT driver_id, first_name, last_name, license_expiry_date FROM transportation.drivers WHERE license_expiry_date < '2025-01-01';

[User] From this list, only include drivers whose status is 'Active'.

[Assistant] SELECT driver_id, first_name, last_name, license_expiry_date FROM transportation.drivers WHERE license_expiry_date < '2025-01-01' AND status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.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.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) )
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 )
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
##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 )
##Table Structure
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 )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )

[User] Which claims have at least one document uploaded by an agent located in 'NY'? Show the claim_id, document_type, file_name, uploaded_by, and the agent's first and last name.

[Assistant]
SELECT cd.claim_id, cd.document_type, cd.file_name, cd.uploaded_by, a.first_name, a.last_name
FROM insurance.claim_documents cd
JOIN insurance.agents a ON cd.uploaded_by = a.agent_id
WHERE a.license_state = 'NY';

[User] Show me all active staff including their staff_id, first_name, last_name, position, and work_email.

[Assistant]
SELECT staff_id,
       first_name,
       last_name,
       position,
       work_email
FROM hospitality_technology.staff
WHERE is_active = true;

[User] Actually, I need the results sorted by hire_date descending.

[Assistant]
SELECT staff_id,
       first_name,
       last_name,
       position,
       work_email
FROM hospitality_technology.staff
WHERE is_active = true
ORDER BY hire_date DESC;

[User] List all developer names and their countries.

[Assistant] SELECT name, country FROM gaming_technology.developers;

[User] Filter the list to only include developers from countries that start with 'U'.

[Assistant] SELECT name, country FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] For these developers from countries starting with 'U', what are the minimum and maximum founded years?

[Assistant] SELECT MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] Also, include the average founded year and the total count of developers in this filtered group.

[Assistant] SELECT COUNT(*), AVG(founded_year), MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] For each document (identified by case_id and document_name), find the latest version number and the ID of the lawyer who uploaded that version.

[Assistant] WITH RankedDocuments AS ( SELECT document_id, case_id, document_name, uploaded_by_lawyer_id, version, ROW_NUMBER() OVER(PARTITION BY case_id, document_name ORDER BY version DESC) as rn FROM legal_services.documents ) SELECT case_id, document_name, version AS latest_version, uploaded_by_lawyer_id AS latest_version_lawyer_id FROM RankedDocuments WHERE rn = 1;

[User] Now, filter these results to only show documents where the very first version (version 1) was uploaded by a different lawyer than the latest version you just listed.

[Assistant] SELECT vi_first.case_id, vi_first.document_name, vi_first.uploaded_by_lawyer_id AS first_version_lawyer_id, vi_latest.uploaded_by_lawyer_id AS latest_version_lawyer_id FROM legal_services.documents vi_first JOIN legal_services.documents vi_latest ON vi_first.case_id = vi_latest.case_id AND vi_first.document_name = vi_latest.document_name JOIN ( SELECT case_id, document_name, MIN(version) AS min_v, MAX(version) AS max_v FROM legal_services.documents GROUP BY case_id, document_name ) AS versions ON vi_first.case_id = versions.case_id AND vi_first.document_name = versions.document_name AND vi_first.version = versions.min_v AND vi_latest.version = versions.max_v WHERE vi_first.uploaded_by_lawyer_id <> vi_latest.uploaded_by_lawyer_id;

[User] Could you also include the upload timestamps for both the first version and the latest version for these documents?

[Assistant] SELECT vi_first.case_id, vi_first.document_name, vi_first.uploaded_by_lawyer_id AS first_version_lawyer_id, vi_first.upload_timestamp AS first_version_timestamp, vi_latest.uploaded_by_lawyer_id AS latest_version_lawyer_id, vi_latest.upload_timestamp AS latest_version_timestamp FROM legal_services.documents vi_first JOIN legal_services.documents vi_latest ON vi_first.case_id = vi_latest.case_id AND vi_first.document_name = vi_latest.document_name JOIN ( SELECT case_id, document_name, MIN(version) AS min_v, MAX(version) AS max_v FROM legal_services.documents GROUP BY case_id, document_name ) AS versions ON vi_first.case_id = versions.case_id AND vi_first.document_name = versions.document_name AND vi_first.version = versions.min_v AND vi_latest.version = versions.max_v WHERE vi_first.uploaded_by_lawyer_id <> vi_latest.uploaded_by_lawyer_id;

[User] List all locations located in the state of 'Florida'.

[Assistant] SELECT * FROM transportation.locations WHERE state_province = 'Florida';

[User] Can you only show locations of type 'Airport' or 'Hangar'?

[Assistant] SELECT * FROM transportation.locations WHERE state_province = 'Florida' AND type IN ('Airport', 'Hangar');

[User] Also, include their latitude and longitude and sort the results by city.

[Assistant] SELECT location_id, name, type, city, latitude, longitude FROM transportation.locations WHERE state_province = 'Florida' AND type IN ('Airport', 'Hangar') ORDER BY city;

[User] Actually, I only want locations in the city of 'Orlando'. Can you filter by city instead of state?

[Assistant] SELECT location_id, name, type, city, latitude, longitude FROM transportation.locations WHERE city = 'Orlando' AND type IN ('Airport', 'Hangar') ORDER BY city;

[User] List all UTXOs with amount greater than 100 and also include the address and transaction_id.

[Assistant]
SELECT utxo_id, address, transaction_id, amount
FROM trading_platform.utxos
WHERE amount > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
##Table Structure
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )

[User] How many trips used more than 500 units of fuel, and what are their trip IDs and scheduled departure times?

[Assistant]
SELECT t.trip_id, t.scheduled_departure, SUM(f.quantity) AS total_fuel
FROM transportation.trips t
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, t.scheduled_departure
HAVING SUM(f.quantity) > 500;

[User] Change the query to show the route number for these trips as well.

[Assistant]
SELECT t.trip_id, t.scheduled_departure, r.route_number, SUM(f.quantity) AS total_fuel
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, t.scheduled_departure, r.route_number
HAVING SUM(f.quantity) > 500;

[User] Show me all services grouped by category, including the minimum and maximum price in each category, and the total number of services.

[Assistant] SELECT category, MIN(price) AS min_price, MAX(price) AS max_price, COUNT(*) AS service_count FROM hospitality_technology.services GROUP BY category;

[User] Please only include categories with more than 3 services.

[Assistant] SELECT category, MIN(price) AS min_price, MAX(price) AS max_price, COUNT(*) AS service_count FROM hospitality_technology.services GROUP BY category HAVING COUNT(*) > 3;

[User] Actually, sort the results by service_count descending and show the category first.

[Assistant] SELECT category, COUNT(*) AS service_count, MIN(price) AS min_price, MAX(price) AS max_price FROM hospitality_technology.services GROUP BY category HAVING COUNT(*) > 3 ORDER BY service_count DESC;

[User] Show me the total invoice amount and the number of invoices for each client in 2024, and include the earliest and latest invoice issue date for each client.

[Assistant]
SELECT client_id, SUM(total_amount) AS total_invoice_amount, COUNT(*) AS invoice_count, MIN(issue_date) AS earliest_issue_date, MAX(issue_date) AS latest_issue_date
FROM legal_services.invoices
WHERE EXTRACT(YEAR FROM issue_date) = 2024
GROUP BY client_id;

[User] List all pairs of users who participated in the same conversation. For each, show conversation_id, user_id1, user_id2.

[Assistant]
SELECT p1.conversation_id,
       p1.user_id AS user_id1,
       p2.user_id AS user_id2
FROM social_media.conversation_participants p1
JOIN social_media.conversation_participants p2
  ON p1.conversation_id = p2.conversation_id
WHERE p1.user_id < p2.user_id;

[User] Only include pairs where both joined after '2024-06-01'.

[Assistant]
SELECT p1.conversation_id,
       p1.user_id AS user_id1,
       p2.user_id AS user_id2
FROM social_media.conversation_participants p1
JOIN social_media.conversation_participants p2
  ON p1.conversation_id = p2.conversation_id
WHERE p1.user_id < p2.user_id
  AND p1.joined_at > '2024-06-01'
  AND p2.joined_at > '2024-06-01';

[User] List all pairs of diagnoses that belong to the same medical record. Show record_id, diagnosis_id from the first entry as diag1_id, and diagnosis_id from the second entry as diag2_id.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id;

[User] Only include pairs where both diagnoses are chronic.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = TRUE;

[User] What is the highest score achieved in any session for each player on each game?

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id;

[User] Show only the player/game combinations where the highest score is at least 500.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;

[User] Also include the number of sessions for each player/game pair.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
##Table Structure
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
##Table Structure
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 )

[User] Which project had the largest single fundraising in each investment round, along with the round's name and introduction?

[Assistant] SELECT t1.project_name, t1.rounds_name, t1.investment_value, t1.introduction FROM project_fundraising_record t1 INNER JOIN (SELECT rounds_name, MAX(investment_value) AS max_value FROM project_fundraising_record GROUP BY rounds_name) t2 ON t1.rounds_name = t2.rounds_name AND t1.investment_value = t2.max_value;

[User] Instead of just one, can you show the top two fundraisings in each round?

[Assistant] SELECT project_name, rounds_name, investment_value, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Can you add the valuation for each project in the output as well?

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Show me only those top two projects per round where the valuation is greater than 100 million.

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2 AND valuation > 100000000;

[User] Which staff members are managing properties, and what are the names and email addresses of those properties?

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, p.property_name, p.email_address FROM hospitality_technology.staff s INNER JOIN hospitality_technology.properties p ON s.staff_id = p.manager_staff_id;

[User] Only include properties located in the United States and list the staff position as well.

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, s.position, p.property_name, p.email_address FROM hospitality_technology.staff s INNER JOIN hospitality_technology.properties p ON s.staff_id = p.manager_staff_id WHERE p.country_code = 'US';

[User] How many prescriptions have been issued per patient?

[Assistant]
SELECT patient_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY patient_id;

[User] Only show patients who have more than 5 prescriptions.

[Assistant]
SELECT patient_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY patient_id
HAVING COUNT(*) > 5;

[User] List the number of appointments for each booking method.

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

[User] Filter this to only include booking methods that have more than 50 appointments.

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

[User] Also only consider appointments that are scheduled in the state of 'Texas'.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE sl.state = 'Texas'
GROUP BY a.booking_method
HAVING COUNT(*) > 50;

[User] Now show the results ordered by appointment_count descending and limit to top 3 methods.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE sl.state = 'Texas'
GROUP BY a.booking_method
HAVING COUNT(*) > 50
ORDER BY appointment_count DESC
LIMIT 3;

[User] What is the total balance for each currency in the accounts table?

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

[User] Can you also show the number of accounts for each currency?

[Assistant] SELECT currency, COUNT(account_id) AS number_of_accounts, SUM(balance) AS total_balance FROM financial_services.accounts GROUP BY currency;

[User] Only include accounts with status 'ACTIVE' in the calculation.

[Assistant] SELECT currency, COUNT(account_id) AS number_of_accounts, SUM(balance) AS total_balance FROM financial_services.accounts WHERE status = 'ACTIVE' GROUP BY currency;

[User] Show me the name and type for all the locations.

[Assistant] SELECT name, type FROM transportation.locations

[User] Now, filter this list to only include locations whose type is either 'Distribution Center' or 'Warehouse'.

[Assistant] SELECT name, type FROM transportation.locations WHERE type IN ('Distribution Center', 'Warehouse')


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;