[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff

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
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Node Label: :Route
// Properties:
//   route_id: String (Constraint: UNIQUE)
//   route_name: String
//   description: String
//   is_active: Boolean
// Relationships:
//   (:Route)-[:STARTS_AT]->(:Station)
//   (:Route)-[:ENDS_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (origin:Station {station_id: 'station_bos'}), (dest:Station {station_id: 'station_was'})
// CREATE (r:Route {route_id: 'route_ne_corr', ...})-[:STARTS_AT]->(origin), (r)-[:ENDS_AT]->(dest)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :ScheduledTrip (or just :Trip)
// Properties:
//   schedule_id: String (Constraint: UNIQUE)
//   departure_datetime: DateTime
//   arrival_datetime: DateTime
//   status: String
//   notes: String
// Relationships:
//   (:ScheduledTrip)-[:USES_TRAIN]->(:Train)
//   (:ScheduledTrip)-[:FOLLOWS_ROUTE]->(:Route)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'}), (r:Route {route_id: 'route_ne_corr'})
// CREATE (sched:ScheduledTrip {schedule_id: 'sched_1122', ...})-[:USES_TRAIN]->(t), (sched)-[:FOLLOWS_ROUTE]->(r)
// Relationship: (:ScheduledTrip)-[rel:SCHEDULED_STOP]->(:Station)
// Relationship Properties on :SCHEDULED_STOP:
//   sequence_order: Integer
//   platform_id: String (references Platform node if modeled, or just store ID)
//   scheduled_arrival_time: DateTime
//   scheduled_departure_time: DateTime
//   actual_arrival_time: DateTime
//   actual_departure_time: DateTime
//   status: String
// Example Cypher CREATE:
// MATCH (sched:ScheduledTrip {schedule_id: 'sched_1122'}), (s:Station {station_id: 'station_pvd'})
// CREATE (sched)-[:SCHEDULED_STOP {sequence_order: 2, platform_id: 'plat_pvd_1', ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Ticket
// Properties:
//   ticket_id: String (Constraint: UNIQUE)
//   seat_number: String
//   ticket_type: String
//   price: Float
//   is_checked_in: Boolean
//   qr_code_data: String
// Relationships:
//   (:Ticket)-[:PART_OF_BOOKING]->(:Booking)
//   (:Ticket)-[:ASSIGNED_TO_CAR]->(:TrainCar)
// Example Cypher CREATE:
// MATCH (b:Booking {booking_id: 'book_zyx'}), (c:TrainCar {car_id: 'car_abc'})
// CREATE (t:Ticket {ticket_id: 'tkt_1a2b', ...})-[:PART_OF_BOOKING]->(b), (t)-[:ASSIGNED_TO_CAR]->(c)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)


[User] What is the current market price of a Boeing 737 MAX aircraft?

[Assistant] I'm sorry, but I don't have access to the current market price of aircraft models. The data I have is limited to technical specifications and general information about aircraft models such as passenger capacity, range, and status. For pricing information, you may need to consult with manufacturers or industry reports.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models (
    model_id character varying(64) NOT NULL,  -- unique identifier for the aircraft model
    model_name character varying(128) NOT NULL, -- commercial name of the model (e.g., 737 MAX, A320neo)
    manufacturer character varying(128) NOT NULL, -- manufacturer name (e.g., Boeing, Airbus)
    passenger_capacity integer, -- typical passenger capacity
    max_range_km integer, -- maximum flight range in kilometers
    engine_type character varying(100), -- type of engines used
    wingspan_m numeric(6,2), -- wingspan in meters
    status character varying(50) NOT NULL, -- e.g., 'In Production', 'Development', 'Discontinued'
    first_flight_date date, -- date of the model's first flight
    PRIMARY KEY (model_id)
)


[User] Find pairs of customers who share the same last name and live in the same city. List the two customer IDs as customer1_id, customer2_id, their first names as first_name1, first_name2, and city.

[Assistant]
SELECT c1.customer_id AS customer1_id,
       c2.customer_id AS customer2_id,
       c1.first_name AS first_name1,
       c2.first_name AS first_name2,
       c1.city
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.last_name = c2.last_name
 AND c1.city = c2.city
 AND c1.customer_id < c2.customer_id;

[User] Only include customers who are currently active.

[Assistant]
SELECT c1.customer_id AS customer1_id,
       c2.customer_id AS customer2_id,
       c1.first_name AS first_name1,
       c2.first_name AS first_name2,
       c1.city
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.last_name = c2.last_name
 AND c1.city = c2.city
 AND c1.customer_id < c2.customer_id
WHERE c1.status = 'active'
  AND c2.status = 'active';

[User] Also include their email addresses and sort the results by city ascending and then by first_name1.

[Assistant]
SELECT c1.customer_id AS customer1_id,
       c2.customer_id AS customer2_id,
       c1.first_name AS first_name1,
       c2.first_name AS first_name2,
       c1.city,
       c1.email AS email1,
       c2.email AS email2
FROM insurance.customers c1
JOIN insurance.customers c2
  ON c1.last_name = c2.last_name
 AND c1.city = c2.city
 AND c1.customer_id < c2.customer_id
WHERE c1.status = 'active'
  AND c2.status = 'active'
ORDER BY c1.city ASC, c1.first_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )


[User] List all DApps that have 'wallet' in their description, along with their URLs.

[Assistant] SELECT name, url FROM trading_platform.dapps WHERE description LIKE '%wallet%';

[User] Now show only DApps created in the last year, and include their creation date.

[Assistant] SELECT name, url, created_at FROM trading_platform.dapps WHERE description LIKE '%wallet%' AND created_at >= NOW() - INTERVAL '1 year';

[User] Actually, I want to see the count of such DApps grouped by month of creation.

[Assistant] SELECT DATE_TRUNC('month', created_at) AS month, COUNT(*) AS dapp_count FROM trading_platform.dapps WHERE description LIKE '%wallet%' AND created_at >= NOW() - INTERVAL '1 year' GROUP BY month ORDER BY month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )


[User] Find the average time it takes for users to read notifications after they are sent.

[Assistant] SELECT AVG(EXTRACT(EPOCH FROM (read_at - sent_at))/3600) as avg_hours_to_read FROM trading_platform.notifications WHERE read_at IS NOT NULL;

[User] Now show me this average broken down by day of the week when the notification was sent.

[Assistant] SELECT EXTRACT(DOW FROM sent_at) as day_of_week, AVG(EXTRACT(EPOCH FROM (read_at - sent_at))/3600) as avg_hours_to_read FROM trading_platform.notifications WHERE read_at IS NOT NULL GROUP BY day_of_week ORDER BY day_of_week;

[User] Can you modify the query to show the day names (Monday-Sunday) instead of numbers?

[Assistant] SELECT CASE EXTRACT(DOW FROM sent_at) WHEN 0 THEN 'Sunday' WHEN 1 THEN 'Monday' WHEN 2 THEN 'Tuesday' WHEN 3 THEN 'Wednesday' WHEN 4 THEN 'Thursday' WHEN 5 THEN 'Friday' WHEN 6 THEN 'Saturday' END as day_of_week, AVG(EXTRACT(EPOCH FROM (read_at - sent_at))/3600) as avg_hours_to_read FROM trading_platform.notifications WHERE read_at IS NOT NULL GROUP BY day_of_week ORDER BY EXTRACT(DOW FROM sent_at);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] Provide the count of diagnoses by status.

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

[User] Now only include statuses with more than 10 diagnoses.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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)
)


[User] Could you list each game title along with its developer's name and the total number of servers hosting it?

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
LEFT JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title, d.name;

[User] Actually, please include only servers with status = 'online' and exclude games with zero online servers.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.status = 'online'
GROUP BY g.title, d.name;

