System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )

[User] Show each vehicle's ID along with another vehicle's ID where they share the same make but have different models. Sort by the first vehicle_id.

[Assistant]
SELECT v1.vehicle_id AS vehicle_a, v2.vehicle_id AS vehicle_b
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model <> v2.model
ORDER BY v1.vehicle_id;

[User] Oops, I only want pairs where both vehicles have status 'Active'.

[Assistant]
SELECT v1.vehicle_id AS vehicle_a, v2.vehicle_id AS vehicle_b
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model <> v2.model
WHERE v1.status = 'Active'
  AND v2.status = 'Active'
ORDER BY v1.vehicle_id;

[User] Also include the year and capacity of both vehicles in the output.

[Assistant]
SELECT v1.vehicle_id AS vehicle_a,
       v1.year   AS year_a,
       v1.capacity AS capacity_a,
       v2.vehicle_id AS vehicle_b,
       v2.year   AS year_b,
       v2.capacity AS capacity_b
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model <> v2.model
WHERE v1.status = 'Active'
  AND v2.status = 'Active'
ORDER BY v1.vehicle_id;

[User] Can you list all vehicles acquired in 2023, their make, model, and acquisition date?

[Assistant] SELECT vehicle_id, make, model, acquisition_date FROM transportation.vehicles WHERE acquisition_date >= '2023-01-01' AND acquisition_date < '2024-01-01';

[User] Add the vehicle's license plate and fuel type to the result.

[Assistant] SELECT vehicle_id, license_plate, make, model, fuel_type, acquisition_date FROM transportation.vehicles WHERE acquisition_date >= '2023-01-01' AND acquisition_date < '2024-01-01';

[User] Only include vehicles with a capacity greater than 40.

[Assistant] SELECT vehicle_id, license_plate, make, model, fuel_type, acquisition_date FROM transportation.vehicles WHERE acquisition_date >= '2023-01-01' AND acquisition_date < '2024-01-01' AND capacity > 40;

[User] I got an error because 'capacity' is not in SELECT. Please add the capacity to the results.

[Assistant] SELECT vehicle_id, license_plate, make, model, fuel_type, capacity, acquisition_date FROM transportation.vehicles WHERE acquisition_date >= '2023-01-01' AND acquisition_date < '2024-01-01' AND capacity > 40;

[User] List the vehicle_id, make, model, and acquisition_date for all active vehicles acquired after '2022-01-01'.

[Assistant]
SELECT vehicle_id, make, model, acquisition_date
FROM transportation.vehicles
WHERE status = 'Active'
  AND acquisition_date > '2022-01-01';

[User] Now, filter this list to only include vehicles with capacity greater than 50 and order by acquisition_date ascending.

[Assistant]
SELECT vehicle_id, make, model, acquisition_date
FROM transportation.vehicles
WHERE status = 'Active'
  AND acquisition_date > '2022-01-01'
  AND capacity > 50
ORDER BY acquisition_date ASC;

[User] For each vehicle, find the vehicle acquired immediately before it in the same depot. Show current vehicle_id, acquisition_date, previous_vehicle_id, and previous_acquisition_date.

[Assistant]
SELECT v.vehicle_id,
       v.acquisition_date,
       prev.vehicle_id AS previous_vehicle_id,
       prev.acquisition_date AS previous_acquisition_date
FROM transportation.vehicles v
LEFT JOIN transportation.vehicles prev
  ON v.depot_id = prev.depot_id
  AND prev.acquisition_date = (
    SELECT MAX(acquisition_date)
    FROM transportation.vehicles
    WHERE depot_id = v.depot_id
      AND acquisition_date < v.acquisition_date
  );

[User] Show me all vehicles that are due for their next service before the end of this month, along with their last service date and type.

[Assistant] SELECT v.vehicle_id, v.make, v.model, s.service_date, s.service_type FROM transportation.vehicles v JOIN transportation.service_logs s ON v.vehicle_id = s.vehicle_id WHERE s.next_service_due <= DATE('now', 'start of month', '+1 month', '-1 day') ORDER BY s.next_service_due;

[User] Can you include the mechanic who performed the last service and order the results by how soon the next service is due?

[Assistant] SELECT v.vehicle_id, v.make, v.model, s.service_date, s.service_type, s.mechanic, s.next_service_due FROM transportation.vehicles v JOIN transportation.service_logs s ON v.vehicle_id = s.vehicle_id WHERE s.next_service_due <= DATE('now', 'start of month', '+1 month', '-1 day') ORDER BY s.next_service_due ASC;

[User] Now filter this to only show vehicles where the last service was an 'Engine Tune-up'.

[Assistant] SELECT v.vehicle_id, v.make, v.model, s.service_date, s.service_type, s.mechanic, s.next_service_due FROM transportation.vehicles v JOIN transportation.service_logs s ON v.vehicle_id = s.vehicle_id WHERE s.next_service_due <= DATE('now', 'start of month', '+1 month', '-1 day') AND s.service_type = 'Engine Tune-up' ORDER BY s.next_service_due ASC;

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

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

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

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

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

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

[User] Please round avg_capacity to one decimal place.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] Which locations have received fuel logs greater than 300 liters in total? Please include the location name and city.

[Assistant]
SELECT l.name AS location_name, l.city, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] Can you also include the number of times fuel was logged at each location?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] Actually, could you restrict it to only locations that are in 'New York' city?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
WHERE l.city = 'New York'
GROUP BY l.location_id, l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] I got an error about ambiguous column in GROUP BY, can you fix and show only the columns used in SELECT in the GROUP BY?

[Assistant]
SELECT l.name AS location_name, l.city, COUNT(f.fuel_log_id) AS log_count, SUM(f.quantity) AS total_quantity
FROM transportation.fuel_logs f
JOIN transportation.locations l ON f.location_id = l.location_id
WHERE l.city = 'New York'
GROUP BY l.name, l.city
HAVING SUM(f.quantity) > 300;