[User] I want to see only developers based in 'USA'.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id AND s.status = 'online'
WHERE d.country = 'USA'
GROUP BY g.title, d.name;

[User] Finally, sort the results by server_count in descending order.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id AND s.status = 'online'
WHERE d.country = 'USA'
GROUP BY g.title, d.name
ORDER BY server_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
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 timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )
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 )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )


[User] For each player, can you find the username and registration_date of the player who registered immediately before them in the same country?

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
LEFT JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    );

[User] Actually, I'd like to exclude players who don't have a previous registrant, so only show rows where prev_username is not null.

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    );

[User] I'd like the final result ordered by country_code and then by the player's registration_date.

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    )
ORDER BY p.country_code, p.registration_date;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )


[User] List all invoices that were paid within 7 days of their issue date. Show invoice number, issue date, payment date, and total amount.

[Assistant] SELECT invoice_number, issue_date, payment_date, total_amount FROM legal_services.invoices WHERE status = 'Paid' AND payment_date IS NOT NULL AND (payment_date::DATE - issue_date) <= 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )


[User] What is the ticket price for a journey on train number T4321?

[Assistant] I'm sorry, but I don't have access to information about ticket prices for specific trains. The data I have is limited to train details such as model, manufacturer, capacity, and maintenance schedules. For ticket pricing, please consult the ticketing office or the official website.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id text PRIMARY KEY, train_number text UNIQUE, model text, manufacturer text, year_manufactured int, capacity int, status text, last_maintenance_date date, next_maintenance_date date )


[User] Calculate the average market cap and average 24-hour trading volume for tokens belonging to each narrative category.

[Assistant] SELECT narrative, AVG(market_cap) AS average_market_cap, AVG(CAST(REPLACE(total_volume, ',', '') AS NUMERIC)) AS average_24h_volume FROM token_basic_info WHERE narrative IS NOT NULL AND total_volume IS NOT NULL GROUP BY narrative;

[User] Filter the results to only include narratives where the average market cap is greater than $1,000,000,000.

[Assistant] SELECT narrative, AVG(market_cap) AS average_market_cap, AVG(CAST(REPLACE(total_volume, ',', '') AS NUMERIC)) AS average_24h_volume FROM token_basic_info WHERE narrative IS NOT NULL AND total_volume IS NOT NULL GROUP BY narrative HAVING AVG(market_cap) > 1000000000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )


[User] List all the appointments that overlap in time for the same location, showing both appointment IDs, their start and end times, and the location.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2,
       a1.start_time AS start_1, a1.end_time AS end_1,
       a2.start_time AS start_2, a2.end_time AS end_2,
       a1.location
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.location = a2.location
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time;

[User] Can you narrow this to only show overlapping appointments that are both in 'Scheduled' status?

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2,
       a1.start_time AS start_1, a1.end_time AS end_1,
       a2.start_time AS start_2, a2.end_time AS end_2,
       a1.location
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.location = a2.location
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
WHERE a1.status = 'Scheduled' AND a2.status = 'Scheduled';

[User] Also, please only show overlaps that last longer than 10 minutes.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2,
       a1.start_time AS start_1, a1.end_time AS end_1,
       a2.start_time AS start_2, a2.end_time AS end_2,
       a1.location
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.location = a2.location
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
WHERE a1.status = 'Scheduled' AND a2.status = 'Scheduled'
  AND EXTRACT(EPOCH FROM (LEAST(a1.end_time, a2.end_time) - GREATEST(a1.start_time, a2.start_time))) > 600;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )


[User] List the names of citizens who have submitted applications for services with a standard fee greater than 50.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.citizens AS T1 JOIN government_services.applications AS T2 ON T1.citizen_id = T2.citizen_id JOIN government_services.services AS T3 ON T2.service_id = T3.service_id WHERE T3.standard_fee > 50;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, 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 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.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 )


[User] Find all patients who have been prescribed medications with dosage greater than 50mg, along with their medication details and prescribing doctor's name.

[Assistant] SELECT p.patient_id, p.first_name, p.last_name, pr.dosage, pr.medication_id, pr.start_date, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.doctors doc ON pr.doctor_id = doc.doctor_id WHERE CAST(SUBSTRING_INDEX(pr.dosage, 'mg', 1) AS UNSIGNED) > 50;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.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.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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 )


[User] List the first name, last name, and hire date of all lawyers who are partners.

[Assistant] SELECT first_name ,  last_name ,  hire_date FROM legal_services.lawyers WHERE is_partner  =  TRUE

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)


[User] List all insurance products that have 'auto' in their product type and are currently active, showing their product name and base premium.

[Assistant] SELECT product_name, base_premium FROM insurance.insurance_products WHERE product_type LIKE '%auto%' AND is_active = true;

[User] Now order these results by base premium in descending order and include the coverage details.

[Assistant] SELECT product_name, base_premium, coverage_details FROM insurance.insurance_products WHERE product_type LIKE '%auto%' AND is_active = true ORDER BY base_premium DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] List the appointment ID, start time, and the case number for all appointments that are linked to a case.

[Assistant] SELECT T1.appointment_id, T1.start_time, T2.case_number FROM legal_services.appointments AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id

[User] Refine this to only show appointments with status 'completed' associated with cases with status 'Closed'.

[Assistant] SELECT T1.appointment_id, T1.start_time, T2.case_number FROM legal_services.appointments AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'completed' AND T2.status = 'Closed'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )


[User] Find all pairs of distinct routes that share the same origin location ID. List the route IDs and route numbers for both routes in each pair, along with the shared origin location ID.

[Assistant] SELECT r1.route_id AS route1_id, r1.route_number AS route1_number, r2.route_id AS route2_id, r2.route_number AS route2_number, r1.origin_location_id FROM transportation.routes AS r1 JOIN transportation.routes AS r2 ON r1.origin_location_id = r2.origin_location_id WHERE r1.route_id < r2.route_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )


[User] For each claim handler, count the number of documents uploaded for the claims they handled. Return claim_handler_id and document_count.

[Assistant]
SELECT c.claim_handler_id,
       COUNT(d.document_id) AS document_count
FROM insurance.claims AS c
JOIN insurance.claim_documents AS d
  ON c.claim_id = d.claim_id
GROUP BY c.claim_handler_id;

[User] Now restrict to handlers who have uploaded more than 10 documents.

[Assistant]
SELECT c.claim_handler_id,
       COUNT(d.document_id) AS document_count
FROM insurance.claims AS c
JOIN insurance.claim_documents AS d
  ON c.claim_id = d.claim_id
GROUP BY c.claim_handler_id
HAVING COUNT(d.document_id) > 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_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 )


[User] List all NFT collections from the sui_nfts table where the owner is not null, including their name and collection_type.

[Assistant] SELECT name, collection_type FROM sui_nfts WHERE owner IS NOT NULL;

[User] Can you also include the display field and filter to only show collections with a package_id starting with '0x'?

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%';

[User] Now sort these results by name in ascending order.

[Assistant] SELECT name, collection_type, display FROM sui_nfts WHERE owner IS NOT NULL AND package_id LIKE '0x%' ORDER BY name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_info_bitcoin (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(255) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)


[User] Can you list the number of citizens registered each month in 2024? Please show the month and the citizen count.

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] Now, can you also show the number of verified citizens for each month?

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] I see some months with zero verified citizens, but they still show up. Can you exclude months with zero verified citizens from the result?

[Assistant] SELECT registration_month, citizen_count, verified_citizen_count FROM (SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month) sub WHERE verified_citizen_count > 0 ORDER BY registration_month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )


[User] Find the total number of documents uploaded by each citizen along with their first and last names.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(d.document_id) AS document_count
FROM government_services.citizens c
LEFT JOIN government_services.documents d ON c.citizen_id = d.citizen_id
GROUP BY c.citizen_id, c.first_name, c.last_name;