[User] List every booking together with the route number and description for the trip being booked.

[Assistant]
SELECT b.booking_id, b.passenger_id, b.trip_id, r.route_number, r.description
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id;

[User] Show me the total fuel quantity and cost for each route, grouped by route number, only for trips that have associated fuel logs.

[Assistant]
SELECT r.route_number, SUM(f.quantity) AS total_quantity, SUM(f.total_cost) AS total_cost
FROM transportation.fuel_logs f
JOIN transportation.routes r ON f.trip_id IS NOT NULL AND f.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs
)
JOIN transportation.bookings b ON f.trip_id = b.trip_id
WHERE r.route_id = b.trip_id
GROUP BY r.route_number;

[User] For each city, show how many trips have started there (origin), how many have ended there (destination), and the total number of unique vehicles used in trips that started in that city.

[Assistant]
SELECT l.city,
       COUNT(CASE WHEN t.origin_location_id = l.location_id THEN 1 END) AS trips_started,
       COUNT(CASE WHEN t.destination_location_id = l.location_id THEN 1 END) AS trips_ended,
       COUNT(DISTINCT CASE WHEN t.origin_location_id = l.location_id THEN t.vehicle_id END) AS unique_vehicles_started
FROM transportation.locations l
LEFT JOIN transportation.trips t ON t.origin_location_id = l.location_id OR t.destination_location_id = l.location_id
GROUP BY l.city;

[User] Show all maintenance logs with the vehicle ID, service date, service type, and the name and city of the location where the vehicle's most recent fueling occurred.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id;

[User] I want to see only maintenance logs where the service_type is 'Inspection' and the maintenance cost exceeds 150.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150;

[User] Can you also add the odometer reading from the maintenance log and sort the results by service_date descending?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.odometer_reading, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150
ORDER BY ml.service_date DESC;

[User] Sorry, can you restrict the results to logs from after January 1, 2023?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.odometer_reading, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150 AND ml.service_date > '2023-01-01'
ORDER BY ml.service_date DESC;

[User] For each city that has a fueling location, show the city name and the total quantity of fuel refueled.

[Assistant] SELECT T2.city ,  SUM(T1.quantity) FROM transportation.fuel_logs AS T1 JOIN transportation.locations AS T2 ON T1.location_id  =  T2.location_id GROUP BY T2.city


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.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)
)

[User] List the total number of appointments for each status and also show the latest appointment_time for each status.

[Assistant]
SELECT status, COUNT(*) AS total_appointments, MAX(appointment_time) AS latest_appointment_time
FROM healthcare.appointments
GROUP BY status;

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

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

[User] Show me the total number of appointments grouped by each unique duration in minutes. Include only durations with more than 5 appointments.

[Assistant]
SELECT duration_minutes, COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY duration_minutes
HAVING COUNT(*) > 5;

[User] Can you also show, for each of these durations, the earliest and latest appointment_time?

[Assistant]
SELECT duration_minutes, COUNT(*) AS appointment_count,
       MIN(appointment_time) AS earliest_appointment,
       MAX(appointment_time) AS latest_appointment
FROM healthcare.appointments
GROUP BY duration_minutes
HAVING COUNT(*) > 5;

[User] List all appointments with a non-empty notes field. Return appointment_id, appointment_time, and doctor_id.

[Assistant]
SELECT appointment_id, appointment_time, doctor_id
FROM healthcare.appointments
WHERE notes IS NOT NULL AND notes <> '';

[User] Could you further filter to only appointments where status is 'No-show'?

[Assistant]
SELECT appointment_id, appointment_time, doctor_id
FROM healthcare.appointments
WHERE notes IS NOT NULL AND notes <> ''
  AND status = 'No-show';

[User] List all appointments that were marked as 'No-show'. Show appointment ID, patient ID, and appointment time.

[Assistant] SELECT appointment_id, patient_id, appointment_time FROM healthcare.appointments WHERE status = 'No-show';

[User] Can you find all appointments where the duration is less than 20 minutes and the status is not 'Cancelled'? For each, show the appointment_id, appointment_time, status, and doctor_id.

[Assistant]
SELECT appointment_id, appointment_time, status, doctor_id
FROM healthcare.appointments
WHERE duration_minutes < 20
  AND status <> 'Cancelled';

[User] Now, only show appointments that took place at locations with an ID starting with 'CLINIC'.

[Assistant]
SELECT appointment_id, appointment_time, status, doctor_id, location_id
FROM healthcare.appointments
WHERE duration_minutes < 20
  AND status <> 'Cancelled'
  AND location_id LIKE 'CLINIC%';

[User] Can you also add the notes field to the output and sort results by appointment_time ascending?

[Assistant]
SELECT appointment_id, appointment_time, status, doctor_id, location_id, notes
FROM healthcare.appointments
WHERE duration_minutes < 20
  AND status <> 'Cancelled'
  AND location_id LIKE 'CLINIC%'
ORDER BY appointment_time ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )

[User] Show a count of drivers per status.

[Assistant]
SELECT status, COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

[User] Can you also list the earliest hire date for each status?

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status;

[User] I only want to see statuses with more than 5 drivers.

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 5;

[User] Please sort the output by driver_count in descending order.

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 5
ORDER BY driver_count DESC;

[User] Calculate the total number of drivers for each status.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

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

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 10;

[User] List all drivers whose licenses are set to expire within the next 60 days, along with their full name, license number, and contact number.

[Assistant]
SELECT driver_id, first_name, last_name, license_number, contact_number
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] For each driver, show their driver_id, first_name, last_name, along with any other driver whose license_expiry_date is earlier than theirs.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date;

[User] Exclude pairs where the two expiry dates are not in the same calendar year.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date);