[User] Actually, I only want to include those citizens who have uploaded documents in the last 30 days.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(d.document_id) AS document_count
FROM government_services.citizens c
JOIN government_services.documents d ON c.citizen_id = d.citizen_id
WHERE d.upload_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY c.citizen_id, c.first_name, c.last_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
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) )


[User] For each citizen who has made at least one payment, show the citizen's full name, number of payments, and total amount paid, grouped by currency.

[Assistant]
SELECT
  c.first_name || ' ' || c.last_name AS full_name,
  p.currency,
  COUNT(*) AS payment_count,
  SUM(p.amount) AS total_amount
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
GROUP BY full_name, p.currency;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, 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) )
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) )


[User] Find all nodes that were last seen in the last 30 days and have port numbers between 8000 and 9000.

[Assistant] SELECT node_id, ip_address, port FROM blockchain.nodes WHERE last_seen >= NOW() - INTERVAL '30 days' AND port BETWEEN 8000 AND 9000

[User] Can you also show the count of transactions sent from wallet addresses that share the same IP as these nodes?

[Assistant] This query isn't possible with the current schema as there's no relationship between nodes IP addresses and wallet addresses.

[User] Then just show me nodes that share the same IP address along with how many nodes share each IP.

[Assistant] SELECT ip_address, COUNT(*) as node_count FROM blockchain.nodes GROUP BY ip_address HAVING COUNT(*) > 1

[User] Now filter this to only show IP addresses with more than 3 nodes and include the earliest and latest last_seen timestamps.

[Assistant] SELECT ip_address, COUNT(*) as node_count, MIN(last_seen) as earliest_seen, MAX(last_seen) as latest_seen FROM blockchain.nodes GROUP BY ip_address HAVING COUNT(*) > 3

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.nodes ( node_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )
CREATE TABLE blockchain.smart_contracts ( contract_id text, creator_address text, code text, timestamp timestamp )


[User] For each user, show their user ID and the count of unique wallet addresses they own.

[Assistant] SELECT user_id, COUNT(DISTINCT address) FROM wallets GROUP BY user_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )


[User] List the appointment ID, subject, and duration in minutes for all completed appointments.

[Assistant] SELECT appointment_id, subject, EXTRACT(EPOCH FROM (end_time - start_time))/60 AS duration_minutes FROM legal_services.appointments WHERE status = 'Completed';


[User] Retrieve the agency name and the most recent notification sent date for each agency, considering only notifications related to agencies.

[Assistant]
SELECT a.agency_name, MAX(n.sent_at) AS last_notification_date
FROM government_services.agencies a
JOIN government_services.notifications n
  ON n.related_entity_type = 'Agency'
  AND n.related_entity_id = a.agency_id
GROUP BY a.agency_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)


[User] List all staff members who have responded to at least one review in the last 6 months, including their first and last names and the count of responses.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, COUNT(r.review_id) AS response_count
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Actually, only include responses to public reviews.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, COUNT(r.review_id) AS response_count
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
  AND r.is_public = TRUE
GROUP BY s.staff_id, s.first_name, s.last_name;

[User] Also include the average response time in days for each staff member.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name,
       COUNT(r.review_id) AS response_count,
       AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 86400) AS avg_response_days
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.staff AS s
  ON r.response_staff_id = s.staff_id
WHERE r.response_date >= CURRENT_DATE - INTERVAL '6 months'
  AND r.is_public = TRUE
GROUP BY s.staff_id, s.first_name, s.last_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
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.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, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] List all securities (security_id, ticker_symbol, security_name) that are traded on the NASDAQ exchange and have a daily trading volume exceeding 1 million shares, along with the employee details (employee_id, first_name, last_name) who last updated these securities.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, e.employee_id, e.first_name, e.last_name FROM financial_services.securities s JOIN financial_services.employees e ON s.last_updated = e.hire_date WHERE s.exchange = 'NASDAQ' AND s.security_id IN (SELECT security_id FROM financial_services.market_data WHERE volume > 1000000);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id text, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id text, 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 )


[User] Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens where the price is greater than $0.10.

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply FROM token_metas tm WHERE tm.is_erc20 = 1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] I think there's a typo in your query - it should be 'total_supply' not 'total_supply'. Also, can you join this with the token_prices_latest table to include the current price of each token?

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.10 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] The token_prices_latest table isn't in the schema. Can you modify the query to use the erc20_balances table instead to show the total balance held across all wallets for each token?

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, SUM(CAST(eb.amount AS decimal)) AS total_balance FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address WHERE tm.is_erc20 = 1 GROUP BY tm.name, tm.contract_address, tm.total_supply ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas (
    block_timestamp timestamp(6) NOT NULL,  -- Timestamp of the block when token metadata was recorded
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    transaction_hash varchar NOT NULL, -- Hash value of the transaction
    transaction_index bigint NOT NULL, -- Index of the transaction within the block
    from_address varchar NOT NULL, -- Address from which the transaction originated
    contract_address varchar NOT NULL, -- Address of the token contract
    symbol varchar NOT NULL, -- Symbol of the token
    total_supply varchar NOT NULL, -- erc20 contract total supply
    name varchar NOT NULL, -- Name of the token
    decimals bigint NOT NULL, -- Number of decimal places for the token
    is_erc20 integer NOT NULL, -- Flag indicating if the token is an ERC-20 token (0 or 1)
    is_erc721 integer NOT NULL, -- Flag indicating if the token is an ERC-721 token (0 or 1)
    is_erc1155 integer NOT NULL, -- Flag indicating if the token is an ERC-1155 token (0 or 1)
    is_proxy integer NOT NULL, -- Flag indicating if the token is a proxy (0 or 1)
    extra_info varchar NOT NULL, -- Additional information about the token
    pk integer NOT NULL  -- Partition key for the table(floor(block_number / 5760))
)
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_activities (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar NOT NULL, -- mint | transfer | burn
    tick varchar NOT NULL, -- Token tick
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Mint amount
    from_address varchar(42) NOT NULL, -- Address sending the inscription (matches from_address in transactions table)
    to_address varchar(42) NOT NULL  -- Address receiving the inscription (match to_address in transactions table)
)
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)


[User] List all claims and the first and last name of the agent who handled each claim.

[Assistant] SELECT T1.claim_id, T1.estimated_loss, T2.first_name, T2.last_name FROM claims AS T1 JOIN agents AS T2 ON T1.claim_handler_id = T2.agent_id

[User] Can you also include the policy ID and customer ID for each claim?

[Assistant] SELECT T1.claim_id, T1.policy_id, T1.customer_id, T1.estimated_loss, T2.first_name, T2.last_name FROM claims AS T1 JOIN agents AS T2 ON T1.claim_handler_id = T2.agent_id

[User] Filter the results to only show claims where the status is 'Open' and the agent is currently 'active'.

[Assistant] SELECT T1.claim_id, T1.policy_id, T1.customer_id, T1.estimated_loss, T2.first_name, T2.last_name FROM claims AS T1 JOIN agents AS T2 ON T1.claim_handler_id = T2.agent_id WHERE T1.status = 'Open' AND T2.status = 'active'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id.text, policy_id.text, customer_id.text, payment_date.timestamp, amount_paid.numeric, payment_method.text, transaction_reference.text, due_date.date, payment_period_start.date, payment_period_end.date, status.text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id.text, policy_id.text, customer_id.text, first_name.text, last_name.text, relationship.text, percentage_share.numeric, contact_info.text, added_at.timestamp )


[User] Provide a list of all vehicles and the total quantity of fuel refueled for each vehicle.

[Assistant] SELECT T1.license_plate, sum(T2.quantity) FROM transportation.vehicles AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id = T2.vehicle_id GROUP BY T1.license_plate

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text 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.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.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 )