[User] Also only include pairs where the difference between their expiry dates is more than 30 days.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date,
       DATE_PART('day', d1.license_expiry_date - d2.license_expiry_date) AS days_difference
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
WHERE d1.license_expiry_date - d2.license_expiry_date > INTERVAL '30 days';

[User] List pairs of drivers whose license expiry dates fall within 30 days of each other. Show both driver_ids, names, and the two expiry dates.

[Assistant] SELECT d1.driver_id AS driver1_id, d1.first_name AS driver1_first, d1.last_name AS driver1_last, d1.license_expiry_date AS expiry1, d2.driver_id AS driver2_id, d2.first_name AS driver2_first, d2.last_name AS driver2_last, d2.license_expiry_date AS expiry2 FROM transportation.drivers d1 JOIN transportation.drivers d2 ON d1.driver_id < d2.driver_id AND ABS((d1.license_expiry_date - d2.license_expiry_date)) <= INTERVAL '30 days';

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.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 pairs of documents uploaded by the same user for the same claim. Return uploaded_by, claim_id, document_id AS doc1_id, and the paired document_id AS doc2_id.

[Assistant]
SELECT cd1.uploaded_by,
       cd1.claim_id,
       cd1.document_id AS doc1_id,
       cd2.document_id AS doc2_id
FROM insurance.claim_documents cd1
JOIN insurance.claim_documents cd2
  ON cd1.claim_id = cd2.claim_id
 AND cd1.uploaded_by = cd2.uploaded_by
 AND cd1.document_id < cd2.document_id;

[User] Filter to only include pairs where the two documents have different mime_types.

[Assistant]
SELECT cd1.uploaded_by,
       cd1.claim_id,
       cd1.document_id AS doc1_id,
       cd2.document_id AS doc2_id
FROM insurance.claim_documents cd1
JOIN insurance.claim_documents cd2
  ON cd1.claim_id = cd2.claim_id
 AND cd1.uploaded_by = cd2.uploaded_by
 AND cd1.document_id < cd2.document_id
WHERE cd1.mime_type <> cd2.mime_type;

[User] List all document IDs, file names, and uploaded timestamps for documents that were uploaded on a weekend.

[Assistant] SELECT document_id, file_name, uploaded_at FROM insurance.claim_documents WHERE EXTRACT(DOW FROM uploaded_at) IN (0, 6);

[User] Show the top 5 largest documents by file size, including document_id, claim_id, file_name, and file_size_bytes.

[Assistant]
SELECT document_id,
       claim_id,
       file_name,
       file_size_bytes
FROM insurance.claim_documents
ORDER BY file_size_bytes DESC
LIMIT 5;

[User] Find claims where documents were uploaded by more than one distinct user. Show the claim_id.

[Assistant] SELECT claim_id FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(DISTINCT uploaded_by) > 1;

[User] Can you also include the total number of distinct uploaders and the total number of documents for each of those claims? Label them as distinct_uploaders and total_documents.

[Assistant] SELECT claim_id, COUNT(DISTINCT uploaded_by) AS distinct_uploaders, COUNT(*) AS total_documents FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(DISTINCT uploaded_by) > 1;

[User] List the document ID, file name, document type, and upload date for all documents.

[Assistant] SELECT document_id, file_name, document_type, uploaded_at FROM insurance.claim_documents;

[User] From these results, only show documents of type 'Insurance Application'.

[Assistant] SELECT document_id, file_name, document_type, uploaded_at FROM insurance.claim_documents WHERE document_type = 'Insurance Application';

[User] Also, only include files larger than 1 megabyte.

[Assistant] SELECT document_id, file_name, document_type, uploaded_at FROM insurance.claim_documents WHERE document_type = 'Insurance Application' AND file_size_bytes > 1048576;

[User] Okay, now just show the document ID, file name, and file size, ordered by file size descending.

[Assistant] SELECT document_id, file_name, file_size_bytes FROM insurance.claim_documents WHERE document_type = 'Insurance Application' AND file_size_bytes > 1048576 ORDER BY file_size_bytes DESC;

[User] List all claim documents where the description contains the word 'invoice'.

[Assistant] SELECT document_id, claim_id, file_name, description FROM insurance.claim_documents WHERE description ILIKE '%invoice%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
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.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Provide a summary for each transaction ID, showing the total amount of all its unspent UTXOs.

[Assistant] SELECT transaction_id, SUM(amount) FROM utxos WHERE spent = false GROUP BY transaction_id

[User] Retrieve all orders placed after '2024-06-01', including order_id, user_id, asset_id, quantity, and price.

[Assistant]
SELECT order_id, user_id, asset_id, quantity, price
FROM trading_platform.orders
WHERE created_at > '2024-06-01';

[User] Actually, only include orders for assets whose metadata key is 'category' and value is 'cryptocurrency'.

[Assistant]
SELECT o.order_id, o.user_id, o.asset_id, o.quantity, o.price
FROM trading_platform.orders o
JOIN trading_platform.metadata m ON o.asset_id = m.asset_id
WHERE o.created_at > '2024-06-01'
  AND m.key = 'category' AND m.value = 'cryptocurrency';

[User] Now, count the number of such orders per asset, along with the asset_id.

[Assistant]
SELECT o.asset_id, COUNT(*) AS order_count
FROM trading_platform.orders o
JOIN trading_platform.metadata m ON o.asset_id = m.asset_id
WHERE o.created_at > '2024-06-01'
  AND m.key = 'category' AND m.value = 'cryptocurrency'
GROUP BY o.asset_id;

[User] Finally, only show assets with more than 5 such orders, ordered by order_count descending.

[Assistant]
SELECT o.asset_id, COUNT(*) AS order_count
FROM trading_platform.orders o
JOIN trading_platform.metadata m ON o.asset_id = m.asset_id
WHERE o.created_at > '2024-06-01'
  AND m.key = 'category' AND m.value = 'cryptocurrency'
GROUP BY o.asset_id
HAVING COUNT(*) > 5
ORDER BY order_count DESC;

[User] List the top 5 largest unspent UTXOs by amount, showing utxo_id, address, and amount, ordered descending.

[Assistant] SELECT utxo_id, address, amount FROM trading_platform.utxos WHERE spent = false ORDER BY amount DESC LIMIT 5;

[User] List each user along with the number of wallets they own and the number of unique addresses found in their UTXOs.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COUNT(DISTINCT ut.address) as unique_utxo_addresses
FROM trading_platform.wallets w
JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id;

[User] Actually, only include users who have more than 1 unique UTXO address.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COUNT(DISTINCT ut.address) as unique_utxo_addresses
FROM trading_platform.wallets w
JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id
HAVING COUNT(DISTINCT ut.address) > 1;

[User] The query doesn't work because some users have no UTXOs. Please include all users with their wallet count, and show 0 for unique_utxo_addresses if they don't have any.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COALESCE(COUNT(DISTINCT ut.address), 0) as unique_utxo_addresses
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id;

[User] Now, show only users who have at least 2 wallets.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COALESCE(COUNT(DISTINCT ut.address), 0) as unique_utxo_addresses
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id
HAVING COUNT(DISTINCT w.wallet_id) >= 2;

[User] Show me the top 5 users who have the highest total trade volume (quantity * price) as buyers, along with their email addresses and the number of distinct assets they traded.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;

[User] Now modify the query to include only trades that happened in the last 30 days and show the average trade price for each buyer.

[Assistant] SELECT u.user_id, u.email, COUNT(DISTINCT t.asset_id) AS distinct_assets_traded, SUM(t.quantity * t.price) AS total_trade_volume, AVG(t.price) AS average_trade_price FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id WHERE t.traded_at >= NOW() - INTERVAL '30 days' GROUP BY u.user_id, u.email ORDER BY total_trade_volume DESC LIMIT 5;

[User] Actually, I want to see the top 5 buyers by total trade volume who also have wallets, and include their wallet addresses.

[Assistant] SELECT u.user_id, u.email, w.address AS wallet_address, SUM(t.quantity * t.price) AS total_trade_volume FROM trading_platform.users u JOIN trading_platform.trades t ON u.user_id = t.buyer_id JOIN trading_platform.orders o ON t.order_id = o.order_id JOIN trading_platform.utxos w ON o.wallet_id = w.address WHERE w.spent = false GROUP BY u.user_id, u.email, w.address ORDER BY total_trade_volume DESC LIMIT 5;

[User] I want a summary of each asset showing the total number of trades executed and the average trade price, including asset name and symbol.

[Assistant]
SELECT a.asset_id,
       a.name,
       a.symbol,
       COUNT(t.trade_id) AS trades_count,
       AVG(t.price) AS avg_price
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON a.asset_id = t.asset_id
GROUP BY a.asset_id, a.name, a.symbol;

[User] Actually, exclude trades before '2024-05-01'.

[Assistant]
SELECT a.asset_id,
       a.name,
       a.symbol,
       COUNT(t.trade_id) AS trades_count,
       AVG(t.price) AS avg_price
FROM trading_platform.assets a
LEFT JOIN trading_platform.trades t ON a.asset_id = t.asset_id
  AND t.traded_at >= '2024-05-01'
GROUP BY a.asset_id, a.name, a.symbol;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.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.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )

[User] List all game titles and the count of online servers hosting each game.

[Assistant] SELECT T1.title, count(T2.server_id) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title;

[User] Only include games that have more than 2 online servers.

[Assistant] SELECT T1.title, count(T2.server_id) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title HAVING count(T2.server_id) > 2;

[User] Also, include the average current player count for these online servers per game.

[Assistant] SELECT T1.title, count(T2.server_id), avg(T2.current_players) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title HAVING count(T2.server_id) > 2;

[User] Sort the results by the average current player count in descending order.

[Assistant] SELECT T1.title, count(T2.server_id), avg(T2.current_players) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T2.status = 'online' GROUP BY T1.title HAVING count(T2.server_id) > 2 ORDER BY avg(T2.current_players) DESC;

[User] List all item names and their rarity, along with the title of the game they belong to.

[Assistant] SELECT T1.item_name, T1.rarity, T2.title FROM in_game_items AS T1 JOIN games AS T2 ON T1.game_id = T2.game_id;

[User] Only show items with a rarity of 'Rare' or 'Epic' and a cost amount greater than 50.

[Assistant] SELECT T1.item_name, T1.rarity, T2.title FROM in_game_items AS T1 JOIN games AS T2 ON T1.game_id = T2.game_id WHERE T1.rarity IN ('Rare', 'Epic') AND T1.cost_amount > 50;

[User] Also, only include items belonging to games released after 2020.

[Assistant] SELECT T1.item_name, T1.rarity, T2.title FROM in_game_items AS T1 JOIN games AS T2 ON T1.game_id = T2.game_id WHERE T1.rarity IN ('Rare', 'Epic') AND T1.cost_amount > 50 AND T2.release_date > '2020-12-31';

[User] I'd like to see, for each month, the total number of players who registered and how many of them are active versus inactive.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count
FROM gaming_technology.players
GROUP BY month;

[User] Actually, limit this to registrations from January 1, 2022 onwards.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count
FROM gaming_technology.players
WHERE registration_date >= '2022-01-01'
GROUP BY month;

[User] Also, I'd like to calculate the active percentage per month as active_count * 100.0 / total_registrations.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count,
       ROUND(
         COUNT(*) FILTER (WHERE status = 'active') * 100.0 /
         NULLIF(COUNT(*),0), 2
       ) AS active_percentage
FROM gaming_technology.players
WHERE registration_date >= '2022-01-01'
GROUP BY month;

[User] Finally, please sort the output by month in ascending order.

[Assistant]
SELECT DATE_TRUNC('month', registration_date) AS month,
       COUNT(*) AS total_registrations,
       COUNT(*) FILTER (WHERE status = 'active')   AS active_count,
       COUNT(*) FILTER (WHERE status = 'inactive') AS inactive_count,
       ROUND(
         COUNT(*) FILTER (WHERE status = 'active') * 100.0 /
         NULLIF(COUNT(*),0), 2
       ) AS active_percentage
FROM gaming_technology.players
WHERE registration_date >= '2022-01-01'
GROUP BY month
ORDER BY month ASC;

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

[User] Show me the username and registration date for players who do not have a last login recorded.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE last_login IS NULL;

[User] Also include their country code in the output.

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL;

[User] Filter this list to only include players from the United Kingdom ('GB').

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'GB';

[User] Order the results by their registration date, from oldest to newest.

[Assistant] SELECT username, registration_date, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'GB' ORDER BY registration_date ASC;

[User] Show me the usernames and registration dates for players who registered between '2023-01-01' and '2023-12-31'.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE registration_date >= '2023-01-01' AND registration_date < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )

[User] Find all notifications that were sent more than 24 hours ago and are still unread. Show the notification ID, user ID, and sent_at timestamp.

[Assistant] SELECT notification_id, user_id, sent_at FROM notifications WHERE read_at IS NULL AND sent_at < NOW() - INTERVAL '24 hour';

[User] Provide a count of notifications, separated by whether they have been read or not.

[Assistant] SELECT CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END, count(T1.notification_id) FROM trading_platform.notifications AS T1 GROUP BY CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END

[User] For each user, show their username and the timestamp of their most recent notification. Include users who have never received notifications.

[Assistant] SELECT T1.username, max(T2.sent_at) FROM users AS T1 LEFT JOIN trading_platform.notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.username

[User] Could you also include the total number of notifications for each user?

[Assistant] SELECT T1.username, count(T2.notification_id), max(T2.sent_at) FROM users AS T1 LEFT JOIN trading_platform.notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.username

[User] Actually, only show users whose latest notification is unread.

[Assistant] WITH LatestNotification AS ( SELECT user_id, sent_at, read_at, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY sent_at DESC) AS rn FROM trading_platform.notifications ) SELECT T1.username, T2.sent_at FROM users AS T1 JOIN LatestNotification AS T2 ON T1.user_id = T2.user_id WHERE T2.rn = 1 AND T2.read_at IS NULL

[User] Also, include the count of unread notifications for these users.

[Assistant] WITH LatestNotification AS ( SELECT user_id, sent_at, read_at, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY sent_at DESC) AS rn FROM trading_platform.notifications ) SELECT T1.username, count(CASE WHEN T3.read_at IS NULL THEN T3.notification_id ELSE NULL END), T2.sent_at FROM users AS T1 JOIN LatestNotification AS T2 ON T1.user_id = T2.user_id AND T2.rn = 1 AND T2.read_at IS NULL JOIN trading_platform.notifications AS T3 ON T1.user_id = T3.user_id GROUP BY T1.username, T2.sent_at

[User] I want to find the average time it takes for a notification to be marked as read, calculated for each user. Please show the user ID and the average read time in seconds, considering only notifications that have been read.

[Assistant] SELECT user_id, AVG(EXTRACT(EPOCH FROM (read_at - sent_at))) AS average_read_time_seconds FROM notifications WHERE read_at IS NOT NULL GROUP BY user_id ORDER BY average_read_time_seconds;

[User] The previous query only included users who have read at least one notification. Please modify it to include all users who have received at least one notification, showing NULL for the average read time if they haven't read any.

[Assistant] SELECT user_id, AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) AS average_read_time_seconds FROM notifications GROUP BY user_id ORDER BY average_read_time_seconds;

[User] Now, filter this list to only include users whose average read time is greater than 600 seconds (10 minutes).

[Assistant] SELECT user_id, AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) AS average_read_time_seconds FROM notifications GROUP BY user_id HAVING AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) > 600 ORDER BY average_read_time_seconds;

[User] Also, include the total number of notifications sent to each of these users in the result, and order the list by average read time in descending order.

[Assistant] SELECT user_id, AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) AS average_read_time_seconds, COUNT(*) AS total_notifications FROM notifications GROUP BY user_id HAVING AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) > 600 ORDER BY average_read_time_seconds DESC;

[User] Could you provide the total number of notifications sent on each day?

[Assistant] SELECT DATE(sent_at), COUNT(*) FROM notifications GROUP BY DATE(sent_at) ORDER BY DATE(sent_at);

[User] Now, show only the days where more than 50 notifications were sent. Also, for those days, calculate the average time it took for notifications sent on that day to be read (only consider notifications that have been read).

[Assistant] SELECT DATE(sent_at), COUNT(*), AVG(EXTRACT(EPOCH FROM (read_at - sent_at))) FROM notifications WHERE read_at IS NOT NULL GROUP BY DATE(sent_at) HAVING COUNT(*) > 50 ORDER BY DATE(sent_at);

[User] Show me all notifications sent in the last 7 days, including the user ID and message.

[Assistant] SELECT user_id, message, sent_at FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days';

[User] From that list, only show the notifications that have not been read yet.

[Assistant] SELECT user_id, message, sent_at FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL;

[User] Instead of listing them, can you just give me the total count of unread notifications sent in the last 7 days?

[Assistant] SELECT COUNT(*) FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL;

[User] Now, show the count of unread notifications sent in the last 7 days for each user ID.

[Assistant] SELECT user_id, COUNT(*) FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL GROUP BY user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] Find all service locations in the city of 'Albany' that are accessible. Show their IDs, names, and contact phone numbers along with their address.

[Assistant] SELECT location_id, location_name, contact_phone, address FROM government_services.service_locations WHERE city = 'Albany' AND is_accessible = TRUE;

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

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

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

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

[User] Find all service locations whose postal code starts with '75' and display their names, cities, and operating hours, including the agency ID.

[Assistant] SELECT location_name, city, operating_hours, agency_id FROM government_services.service_locations WHERE postal_code LIKE '75%';

[User] How many service locations do we have in each state?

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

[User] Only show states where there are at least 3 locations.

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Can you also show the number of accessible locations in each of those states?

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Order the results by accessible location count in descending order.

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3 ORDER BY accessible_location_count DESC;

[User] List all states where we have more than two service locations, and display the number of locations per state.

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

[User] Can you also show only those states that have at least one accessible location?

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations WHERE state IN (SELECT DISTINCT state FROM government_services.service_locations WHERE is_accessible = TRUE) GROUP BY state HAVING COUNT(*) > 2;

[User] Now sort the results by location_count in descending order.

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations WHERE state IN (SELECT DISTINCT state FROM government_services.service_locations WHERE is_accessible = TRUE) GROUP BY state HAVING COUNT(*) > 2 ORDER BY location_count DESC;

[User] What if I only want states where more than one third of locations are accessible? Show state, location_count, and accessible_location_count.

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) > COUNT(*)/3;

[User] Show me a list of all appointment IDs, the name of the service associated with each appointment, and the location name where it is scheduled.

[Assistant]
SELECT appt.appointment_id, srv.service_id, loc.location_name
FROM government_services.appointments appt
JOIN government_services.service_locations loc ON appt.location_id = loc.location_id
JOIN government_services.applications appl ON appl.citizen_id = appt.citizen_id AND appl.service_id = appt.service_id
JOIN government_services.applications app ON app.service_id = appt.service_id
JOIN government_services.service_locations sloc ON appt.location_id = sloc.location_id;

[User] Actually, can you also include the scheduled start time for each appointment in the result?

[Assistant]
SELECT appt.appointment_id, srv.service_id, loc.location_name, appt.scheduled_start_time
FROM government_services.appointments appt
JOIN government_services.service_locations loc ON appt.location_id = loc.location_id
JOIN government_services.applications appl ON appl.citizen_id = appt.citizen_id AND appl.service_id = appt.service_id
JOIN government_services.applications app ON app.service_id = appt.service_id
JOIN government_services.service_locations sloc ON appt.location_id = sloc.location_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 token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )

[User] Show me all tokens which have a 6-hour price change percentage above 2% and the current price, on the Arbitrum chain.

[Assistant]
SELECT token_symbol, price, price_change_percentage_6h
FROM token_dexpool_info
WHERE chain = 'Arbitrum'
  AND price_change_percentage_6h > 2;

[User] For each chain, which token has the lowest average cost as reported by smart money, and what is its current price and ROI?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Now, I only want to see tokens where the ROI is above 0.5.

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Can you also return the token narrative from the token_basic_info table for each result?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi, tbi.narrative
FROM smart_money_token_performance smtp
JOIN token_basic_info tbi ON smtp.token_symbol = tbi.token_symbol AND smtp.chain = tbi.chain
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi, tbi.narrative;

[User] Show me the top 3 narratives by trend rank, along with their top 3 tokens and 7-day price change percentage.

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d FROM narrative_info n ORDER BY n.trend_rank ASC LIMIT 3;

[User] Can you also include the 24-hour trading volume for these narratives?

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n ORDER BY n.trend_rank ASC LIMIT 3;

[User] Actually, I only want narratives with a 7-day price change percentage above 10%.

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n WHERE n.price_change_percentage_7d > 10 ORDER BY n.trend_rank ASC LIMIT 3;

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

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n WHERE n.price_change_percentage_7d > 10 ORDER BY n.volume_24h DESC LIMIT 3;

[User] What is the total USD value of tokens held by 'Binance' on the 'BSC' chain according to the latest snapshot?

[Assistant] SELECT SUM(usd_value) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] Also, show the number of distinct token symbols held by Binance on BSC in that same snapshot.

[Assistant] SELECT SUM(usd_value), COUNT(DISTINCT token_symbol) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] For each narrative, what is the average smart money ROI and the total 24-hour trading volume of the narrative?

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative

[User] Only include narratives that have more than 20 tokens and a total 24h trading volume above $1,000,000.

[Assistant] SELECT T3.narrative, T4.avg_roi, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Also show the average net flow for smart money performance within each of these narratives.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000

[User] Order the results by average ROI descending and show the top 5.

[Assistant] SELECT T3.narrative, T4.avg_roi, T4.avg_net_flow, T3.volume_24h FROM narrative_info AS T3 JOIN ( SELECT T2.narrative, AVG(T1.roi) as avg_roi, AVG(T1.net_flow) as avg_net_flow FROM smart_money_token_performance AS T1 JOIN token_basic_info AS T2 ON T1.token_address = T2.token_address AND T1.chain = T2.chain GROUP BY T2.narrative ) AS T4 ON T3.narrative = T4.narrative WHERE T3.token_num > 20 AND T3.volume_24h > 1000000 ORDER BY T4.avg_roi DESC LIMIT 5

[User] For each narrative in smart_money_token_inflow, calculate the total usd_value and avg_price from buy transactions (type=1) and include the narrative's token count from narrative_info. Show narrative, chain, total_usd_value, avg_price, and token_num, ordered by total_usd_value descending, limit to 5.

[Assistant]
SELECT i.narrative, i.chain, SUM(i.usd_value) AS total_usd_value, AVG(i.avg_price) AS avg_price, ni.token_num
FROM smart_money_token_inflow AS i
JOIN narrative_info AS ni ON i.narrative = ni.narrative
WHERE i.type = 1
GROUP BY i.narrative, i.chain, ni.token_num
ORDER BY total_usd_value DESC
LIMIT 5;

[User] Please filter results to only include narratives where the total token_amount exceeds 1000.

[Assistant]
SELECT i.narrative, i.chain, SUM(i.usd_value) AS total_usd_value, AVG(i.avg_price) AS avg_price, ni.token_num
FROM smart_money_token_inflow AS i
JOIN narrative_info AS ni ON i.narrative = ni.narrative
WHERE i.type = 1
GROUP BY i.narrative, i.chain, ni.token_num
HAVING SUM(i.token_amount) > 1000
ORDER BY total_usd_value DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id 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 PRIMARY KEY, 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 )

[User] For each account type, show the average balance and the number of completed trades associated with accounts of that type.

[Assistant]
SELECT a.account_type, AVG(a.balance) AS average_balance, COUNT(t.trade_id) AS completed_trade_count
FROM financial_services.accounts a
LEFT JOIN financial_services.trades t ON a.account_id = t.account_id AND t.status = 'COMPLETED'
GROUP BY a.account_type;

[User] Could you also group by currency and include it in the result?

[Assistant]
SELECT a.account_type, a.currency, AVG(a.balance) AS average_balance, COUNT(t.trade_id) AS completed_trade_count
FROM financial_services.accounts a
LEFT JOIN financial_services.trades t ON a.account_id = t.account_id AND t.status = 'COMPLETED'
GROUP BY a.account_type, a.currency;

[User] Now, only include groups where the completed_trade_count is at least 5 and order by average_balance descending.

[Assistant]
SELECT a.account_type, a.currency, AVG(a.balance) AS average_balance, COUNT(t.trade_id) AS completed_trade_count
FROM financial_services.accounts a
LEFT JOIN financial_services.trades t ON a.account_id = t.account_id AND t.status = 'COMPLETED'
GROUP BY a.account_type, a.currency
HAVING COUNT(t.trade_id) >= 5
ORDER BY average_balance DESC;

[User] Show me the average high price and average low price for each security sector using market data.

[Assistant] SELECT T1.sector, AVG(T2.high_price) AS average_high_price, AVG(T2.low_price) AS average_low_price FROM financial_services.securities AS T1 JOIN financial_services.market_data AS T2 ON T1.security_id = T2.security_id WHERE T1.sector IS NOT NULL GROUP BY T1.sector

[User] Restrict the data to market data points from 2023.

[Assistant] SELECT T1.sector, AVG(T2.high_price) AS average_high_price, AVG(T2.low_price) AS average_low_price FROM financial_services.securities AS T1 JOIN financial_services.market_data AS T2 ON T1.security_id = T2.security_id WHERE T1.sector IS NOT NULL AND EXTRACT(YEAR FROM T2.data_timestamp) = 2023 GROUP BY T1.sector

[User] Show me for each loan_type, the total number of loans and the average principal_amount, along with the average account balance for the accounts associated with those loans.

[Assistant]
SELECT l.loan_type, COUNT(l.loan_id) AS loan_count, AVG(l.principal_amount) AS avg_principal_amount, AVG(a.balance) AS avg_account_balance
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY l.loan_type;

[User] Can you only include loan types with more than 3 loans?

[Assistant]
SELECT l.loan_type, COUNT(l.loan_id) AS loan_count, AVG(l.principal_amount) AS avg_principal_amount, AVG(a.balance) AS avg_account_balance
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY l.loan_type
HAVING COUNT(l.loan_id) > 3;

[User] And sort the result by avg_principal_amount in descending order.

[Assistant]
SELECT l.loan_type, COUNT(l.loan_id) AS loan_count, AVG(l.principal_amount) AS avg_principal_amount, AVG(a.balance) AS avg_account_balance
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY l.loan_type
HAVING COUNT(l.loan_id) > 3
ORDER BY avg_principal_amount DESC;

[User] List all trades for a given security, showing ticker_symbol, trade_id, account_id, trade_type, and total_amount.

[Assistant]
SELECT s.ticker_symbol, t.trade_id, t.account_id, t.trade_type, t.total_amount
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id;

[User] Only include trades executed on the 'NASDAQ' exchange.

[Assistant]
SELECT s.ticker_symbol, t.trade_id, t.account_id, t.trade_type, t.total_amount
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE s.exchange = 'NASDAQ';

[User] Also, filter to only show trades with total_amount above 2000.

[Assistant]
SELECT s.ticker_symbol, t.trade_id, t.account_id, t.trade_type, t.total_amount
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE s.exchange = 'NASDAQ' AND t.total_amount > 2000;

[User] Show me the total number of customers and their average age grouped by city.

[Assistant] SELECT city, COUNT(customer_id) AS total_customers, AVG(EXTRACT(YEAR FROM NOW()) - EXTRACT(YEAR FROM date_of_birth)) AS average_age FROM financial_services.customers WHERE city IS NOT NULL GROUP BY city

[User] Only include customers with status 'Active'.

[Assistant] SELECT city, COUNT(customer_id) AS total_customers, AVG(EXTRACT(YEAR FROM NOW()) - EXTRACT(YEAR FROM date_of_birth)) AS average_age FROM financial_services.customers WHERE city IS NOT NULL AND status = 'Active' GROUP BY city

[User] Can you show me, for each account type, the total transaction amount and the number of transactions, including the customer full name for each account type?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
GROUP BY a.account_type, customer_name;

[User] Actually, could you only include accounts where the balance is greater than 5000?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE a.balance > 5000
GROUP BY a.account_type, customer_name;

[User] Can you also filter transactions to only include those with status 'SUCCESSFUL'?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE a.balance > 5000 AND t.status = 'SUCCESSFUL'
GROUP BY a.account_type, customer_name;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 train_station_management.trains ( train_id character varying(64) NOT NULL, train_number character varying(32) NOT NULL, model character varying(128), manufacturer character varying(128), year_manufactured integer, capacity integer NOT NULL, status character varying(32) NOT NULL DEFAULT 'Active', last_maintenance_date date, next_maintenance_date date, PRIMARY KEY (train_id), UNIQUE (train_number) )

[User] What is the fuel consumption rate of train number T1234?

[Assistant] I'm sorry, but I don't have information on the fuel consumption rate of train number T1234. The data available in the system only includes details such as train ID, model, manufacturer, year manufactured, capacity, status, and maintenance dates.

[User] What is the current number of passengers waiting at platform 2B at station ABC?

[Assistant] I'm sorry, but I can't provide information on the current number of passengers at a specific platform. The data in the platforms table only includes details like platform number, track number, status, length, and accessibility. For real-time passenger counts, you may need to refer to station monitoring systems or staff reports.

[User] What is the current location of train number Acela 2151?

[Assistant] I'm sorry, but I don't have access to real-time location data for trains. The database only contains static information such as train ID, model, capacity, and maintenance schedules. For current location updates, please check with the train operator or a tracking service.

[User] What is the reason behind the cost variation for maintenance of asset_id 'ASSET456' over the past year?

[Assistant] I'm sorry, but I can't provide information on the reasons behind cost variations for maintenance. The data in the maintenance_records table includes only the cost amount and other basic details of each maintenance record, but it does not contain explanations or factors influencing cost changes.

[User] What is the salary or compensation package for a staff member with the role of Ticket Inspector?

[Assistant] I'm sorry, but I can't provide information about salary or compensation packages as this data is not included in the staff table. For details on salaries, please refer to the HR department or relevant documentation.

[User] What are the ticket prices for trains departing from the station with ID 'ST456'?

[Assistant] I'm sorry, but I can't provide information on ticket prices as this data is not included in the station management database. For ticket pricing, please refer to the ticketing system or contact customer service.


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
Index 'component_inventory'. Mapping: { properties: { inventory_record_id: { type: 'keyword' }, component_id: { type: 'keyword' }, quantity: { type: 'integer' }, location_warehouse: { type: 'keyword' }, location_bin: { type: 'keyword' }, received_date: { type: 'date' }, expiry_date: { type: 'date' }, batch_number: { type: 'keyword' }, last_updated: { type: 'date' } } }. Document _id can be inventory_record_id.

[User] 特定の倉庫にあるコンポーネントの在庫情報を取得したいです。倉庫の場所、ビンの位置、在庫数量、コンポーネントIDを表示してください。

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

[User] 受け取り日が2023年1月1日以降の記録だけに絞り込むことはできますか？

[Assistant] SELECT location_warehouse, location_bin, quantity, component_id FROM component_inventory WHERE location_warehouse = 'specific_warehouse' AND received_date >= '2023-01-01';

[User] さらに、最終更新日が過去1ヶ月以内のものだけを表示するようにできますか？

[Assistant] SELECT location_warehouse, location_bin, quantity, component_id FROM component_inventory WHERE location_warehouse = 'specific_warehouse' AND received_date >= '2023-01-01' AND last_updated >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);

[User] 最後に、コンポーネントIDごとにグループ化して、在庫数量の合計を表示してください。

[Assistant] SELECT location_warehouse, location_bin, component_id, SUM(quantity) AS total_quantity FROM component_inventory WHERE location_warehouse = 'specific_warehouse' AND received_date >= '2023-01-01' AND last_updated >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY component_id, location_warehouse, location_bin;

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

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

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

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

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

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

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

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

[User] 在庫記録の中で、特定のバッチ番号に関連する情報を取得したいです。バッチ番号と在庫数量、倉庫の位置を表示してください。

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number';

[User] 有効期限が2023年12月31日以前のものだけを除外できますか？

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number' AND (expiry_date > '2023-12-31' OR expiry_date IS NULL);

[User] さらに、倉庫の位置が特定の場所に限定されるようにできますか？例えば「Warehouse_A」のみ。

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number' AND (expiry_date > '2023-12-31' OR expiry_date IS NULL) AND location_warehouse = 'Warehouse_A';

[User] 最後に、在庫数量を多い順に並べ替えてください。

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number' AND (expiry_date > '2023-12-31' OR expiry_date IS NULL) AND location_warehouse = 'Warehouse_A' ORDER BY quantity DESC;

[User] What is the purchase price of the components in a specific batch with batch_number 'BATCH123'?

[Assistant] I'm sorry, but I can't provide information on the purchase price of components as this data is not stored in the component_inventory table. If you have other questions or need assistance with data available in the table, such as quantity or location, I'm happy to help.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] List the first name, last name, and email of all customers who live in New York or California.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE state IN ('NY', 'CA');

[User] Find all customers whose email address ends with '@gmail.com'. Please show the customer_id, first name, and email.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com';

[User] Also, restrict this to only customers who are currently 'inactive'.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com' AND status = 'inactive';

[User] How many customers have a non-null phone number in your system?

[Assistant] SELECT COUNT(*) FROM insurance.customers WHERE phone_number IS NOT NULL;

[User] Which cities have more than 10 active customers in the state of Texas? Provide the city name and the customer count.

[Assistant]
SELECT city, COUNT(*) AS customer_count
FROM insurance.customers
WHERE state = 'TX' AND status = 'Active'
GROUP BY city
HAVING COUNT(*) > 10;

[User] How many customers were created in 2023?

[Assistant]
SELECT COUNT(*)
FROM insurance.customers
WHERE EXTRACT(YEAR FROM created_at) = 2023;

[User] Show me the full names and email addresses of all customers who registered after January 1st, 2024.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE created_at > '2024-01-01';

[User] I also want to see their city and state in the result.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01';

[User] Sort the output by the created_at timestamp, newest first.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Limit the result to the top 10 most recently registered customers.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC LIMIT 10;