[User] Find all contracts where the deployer address is the same as the contract address, indicating self-deployed contracts, and show their network IDs and deployment timestamps.

[Assistant] SELECT address, network_id, deployed_at FROM web3.contracts WHERE address = deployer_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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 )


[User] Show me assets along with their associated 'symbol' metadata value. Assume an assets table with asset_id exists.

[Assistant] SELECT a.asset_id, m.value FROM assets a JOIN metadata m ON a.asset_id = m.asset_id WHERE m.key = 'symbol'

[User] Now, also include the 'name' metadata value for these assets in the same result.

[Assistant] SELECT a.asset_id, m_symbol.value AS symbol, m_name.value AS name FROM assets a LEFT JOIN metadata m_symbol ON a.asset_id = m_symbol.asset_id AND m_symbol.key = 'symbol' LEFT JOIN metadata m_name ON a.asset_id = m_name.asset_id AND m_name.key = 'name'

[User] For assets that have both 'symbol' and 'name' metadata, list the asset ID and the count of *all* metadata entries they have.

[Assistant] SELECT a.asset_id, COUNT(m_all.metadata_id) FROM assets a JOIN metadata m_symbol ON a.asset_id = m_symbol.asset_id AND m_symbol.key = 'symbol' JOIN metadata m_name ON a.asset_id = m_name.asset_id AND m_name.key = 'name' JOIN metadata m_all ON a.asset_id = m_all.asset_id GROUP BY a.asset_id

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] Show me all time entries, including the case name they are associated with.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id

[User] Only show me time entries for lawyer with ID 'lawyer_789'.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789'

[User] Actually, I only want entries for the date '2024-07-30', and just show the entry description, hours spent, and case name.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789' AND T1.date_worked = '2024-07-30'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] Find all pairs of users who registered at exactly the same timestamp, showing both user IDs, usernames, and the shared registration timestamp.

[Assistant]
SELECT u1.user_id AS user_id_1, u1.username AS username_1, u2.user_id AS user_id_2, u2.username AS username_2, u1.created_at
FROM web3.users u1
JOIN web3.users u2
  ON u1.created_at = u2.created_at
  AND u1.user_id < u2.user_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] Retrieve the count of active insurance products for each product_type and order the results by the count descending.

[Assistant]
SELECT product_type,
       COUNT(*) AS active_count
FROM insurance.insurance_products
WHERE is_active = TRUE
GROUP BY product_type
ORDER BY active_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )


[User] Show me all cryptocurrency assets that have been traded more than 50 times but have never been traded in quantities greater than 100, along with their average trade price.

[Assistant] SELECT a.asset_id, a.name, a.symbol, COUNT(t.trade_id) AS trade_count, AVG(t.price) AS avg_price FROM trading_platform.assets a JOIN trading_platform.trades t ON a.asset_id = t.asset_id WHERE a.type = 'cryptocurrency' GROUP BY a.asset_id, a.name, a.symbol HAVING COUNT(t.trade_id) > 50 AND MAX(t.quantity) <= 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )


[User] Find transactions that triggered events and whose to_address matches the contract_id of the emitted event. List the transaction ID, the to_address, and the count of such events for that transaction.

[Assistant] SELECT t.transaction_id, t.to_address, COUNT(e.event_id) AS matching_event_count FROM web3.transactions t JOIN web3.events e ON t.transaction_id = e.transaction_id WHERE t.to_address IS NOT NULL AND t.to_address = e.contract_id GROUP BY t.transaction_id, t.to_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )


[User] For each guest, list reservation_id, guest_id, check_in_date, and the next reservation_id and its check_in_date.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     );

[User] Only include guests who have at least two reservations.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

[User] Also, only show next reservations that occur within 30 days of the current reservation.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
   AND r2.check_in_date <= r1.check_in_date + INTERVAL '30 days'
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id text, 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 integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )