System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )

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

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

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

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

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

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

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

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

[User] List all room types along with the name of the property they belong to. Show the room type name, property name, and base rate.

[Assistant] SELECT t1.type_name, t2.property_name, t1.base_rate FROM hospitality_technology.room_types AS t1 JOIN hospitality_technology.properties AS t2 ON t1.property_id = t2.property_id

[User] Show all room types that offer 'WiFi' in their amenities.

[Assistant] SELECT room_type_id, property_id, type_name, amenities FROM hospitality_technology.room_types WHERE amenities LIKE '%WiFi%';

[User] Only include those with a base rate below 100 and return the results sorted by base_rate ascending.

[Assistant] SELECT room_type_id, property_id, type_name, amenities, base_rate FROM hospitality_technology.room_types WHERE amenities LIKE '%WiFi%' AND base_rate < 100 ORDER BY base_rate ASC;

[User] Which room types offer both 'Sea View' and 'Balcony' amenities? Show their type names, property IDs, and base rates.

[Assistant] SELECT type_name, property_id, base_rate FROM hospitality_technology.room_types WHERE amenities LIKE '%Sea View%' AND amenities LIKE '%Balcony%';

[User] Can you also include the max occupancy and only return results with a base rate of at least 150?

[Assistant] SELECT type_name, property_id, base_rate, max_occupancy FROM hospitality_technology.room_types WHERE amenities LIKE '%Sea View%' AND amenities LIKE '%Balcony%' AND base_rate >= 150;

[User] Sort the results by max_occupancy descending, and if there's a tie, by base_rate ascending.

[Assistant] SELECT type_name, property_id, base_rate, max_occupancy FROM hospitality_technology.room_types WHERE amenities LIKE '%Sea View%' AND amenities LIKE '%Balcony%' AND base_rate >= 150 ORDER BY max_occupancy DESC, base_rate ASC;

[User] Which bed types are offered in each property and how many different room types are associated with each bed type?

[Assistant] SELECT property_id, bed_type, COUNT(DISTINCT room_type_id) AS room_type_count FROM hospitality_technology.room_types GROUP BY property_id, bed_type;

[User] Now, show only bed types that are available for at least 3 different room types within the same property.

[Assistant] SELECT property_id, bed_type, COUNT(DISTINCT room_type_id) AS room_type_count FROM hospitality_technology.room_types GROUP BY property_id, bed_type HAVING COUNT(DISTINCT room_type_id) >= 3;

[User] Can you list all the room types and their base rates along with the maximum occupancy for each property?

[Assistant] SELECT property_id, type_name, base_rate, max_occupancy FROM hospitality_technology.room_types;

[User] Show only those room types that can accommodate more than 4 people and have a base rate above 200. Order the results by base rate.

[Assistant] SELECT property_id, type_name, base_rate, max_occupancy FROM hospitality_technology.room_types WHERE max_occupancy > 4 AND base_rate > 200 ORDER BY base_rate;

[User] Show me all rooms on floor 4 or above together with their room number, features, and current status.

[Assistant]
SELECT room_id, room_number, features, status
FROM hospitality_technology.rooms
WHERE floor >= 4;

[User] Only include rooms that are marked as non-smoking and sort the results by floor descending.

[Assistant]
SELECT room_id, room_number, features, status, floor
FROM hospitality_technology.rooms
WHERE floor >= 4 AND is_smoking = FALSE
ORDER BY floor DESC;

[User] Which rooms have not been cleaned in over 14 days? Show the room number, property ID, last cleaned date, and status.

[Assistant]
SELECT room_number, property_id, last_cleaned_at, status
FROM hospitality_technology.rooms
WHERE last_cleaned_at < NOW() - INTERVAL '14 days';

[User] Include only those rooms that are currently occupied.

[Assistant]
SELECT room_number, property_id, last_cleaned_at, status
FROM hospitality_technology.rooms
WHERE last_cleaned_at < NOW() - INTERVAL '14 days' AND status = 'Occupied';

[User] Actually, I also want to see which of these rooms are smoking rooms. Add a column indicating whether the room is smoking.

[Assistant]
SELECT room_number, property_id, last_cleaned_at, status, is_smoking
FROM hospitality_technology.rooms
WHERE last_cleaned_at < NOW() - INTERVAL '14 days' AND status = 'Occupied';

[User] List pairs of smoking and non-smoking rooms on the same floor for each property, showing the property_id, floor, smoking room_number, and non_smoking room_number.

[Assistant]
SELECT r1.property_id,
       r1.floor,
       r1.room_number AS smoking_room,
       r2.room_number AS non_smoking_room
FROM hospitality_technology.rooms r1
JOIN hospitality_technology.rooms r2
  ON r1.property_id = r2.property_id
 AND r1.floor = r2.floor
 AND r1.is_smoking = TRUE
 AND r2.is_smoking = FALSE;


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 character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )

[User] Could you provide the route number, the name of the origin location, and the name of the destination location for all routes?

[Assistant] SELECT T1.route_number ,  T2.name ,  T3.name FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id JOIN transportation.locations AS T3 ON T1.destination_location_id  =  T3.location_id

[User] Now, only show routes where the origin location is in the United States and the destination location is in Canada.

[Assistant] SELECT T1.route_number ,  T2.name ,  T3.name FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id JOIN transportation.locations AS T3 ON T1.destination_location_id  =  T3.location_id WHERE T2.country  =  'USA' AND T3.country  =  'Canada'

[User] For each booking, show the booking_id, seat_number, fare, and the city of the origin location for the trip that was booked.

[Assistant]
SELECT b.booking_id, b.seat_number, b.fare, orig.city AS origin_city
FROM transportation.bookings b
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.locations orig ON r.origin_location_id = orig.location_id;

[User] List all routes where the origin and destination are in the same state, showing the route_number, state, origin city, destination city, distance_km, and type.

[Assistant] SELECT r.route_number, o.state_province AS state, o.city AS origin_city, d.city AS destination_city, r.distance_km, r.type FROM transportation.routes r JOIN transportation.locations o ON r.origin_location_id = o.location_id JOIN transportation.locations d ON r.destination_location_id = d.location_id WHERE o.state_province = d.state_province;

[User] List the route number, route type, distance, and the city of the origin location for all routes.

[Assistant] SELECT T1.route_number ,  T1.type ,  T1.distance_km ,  T2.city FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id

[User] Now, restrict the results to only include routes with a distance greater than 500 kilometers.

[Assistant] SELECT T1.route_number ,  T1.type ,  T1.distance_km ,  T2.city FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id WHERE T1.distance_km  >  500

[User] For these long routes, also display the state/province of the destination location and order the results by distance descending.

[Assistant] SELECT T1.route_number ,  T1.type ,  T1.distance_km ,  T2.city AS origin_city ,  T3.state_province AS destination_state FROM transportation.routes AS T1 JOIN transportation.locations AS T2 ON T1.origin_location_id  =  T2.location_id JOIN transportation.locations AS T3 ON T1.destination_location_id  =  T3.location_id WHERE T1.distance_km  >  500 ORDER BY T1.distance_km DESC

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

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

[User] How many passengers were born in each year? Please show the birth year and the count.

[Assistant] SELECT EXTRACT(YEAR FROM date_of_birth) AS birth_year ,  COUNT(*) AS passenger_count FROM transportation.passengers WHERE date_of_birth IS NOT NULL GROUP BY birth_year ORDER BY birth_year

[User] Filter this list to include only years where more than 50 passengers were born, and order by the number of passengers descending.

[Assistant] SELECT EXTRACT(YEAR FROM date_of_birth) AS birth_year ,  COUNT(*) AS passenger_count FROM transportation.passengers WHERE date_of_birth IS NOT NULL GROUP BY birth_year HAVING COUNT(*)  >  50 ORDER BY passenger_count DESC

[User] Show the full name and email of all drivers who have an expired license (license_expiry_date before today).

[Assistant]
SELECT first_name, last_name, email
FROM transportation.drivers
WHERE license_expiry_date < CURRENT_DATE;

[User] How many routes start and end in the same city?

[Assistant]
SELECT COUNT(*) AS same_city_routes
FROM transportation.routes AS r
JOIN transportation.locations AS o ON r.origin_location_id = o.location_id
JOIN transportation.locations AS d ON r.destination_location_id = d.location_id
WHERE o.city = d.city;

[User] Actually, I would like to see each route_number and the city instead of just the count.

[Assistant]
SELECT r.route_number,
       o.city AS common_city
FROM transportation.routes AS r
JOIN transportation.locations AS o ON r.origin_location_id = o.location_id
JOIN transportation.locations AS d ON r.destination_location_id = d.location_id
WHERE o.city = d.city;

[User] Can you also restrict it to routes where distance_km is greater than 100?

[Assistant]
SELECT r.route_number,
       o.city AS common_city
FROM transportation.routes AS r
JOIN transportation.locations AS o ON r.origin_location_id = o.location_id
JOIN transportation.locations AS d ON r.destination_location_id = d.location_id
WHERE o.city = d.city
  AND r.distance_km > 100;

[User] Please sort the results by route_number in ascending order.

[Assistant]
SELECT r.route_number,
       o.city AS common_city
FROM transportation.routes AS r
JOIN transportation.locations AS o ON r.origin_location_id = o.location_id
JOIN transportation.locations AS d ON r.destination_location_id = d.location_id
WHERE o.city = d.city
  AND r.distance_km > 100
ORDER BY r.route_number ASC;

[User] Show each maintenance log with the vehicle ID, make, model, service date, and the cost, including the city where the maintenance was performed.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.make, v.model, ml.service_date, ml.cost, l.city AS maintenance_city
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
LEFT JOIN transportation.locations l ON v.depot_id = l.location_id;

[User] For each booking, show the booking ID, passenger's full name, booking status, and the email of the passenger.

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, b.status, p.email
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Please also include only those passengers who have an email address, and order the results by passenger's last name ascending.

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, b.status, p.email
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE p.email IS NOT NULL
ORDER BY p.last_name 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 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] Can you list all appointments along with the scheduled start time, purpose, and booking method, as well as the employee ID and location ID for each appointment?

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments;

[User] Now, only include appointments that are scheduled for a future date and have the status 'Scheduled'.

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments WHERE scheduled_start_time > CURRENT_TIMESTAMP AND status = 'Scheduled';

[User] How many appointments have a status of 'Cancelled' for each service?

[Assistant] SELECT service_id, COUNT(*) AS cancelled_appointments FROM government_services.appointments WHERE status = 'Cancelled' GROUP BY service_id;

[User] Show me all appointment IDs and their scheduled start times along with the employee ID and service ID for appointments that have been booked using the 'Kiosk' booking method.

[Assistant] SELECT appointment_id, scheduled_start_time, employee_id, service_id FROM government_services.appointments WHERE booking_method = 'Kiosk';

[User] Only include appointments that are currently in 'Scheduled' status.

[Assistant] SELECT appointment_id, scheduled_start_time, employee_id, service_id FROM government_services.appointments WHERE booking_method = 'Kiosk' AND status = 'Scheduled';

[User] List the location ID and the total number of appointments scheduled at each location in the month of February 2024.

[Assistant] SELECT location_id, COUNT(*) AS appointment_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' GROUP BY location_id;

[User] I also want to see only those locations with more than 3 appointments in that month.

[Assistant] SELECT location_id, COUNT(*) AS appointment_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' GROUP BY location_id HAVING COUNT(*) > 3;

[User] Can you add the distinct number of citizens who had appointments at each qualifying location?

[Assistant] SELECT location_id, COUNT(*) AS appointment_count, COUNT(DISTINCT citizen_id) AS distinct_citizen_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' GROUP BY location_id HAVING COUNT(*) > 3;

[User] Now, only include appointments where the booking method used was 'Online'.

[Assistant] SELECT location_id, COUNT(*) AS appointment_count, COUNT(DISTINCT citizen_id) AS distinct_citizen_count FROM government_services.appointments WHERE scheduled_start_time >= '2024-02-01' AND scheduled_start_time < '2024-03-01' AND booking_method = 'Online' GROUP BY location_id HAVING COUNT(*) > 3;

[User] For each location, count the total number of appointments scheduled. Show the location name and the count.

[Assistant] SELECT T2.location_name, COUNT(T1.appointment_id) FROM government_services.appointments AS T1 JOIN locations AS T2 ON T1.location_id = T2.location_id GROUP BY T2.location_name;

[User] Find all appointments where the employee ID is not null and show the appointment ID, employee ID, and the scheduled start time.

[Assistant] SELECT appointment_id, employee_id, scheduled_start_time FROM government_services.appointments WHERE employee_id IS NOT NULL;

[User] List the names of service locations that have had more than 10 appointments with a status of 'Cancelled'.

[Assistant] SELECT T2.location_name FROM government_services.appointments AS T1 JOIN government_services.service_locations AS T2 ON T1.location_id = T2.location_id WHERE T1.status = 'Cancelled' GROUP BY T2.location_name HAVING count(T1.appointment_id) > 10

[User] How many appointments are scheduled to start tomorrow?

[Assistant] SELECT count(*) FROM government_services.appointments WHERE DATE(scheduled_start_time) = CURRENT_DATE + INTERVAL '1 day'

[User] Find pairs of appointment IDs that were scheduled at the same location. Show the IDs of the two appointments.

[Assistant] SELECT t1.appointment_id, t2.appointment_id FROM appointments AS t1 JOIN appointments AS t2 ON t1.location_id = t2.location_id WHERE t1.appointment_id < t2.appointment_id;

[User] Restrict the results to pairs where both appointments have the status 'Scheduled'.

[Assistant] SELECT t1.appointment_id, t2.appointment_id FROM appointments AS t1 JOIN appointments AS t2 ON t1.location_id = t2.location_id WHERE t1.appointment_id < t2.appointment_id AND t1.status = 'Scheduled' AND t2.status = 'Scheduled';


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 manufacturing.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, skill_certifications text, hire_date date, assigned_line_id text, employment_status text, supervisor_employee_id text )

[User] What is the total number of vacation days taken by employee with ID 'EMP101' in the past year?

[Assistant] I'm sorry, but I can't provide information on the vacation days taken by an employee as this data is not stored in the current table structure.

[User] What is the reason for the termination of employee with ID 'EMP789'?

[Assistant] I'm sorry, but I can't provide information on the reason for an employee's termination as it is not stored in the current database table.

[User] What is the current address of the employee with ID 'EMP234'?

[Assistant] I'm sorry, but I can't provide the current address of an employee as this information is not stored in the database table.

[User] What is the performance review score for employee with ID 'EMP456' for the last quarter?

[Assistant] I'm sorry, but I can't assist with information about performance review scores as this data is not included in the employees table.

[User] What is the current salary of employee with ID 'EMP123'?

[Assistant] I'm sorry, but I can't provide information about an employee's salary as it is not included in the data available in the 'employees' table.


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 manufacturing.aircraft_models ( model_id text, model_name text, manufacturer text, passenger_capacity integer, max_range_km integer, engine_type text, wingspan_m numeric, status text, first_flight_date date )

[User] What are the safety ratings or crash statistics for the Boeing 787 Dreamliner?

[Assistant] I'm sorry, but I don't have access to safety ratings or crash statistics for specific aircraft models like the Boeing 787 Dreamliner. My data is limited to the information in the aircraft_models table, which includes details such as model name, manufacturer, passenger capacity, and technical specifications. For safety-related information, I recommend consulting official aviation authorities or safety reports.

[User] What are the environmental impact assessments for the production of the Airbus A350 model?

[Assistant] I'm sorry, but I don't have access to data regarding the environmental impact assessments for the production of specific aircraft models like the Airbus A350. My information is limited to the technical specifications and basic details stored in the database, such as model name, manufacturer, and capacity. If you have a question related to the available data, I'd be happy to assist.

[User] What are the fuel consumption rates per hour for the Boeing 747-8 model?

[Assistant] I'm sorry, but I can't provide information on the fuel consumption rates for the Boeing 747-8 model as this data is not included in the aircraft_models table. The table contains details such as model name, manufacturer, passenger capacity, and other specifications, but fuel consumption data is not available. If you have another question or need assistance with something else related to the table, I'm happy to help.

[User] What are the maintenance costs for a specific aircraft model like the Airbus A320?

[Assistant] I'm sorry, but I don't have access to data regarding maintenance costs for specific aircraft models such as the Airbus A320. The information in the database is limited to details like model name, manufacturer, passenger capacity, and technical specifications. For maintenance cost information, you may need to consult with the manufacturer or a maintenance service provider.

[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 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.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)

[User] List employees whose job title is different from their manager's job title, showing the employee's full name and their manager's full name.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.job_title <> m.job_title;

[User] Only include employees from the 'IT' department.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.job_title <> m.job_title AND e.department = 'IT';

[User] Add the job titles for both the employee and manager, and order by employee's last name.

[Assistant] SELECT e.first_name, e.last_name, e.job_title AS employee_job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.job_title <> m.job_title AND e.department = 'IT' ORDER BY e.last_name ASC;

[User] Give me a count of employees hired in each department for employees currently active or terminated.

[Assistant] SELECT department, status, COUNT(employee_id) AS employee_count FROM financial_services.employees WHERE status IN ('Active', 'Terminated') GROUP BY department, status;

[User] For the terminated employees in those departments, also include the average tenure in days, considering only those with a termination date.

[Assistant] SELECT department, SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN status = 'Terminated' THEN 1 ELSE 0 END) AS terminated_count, AVG(CASE WHEN status = 'Terminated' AND termination_date IS NOT NULL THEN EXTRACT(EPOCH FROM (termination_date - hire_date)) / 86400.0 ELSE NULL END) AS avg_terminated_tenure_days FROM financial_services.employees GROUP BY department;

[User] Only show departments with more than 5 active employees and order by the active employee count descending.

[Assistant] SELECT department, SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN status = 'Terminated' THEN 1 ELSE 0 END) AS terminated_count, AVG(CASE WHEN status = 'Terminated' AND termination_date IS NOT NULL THEN EXTRACT(EPOCH FROM (termination_date - hire_date)) / 86400.0 ELSE NULL END) AS avg_terminated_tenure_days FROM financial_services.employees GROUP BY department HAVING SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) > 5 ORDER BY active_count DESC;

[User] Report the number of employees for each department, broken down by their employment status.

[Assistant] SELECT department, status, COUNT(*) AS employee_count FROM financial_services.employees GROUP BY department, status

[User] Only show results for departments that have at least 10 employees in total (across all statuses).

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status;

[User] Exclude any groups where the employee count is less than 5.

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status
HAVING COUNT(*) >= 5;

[User] Finally, order the results by department name descending.

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status
HAVING COUNT(*) >= 5
ORDER BY department DESC;

[User] Provide a list of all employees and their corresponding managers. Please display the full name for both the employee and their manager.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id

[User] Restrict the list to only include employees who are currently in 'Active' status.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.status = 'Active'

[User] For each department, what is the earliest and latest employee hire date?

[Assistant] SELECT department, MIN(hire_date) AS earliest_hire_date, MAX(hire_date) AS latest_hire_date FROM financial_services.employees GROUP BY department;

[User] Include the total number of employees for each department.

[Assistant] SELECT department, MIN(hire_date) AS earliest_hire_date, MAX(hire_date) AS latest_hire_date, COUNT(employee_id) AS total_employees FROM financial_services.employees GROUP BY department;

[User] Only show departments with more than 3 employees.

[Assistant] SELECT department, MIN(hire_date) AS earliest_hire_date, MAX(hire_date) AS latest_hire_date, COUNT(employee_id) AS total_employees FROM financial_services.employees GROUP BY department HAVING COUNT(employee_id) > 3;

[User] Show me the full names and job titles of all employees along with their managers’ full names in the same result.

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.job_title, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Only include employees whose managers are from a different department.

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.job_title, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department IS DISTINCT FROM m.department;

[User] Can you add the departments of both the employee and the manager to the result?

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.department AS employee_department, e.job_title, m.first_name || ' ' || m.last_name AS manager_name, m.department AS manager_department FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department IS DISTINCT FROM m.department;

[User] Now, filter the list to only show employees hired after 2020-01-01.

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.department AS employee_department, e.job_title, m.first_name || ' ' || m.last_name AS manager_name, m.department AS manager_department FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department IS DISTINCT FROM m.department AND e.hire_date > '2020-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 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 )
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] For each case, show the total amount of all invoices and the number of scheduled appointments. Only include cases that have both an invoice and at least one appointment.

[Assistant]
SELECT i.case_id, SUM(i.total_amount) AS total_invoice_amount, COUNT(DISTINCT a.appointment_id) AS scheduled_appointments
FROM legal_services.invoices i
JOIN legal_services.appointments a ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
GROUP BY i.case_id;

[User] Actually, can you split the scheduled appointments count by each client within the case? So I want case_id, client_id, total_invoice_amount, and count of scheduled appointments per client.

[Assistant]
SELECT i.case_id, a.client_id, SUM(i.total_amount) AS total_invoice_amount, COUNT(a.appointment_id) AS scheduled_appointments
FROM legal_services.invoices i
JOIN legal_services.appointments a ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
GROUP BY i.case_id, a.client_id;

[User] Now, please only include cases where the total_invoice_amount is greater than 10000.

[Assistant]
SELECT i.case_id, a.client_id, SUM(i.total_amount) AS total_invoice_amount, COUNT(a.appointment_id) AS scheduled_appointments
FROM legal_services.invoices i
JOIN legal_services.appointments a ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
GROUP BY i.case_id, a.client_id
HAVING SUM(i.total_amount) > 10000;

[User] Which clients have appointments scheduled for a case that also has at least one invoice issued? Please show the client_id, appointment_id, appointment start_time, related case_id, and invoice_number.

[Assistant]
SELECT a.client_id, a.appointment_id, a.start_time, a.case_id, i.invoice_number
FROM legal_services.appointments a
JOIN legal_services.invoices i ON a.case_id = i.case_id
WHERE a.status = 'Scheduled';

[User] Find the total number of distinct lawyers and distinct documents in the database.

[Assistant] SELECT (SELECT COUNT(DISTINCT lawyer_id) FROM legal_services.lawyers) AS distinct_lawyer_count, (SELECT COUNT(DISTINCT document_id) FROM legal_services.documents) AS distinct_document_count;

[User] Get all documents uploaded by lawyers who are partners.

[Assistant]
SELECT d.document_id, d.document_name, d.case_id, d.upload_timestamp
FROM legal_services.documents d
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.is_partner = true;

[User] Actually, I want to see for each document the appointment subjects that are related to the same case along with the document name.

[Assistant]
SELECT d.document_name, a.subject
FROM legal_services.documents d
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
JOIN legal_services.appointments a ON d.case_id = a.case_id
WHERE l.is_partner = true;

[User] Only include documents that were uploaded in 2024.

[Assistant]
SELECT d.document_name, a.subject
FROM legal_services.documents d
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
JOIN legal_services.appointments a ON d.case_id = a.case_id
WHERE l.is_partner = true AND EXTRACT(YEAR FROM d.upload_timestamp) = 2024;

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

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

[User] List the first name, last name, and specialization of all lawyers who have uploaded at least one document.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM legal_services.lawyers AS T1 JOIN legal_services.documents AS T2 ON T1.lawyer_id = T2.uploaded_by_lawyer_id GROUP BY T1.lawyer_id, T1.first_name, T1.last_name, T1.specialization;

[User] Show me case numbers, names, and related invoice numbers.

[Assistant] SELECT T1.case_number, T1.case_name, T2.invoice_number FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id;

[User] Only include cases that are currently 'Open'.

[Assistant] SELECT T1.case_number, T1.case_name, T2.invoice_number FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'Open';

[User] Also, only show invoices that have a 'Paid' status.

[Assistant] SELECT T1.case_number, T1.case_name, T2.invoice_number FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'Open' AND T2.status = 'Paid';

[User] List all case numbers, names, and types.

[Assistant] SELECT case_number, case_name, case_type FROM legal_services.cases;

[User] Only include cases opened after 2023.

[Assistant] SELECT case_number, case_name, case_type FROM legal_services.cases WHERE date_opened >= '2024-01-01';

[User] Also show the date opened and the lead lawyer ID.

[Assistant] SELECT case_number, case_name, case_type, date_opened, lead_lawyer_id FROM legal_services.cases WHERE date_opened >= '2024-01-01';

[User] Order the results by date opened descending.

[Assistant] SELECT case_number, case_name, case_type, date_opened, lead_lawyer_id FROM legal_services.cases WHERE date_opened >= '2024-01-01' ORDER BY date_opened DESC;

[User] List all invoices with a total_amount less than 1000 and show the associated client's ID and case ID.

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount
FROM legal_services.invoices
WHERE total_amount < 1000;

[User] Actually, can you also include the invoice status and order the results by total_amount ascending?

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount, status
FROM legal_services.invoices
WHERE total_amount < 1000
ORDER BY total_amount ASC;

[User] Now, only show invoices where the status is 'Sent' or 'Overdue', and include the issue_date as well.

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount, status, issue_date
FROM legal_services.invoices
WHERE total_amount < 1000 AND status IN ('Sent', 'Overdue')
ORDER BY total_amount ASC;

[User] Show me the total hours worked and total amount billed for each case that has associated invoices, along with the case ID and invoice number.

[Assistant]
SELECT t.case_id, i.invoice_number, SUM(t.hours_spent) AS total_hours, SUM(t.hours_spent * t.billing_rate) AS total_billed_amount
FROM legal_services.time_entries t
JOIN legal_services.invoices i ON t.invoice_id = i.invoice_id
GROUP BY t.case_id, i.invoice_number;


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
// db.createCollection('stations')
// Optional: Add unique index: db.stations.createIndex({ station_id: 1 }, { unique: true })
{
  _id: ObjectId(), // Auto-generated MongoDB ID
  station_id: "station_xyz", // String (unique identifier, corresponds to SQL PK)
  station_name: "Grand Central Terminal", // String
  city: "New York", // String
  state_province: "NY", // String
  country_code: "USA", // String
  address: "89 E 42nd St, New York, NY 10017", // String
  timezone: "America/New_York", // String
  number_of_platforms: 44, // Int32
  created_at: ISODate("2023-01-15T10:00:00Z"), // Date
  last_updated_at: ISODate("2023-10-28T15:30:00Z") // Date
}
// db.createCollection('trains')
// Optional: db.trains.createIndex({ train_id: 1 }, { unique: true })
// Optional: db.trains.createIndex({ train_number: 1 }, { unique: true })
{
  _id: ObjectId(),
  train_id: "train_789", // String (unique)
  train_number: "Acela 2151", // String (unique)
  model: "Siemens Velaro", // String
  manufacturer: "Siemens", // String
  year_manufactured: 2010, // Int32
  capacity: 304, // Int32
  status: "Active", // String ('Active', 'Maintenance', 'Retired')
  last_maintenance_date: ISODate("2023-09-15"), // Date (Date part only relevant)
  next_maintenance_date: ISODate("2024-03-15") // Date (Date part only relevant)
}
// db.createCollection('bookings')
// Optional: db.bookings.createIndex({ booking_id: 1 }, { unique: true })
// Optional: db.bookings.createIndex({ passenger_id: 1 })
// Optional: db.bookings.createIndex({ schedule_id: 1 })
{
  _id: ObjectId(),
  booking_id: "book_zyx", // String (unique)
  passenger_id: "pass_pqr", // String (references passengers.passenger_id)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  booking_datetime: ISODate("2024-04-15T14:30:00Z"), // Date
  status: "Confirmed", // String ('Confirmed', 'Cancelled', 'Pending')
  total_price: 150.75, // Decimal128 or Double
  currency_code: "USD", // String
  special_requests: "Wheelchair assistance required at origin" // String
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}

[User] Can you help me count the total number of active staff members in the database?

[Assistant] db.staff.countDocuments({ is_active: true });

[User] Can you assist me in finding all staff members assigned to a specific station with station_id 'station_xyz', including the station details and their roles?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            'primary_station_id': 'station_xyz'
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 1
        }
    }
]);

[User] I noticed that some staff might not have a primary station assigned. Can you revise the query to include staff who might be associated with the station in other ways, if possible?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            $or: [
                { 'primary_station_id': 'station_xyz' },
                { 'primary_station_id': null }
            ]
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 1
        }
    }
]);

[User] Can you help me retrieve the details of all bookings for a specific station with station_id 'station_xyz', including the associated schedule and passenger information?

[Assistant]
db.bookings.aggregate([
    {
        $lookup: {
            from: 'schedules',
            localField: 'schedule_id',
            foreignField: 'schedule_id',
            as: 'schedule_details'
        }
    },
    {
        $lookup: {
            from: 'passengers',
            localField: 'passenger_id',
            foreignField: 'passenger_id',
            as: 'passenger_details'
        }
    },
    {
        $lookup: {
            from: 'stations',
            localField: 'schedule_details.origin_station_id',
            foreignField: 'station_id',
            as: 'origin_station'
        }
    },
    {
        $match: {
            'origin_station.station_id': 'station_xyz'
        }
    },
    {
        $project: {
            booking_id: 1,
            booking_datetime: 1,
            status: 1,
            total_price: 1,
            'schedule_details.schedule_id': 1,
            'schedule_details.departure_datetime': 1,
            'passenger_details.first_name': 1,
            'passenger_details.last_name': 1,
            'origin_station.station_name': 1
        }
    }
]);

[User] Can you modify the query to include only bookings with a status of 'Pending'?

[Assistant]
db.bookings.aggregate([
    {
        $lookup: {
            from: 'schedules',
            localField: 'schedule_id',
            foreignField: 'schedule_id',
            as: 'schedule_details'
        }
    },
    {
        $lookup: {
            from: 'passengers',
            localField: 'passenger_id',
            foreignField: 'passenger_id',
            as: 'passenger_details'
        }
    },
    {
        $lookup: {
            from: 'stations',
            localField: 'schedule_details.origin_station_id',
            foreignField: 'station_id',
            as: 'origin_station'
        }
    },
    {
        $match: {
            'origin_station.station_id': 'station_xyz',
            status: 'Pending'
        }
    },
    {
        $project: {
            booking_id: 1,
            booking_datetime: 1,
            status: 1,
            total_price: 1,
            'schedule_details.schedule_id': 1,
            'schedule_details.departure_datetime': 1,
            'passenger_details.first_name': 1,
            'passenger_details.last_name': 1,
            'origin_station.station_name': 1
        }
    }
]);

[User] Can you help me get the total number of operational platforms across all stations?

[Assistant] db.platforms.countDocuments({ status: 'Operational' });


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.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)

[User] Show the first and last name of each passenger along with the total number of bookings they have made.

[Assistant] SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count FROM transportation.passengers p LEFT JOIN transportation.bookings b ON p.passenger_id = b.passenger_id GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Now, only include passengers who have made more than 5 bookings.

[Assistant] SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id GROUP BY p.passenger_id, p.first_name, p.last_name HAVING COUNT(b.booking_id) > 5;

[User] List all passengers born before 1990 with their first and last names and email addresses.

[Assistant] SELECT first_name, last_name, email FROM transportation.passengers WHERE date_of_birth < '1990-01-01';

[User] Can you also include their phone numbers in the result?

[Assistant] SELECT first_name, last_name, email, phone_number FROM transportation.passengers WHERE date_of_birth < '1990-01-01';

[User] Now, filter it further to only passengers who have an email address registered.

[Assistant] SELECT first_name, last_name, email, phone_number FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND email IS NOT NULL;

[User] Sort the final result by last name in ascending order.

[Assistant] SELECT first_name, last_name, email, phone_number FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND email IS NOT NULL ORDER BY last_name ASC;

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

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

[User] Show me the list of all passengers who do not have a loyalty program membership, including their passenger ID and the date their record was created.

[Assistant] SELECT passenger_id, created_at FROM transportation.passengers WHERE loyalty_program_id IS NULL;

[User] Show me the first name, last name, and email address for passengers who have made a booking with 'Completed' status.

[Assistant] SELECT DISTINCT p.first_name, p.last_name, p.email FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id WHERE b.status = 'Completed';

[User] From this list, can you also include the booking time and fare for these completed bookings?

[Assistant] SELECT p.first_name, p.last_name, p.email, b.booking_time, b.fare FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id WHERE b.status = 'Completed';

[User] Now, order the results by booking time in descending order and only show bookings with a fare greater than 200.

[Assistant] SELECT p.first_name, p.last_name, p.email, b.booking_time, b.fare FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id WHERE b.status = 'Completed' AND b.fare > 200 ORDER BY b.booking_time DESC;

[User] Please show me the first name, last name, and date of birth for all passengers born before January 1, 1990.

[Assistant] SELECT first_name, last_name, date_of_birth FROM transportation.passengers WHERE date_of_birth < '1990-01-01';

[User] From that group, could you further filter to only include those whose records were added on or after January 1, 2022?

[Assistant] SELECT first_name, last_name, date_of_birth FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND created_at >= '2022-01-01';

[User] Finally, order the results of this refined list by their date of birth in ascending order.

[Assistant] SELECT first_name, last_name, date_of_birth FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND created_at >= '2022-01-01' ORDER BY date_of_birth ASC;

[User] Show me all bookings with the passenger's full name and the booking status.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Please only include bookings where the status is 'Completed'.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status = 'Completed';

[User] Add the fare amount and booking time for each completed booking.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status, b.fare, b.booking_time
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status = 'Completed';

[User] Limit the results to the latest 10 completed bookings by booking_time.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status, b.fare, b.booking_time
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status = 'Completed'
ORDER BY b.booking_time DESC
LIMIT 10;

[User] For each passenger, list their email along with the total amount spent on fares across all their bookings.

[Assistant]
SELECT p.passenger_id, p.email, SUM(b.fare) AS total_fare_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.email;

[User] List the number of bookings made by each loyalty program member. Show the loyalty_program_id and the booking count.

[Assistant]
SELECT p.loyalty_program_id, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE p.loyalty_program_id IS NOT NULL
GROUP BY p.loyalty_program_id;

[User] Show a list of all trips along with the first and last names of all passengers who have booked on those trips. Each result should have the trip_id, passenger first name and last name.

[Assistant]
SELECT t.trip_id, p.first_name, p.last_name
FROM transportation.trips t
JOIN transportation.bookings b ON t.trip_id = b.trip_id
JOIN transportation.passengers p ON b.passenger_id = p.passenger_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 insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )

[User] Show all policies that started before January 1, 2022, including policy_id, policy_number, start_date, and status.

[Assistant]
SELECT policy_id, policy_number, start_date, status
FROM insurance.policies
WHERE start_date < '2022-01-01';

[User] How many claims were reported in the last 90 days?

[Assistant] SELECT COUNT(*) FROM claims WHERE reported_date >= CURRENT_DATE - INTERVAL '90 days'

[User] List all policies that have at least one beneficiary with a 'Child' relationship, showing policy number, policy status, and the number of child beneficiaries for that policy.

[Assistant] SELECT T1.policy_number, T1.status, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status HAVING COUNT(T2.beneficiary_id) >= 1

[User] Can you also include the total premium amount for these policies?

[Assistant] SELECT T1.policy_number, T1.status, T1.premium_amount, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status, T1.premium_amount HAVING COUNT(T2.beneficiary_id) >= 1

[User] For each agent, show their agent_id, first and last name, and the total estimated loss for all claims they have handled as a claim handler.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, SUM(c.estimated_loss) AS total_estimated_loss
FROM insurance.agents a
JOIN insurance.claims c ON a.agent_id = c.claim_handler_id
GROUP BY a.agent_id, a.first_name, a.last_name;

[User] Actually, please only show agents with a total estimated loss above 100000.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, SUM(c.estimated_loss) AS total_estimated_loss
FROM insurance.agents a
JOIN insurance.claims c ON a.agent_id = c.claim_handler_id
GROUP BY a.agent_id, a.first_name, a.last_name
HAVING SUM(c.estimated_loss) > 100000;

[User] Show me the incident date, estimated loss, and the associated product name for all claims with an estimated loss greater than 20000.

[Assistant]
SELECT c.incident_date, c.estimated_loss, p.product_name
FROM insurance.claims c
JOIN insurance.policies pol ON c.policy_id = pol.policy_id
JOIN insurance.insurance_products p ON pol.product_id = p.product_id
WHERE c.estimated_loss > 20000;

[User] Show me claim IDs and the file names of any documents associated with claims filed before January 1, 2024.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01';

[User] Only include documents where the file size is less than 1 MB.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576;

[User] Add the document type to the results and sort by file size ascending.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

[User] Sorry, I got an error about NULL file sizes. Please exclude records where the file size is NULL.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes IS NOT NULL
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

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

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

[User] Which insurance products have had a policy issued in 2024, and what is the name and type of those products? Show the product_id, product_name, and product_type.

[Assistant]
SELECT DISTINCT ip.product_id, ip.product_name, ip.product_type
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.start_date >= '2024-01-01';

[User] Can you also include the base premium of each product and only show policies where the base premium is greater than 2500?

[Assistant]
SELECT DISTINCT ip.product_id, ip.product_name, ip.product_type, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.start_date >= '2024-01-01'
  AND ip.base_premium > 2500;

[User] Actually, I want to see only products that are currently active, and order the results by base premium descending.

[Assistant]
SELECT DISTINCT ip.product_id, ip.product_name, ip.product_type, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE p.start_date >= '2024-01-01'
  AND ip.base_premium > 2500
  AND ip.is_active = true
ORDER BY ip.base_premium DESC;

[User] Show me all policies that use insurance products of type 'health', and display the policy_number, start_date, and the product's name.

[Assistant]
SELECT p.policy_number, p.start_date, ip.product_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE ip.product_type = 'health';

[User] Add the base premium of each insurance product and only show policies with a deductible higher than 500.

[Assistant]
SELECT p.policy_number, p.start_date, ip.product_name, ip.base_premium
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
WHERE ip.product_type = 'health'
  AND p.deductible > 500;

[User] Show policy numbers and the name of the insurance product for all policies with a coverage limit greater than 500,000.

[Assistant] SELECT p.policy_number, ip.product_name FROM insurance.policies p JOIN insurance.insurance_products ip ON p.product_id = ip.product_id WHERE p.coverage_limit > 500000;

[User] Could you also include the product type and the base premium for these policies?

[Assistant] SELECT p.policy_number, ip.product_name, ip.product_type, ip.base_premium FROM insurance.policies p JOIN insurance.insurance_products ip ON p.product_id = ip.product_id WHERE p.coverage_limit > 500000;

[User] Actually, only show policies whose status is 'active' and sort the results by policy number.

[Assistant] SELECT p.policy_number, ip.product_name, ip.product_type, ip.base_premium FROM insurance.policies p JOIN insurance.insurance_products ip ON p.product_id = ip.product_id WHERE p.coverage_limit > 500000 AND p.status = 'active' ORDER BY p.policy_number;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )

[User] List the order ID, type, and quantity for all orders placed using the wallet with ID 'wallet123'.

[Assistant] SELECT order_id, order_type, quantity FROM orders WHERE wallet_id = 'wallet123'

[User] Also include the creation date of the wallet that placed the order.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T1.wallet_id = 'wallet123'

[User] Actually, ignore the specific wallet ID. Show the same information for all orders, but only include orders placed using wallets created before '2023-12-31'.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at < '2023-12-31'

[User] Filter that list further to only show 'sell' orders.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at < '2023-12-31' AND T1.order_type = 'sell'

[User] Show the number of wallets created each month in 2024, showing the year and month.

[Assistant] SELECT EXTRACT(YEAR FROM created_at) AS year, EXTRACT(MONTH FROM created_at) AS month, COUNT(*) FROM wallets WHERE EXTRACT(YEAR FROM created_at) = 2024 GROUP BY 1, 2 ORDER BY 1, 2

[User] List all orders, showing order ID, type, quantity, and price, that were placed using a wallet created after '2024-01-01'.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T1.price FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at > '2024-01-01'

[User] From that list, only show orders with 'completed' status.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T1.price FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at > '2024-01-01' AND T1.status = 'completed'

[User] List all wallets created before '2024-01-01', including the wallet_id, user_id, and creation date.

[Assistant] SELECT wallet_id, user_id, created_at FROM wallets WHERE created_at < '2024-01-01';

[User] Now, from that list, only include wallets belonging to users who also have created at least one wallet on or after '2024-01-01'.

[Assistant] SELECT w1.wallet_id, w1.user_id, w1.created_at FROM wallets w1 JOIN wallets w2 ON w1.user_id = w2.user_id WHERE w1.created_at < '2024-01-01' AND w2.created_at >= '2024-01-01' GROUP BY w1.wallet_id, w1.user_id, w1.created_at;

[User] For these users, show their user ID, the creation date of their earliest wallet created *before* '2024-01-01', and the creation date of their latest wallet created *on or after* '2024-01-01'.

[Assistant] SELECT user_id, MIN(CASE WHEN created_at < '2024-01-01' THEN created_at ELSE NULL END) AS earliest_before_2024, MAX(CASE WHEN created_at >= '2024-01-01' THEN created_at ELSE NULL END) AS latest_from_2024 FROM wallets GROUP BY user_id HAVING MIN(CASE WHEN created_at < '2024-01-01' THEN created_at ELSE NULL END) IS NOT NULL AND MAX(CASE WHEN created_at >= '2024-01-01' THEN created_at ELSE NULL END) IS NOT NULL;

[User] How many such users are there?

[Assistant] SELECT COUNT(DISTINCT user_id) FROM ( SELECT user_id FROM wallets WHERE created_at < '2024-01-01' GROUP BY user_id ) t1 JOIN ( SELECT user_id FROM wallets WHERE created_at >= '2024-01-01' GROUP BY user_id ) t2 ON t1.user_id = t2.user_id;

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

[User] List pairs of wallets created on the same day but belonging to different users. Show the wallet IDs, user IDs, and creation dates for both wallets in each pair.

[Assistant] SELECT w1.wallet_id AS wallet1_id, w1.user_id AS user1_id, w1.created_at AS wallet1_created_at, w2.wallet_id AS wallet2_id, w2.user_id AS user2_id, w2.created_at AS wallet2_created_at FROM wallets w1 JOIN wallets w2 ON DATE(w1.created_at) = DATE(w2.created_at) AND w1.user_id != w2.user_id AND w1.wallet_id < w2.wallet_id;

[User] Filter the previous results to only include pairs where both wallet addresses start with '0x'.

[Assistant] SELECT w1.wallet_id AS wallet1_id, w1.user_id AS user1_id, w1.created_at AS wallet1_created_at, w2.wallet_id AS wallet2_id, w2.user_id AS user2_id, w2.created_at AS wallet2_created_at FROM wallets w1 JOIN wallets w2 ON DATE(w1.created_at) = DATE(w2.created_at) AND w1.user_id != w2.user_id AND w1.wallet_id < w2.wallet_id WHERE w1.address LIKE '0x%' AND w2.address LIKE '0x%';

[User] Show each order with its previous order timestamp for the same user.

[Assistant]
SELECT o.order_id, o.user_id, o.created_at AS current_time, MAX(prev.created_at) AS previous_time
FROM trading_platform.orders o
LEFT JOIN trading_platform.orders prev
  ON o.user_id = prev.user_id
  AND prev.created_at < o.created_at
GROUP BY o.order_id, o.user_id, o.created_at
ORDER BY o.user_id, o.created_at;

[User] Filter to include only those orders where the gap between current_time and previous_time exceeds one day.

[Assistant]
SELECT *
FROM (
  SELECT o.order_id,
         o.user_id,
         o.created_at AS current_time,
         MAX(prev.created_at) AS previous_time
  FROM trading_platform.orders o
  LEFT JOIN trading_platform.orders prev
    ON o.user_id = prev.user_id
    AND prev.created_at < o.created_at
  GROUP BY o.order_id, o.user_id, o.created_at
) t
WHERE t.current_time - t.previous_time > INTERVAL '1 day'
ORDER BY t.user_id, t.current_time;

[User] Count the number of orders in each status.

[Assistant]
SELECT status, COUNT(*) AS order_count
FROM trading_platform.orders
GROUP BY status;

[User] For each user, calculate the total value of 'buy' and 'sell' orders (quantity * price).

[Assistant]
SELECT b.user_id,
       b.total_buy_value,
       s.total_sell_value
FROM (
  SELECT user_id,
         SUM(quantity * price) AS total_buy_value
  FROM trading_platform.orders
  WHERE order_type = 'buy'
  GROUP BY user_id
) b
JOIN (
  SELECT user_id,
         SUM(quantity * price) AS total_sell_value
  FROM trading_platform.orders
  WHERE order_type = 'sell'
  GROUP BY user_id
) s
  ON b.user_id = s.user_id;

[User] Include users who have only buys or only sells, showing missing values as zero.

[Assistant]
SELECT COALESCE(b.user_id, s.user_id) AS user_id,
       COALESCE(b.total_buy_value, 0) AS total_buy_value,
       COALESCE(s.total_sell_value, 0) AS total_sell_value
FROM (
  SELECT user_id,
         SUM(quantity * price) AS total_buy_value
  FROM trading_platform.orders
  WHERE order_type = 'buy'
  GROUP BY user_id
) b
FULL OUTER JOIN (
  SELECT user_id,
         SUM(quantity * price) AS total_sell_value
  FROM trading_platform.orders
  WHERE order_type = 'sell'
  GROUP BY user_id
) s
  ON b.user_id = s.user_id;

[User] Also add the count of completed orders per user.

[Assistant]
SELECT u.user_id,
       u.total_buy_value,
       u.total_sell_value,
       COALESCE(c.completed_count, 0) AS completed_count
FROM (
  SELECT COALESCE(b.user_id, s.user_id) AS user_id,
         COALESCE(b.total_buy_value, 0) AS total_buy_value,
         COALESCE(s.total_sell_value, 0) AS total_sell_value
  FROM (
    SELECT user_id,
           SUM(quantity * price) AS total_buy_value
    FROM trading_platform.orders
    WHERE order_type = 'buy'
    GROUP BY user_id
  ) b
  FULL OUTER JOIN (
    SELECT user_id,
           SUM(quantity * price) AS total_sell_value
    FROM trading_platform.orders
    WHERE order_type = 'sell'
    GROUP BY user_id
  ) s
    ON b.user_id = s.user_id
) u
LEFT JOIN (
  SELECT user_id,
         COUNT(*) AS completed_count
  FROM trading_platform.orders
  WHERE status = 'completed'
  GROUP BY user_id
) c
  ON u.user_id = c.user_id;

[User] Order results by total_buy_value descending and limit to 10.

[Assistant]
SELECT u.user_id,
       u.total_buy_value,
       u.total_sell_value,
       COALESCE(c.completed_count, 0) AS completed_count
FROM (
  SELECT COALESCE(b.user_id, s.user_id) AS user_id,
         COALESCE(b.total_buy_value, 0) AS total_buy_value,
         COALESCE(s.total_sell_value, 0) AS total_sell_value
  FROM (
    SELECT user_id,
           SUM(quantity * price) AS total_buy_value
    FROM trading_platform.orders
    WHERE order_type = 'buy'
    GROUP BY user_id
  ) b
  FULL OUTER JOIN (
    SELECT user_id,
           SUM(quantity * price) AS total_sell_value
    FROM trading_platform.orders
    WHERE order_type = 'sell'
    GROUP BY user_id
  ) s
    ON b.user_id = s.user_id
) u
LEFT JOIN (
  SELECT user_id,
         COUNT(*) AS completed_count
  FROM trading_platform.orders
  WHERE status = 'completed'
  GROUP BY user_id
) c
  ON u.user_id = c.user_id
ORDER BY u.total_buy_value DESC
LIMIT 10;

[User] Show me pairs of wallets that belong to the same user, listing the wallet_id, user_id, address, and created_at for the earlier and later wallet in each pair.

[Assistant]
SELECT w1.user_id,
       w1.wallet_id AS earlier_wallet,
       w1.address AS earlier_address,
       w1.created_at AS earlier_created_at,
       w2.wallet_id AS later_wallet,
       w2.address AS later_address,
       w2.created_at AS later_created_at
FROM trading_platform.wallets w1
JOIN trading_platform.wallets w2
  ON w1.user_id = w2.user_id
 AND w1.created_at < w2.created_at;

[User] Now only include pairs where the later wallet was created more than 30 days after the earlier one.

[Assistant]
SELECT w1.user_id,
       w1.wallet_id AS earlier_wallet,
       w1.address AS earlier_address,
       w1.created_at AS earlier_created_at,
       w2.wallet_id AS later_wallet,
       w2.address AS later_address,
       w2.created_at AS later_created_at
FROM trading_platform.wallets w1
JOIN trading_platform.wallets w2
  ON w1.user_id = w2.user_id
 AND w2.created_at > w1.created_at + INTERVAL '30 days';


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.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Show me all KYC audit records for user ID 'user_abc_123'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123';

[User] From those, list only the ones with status 'pending'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending';

[User] Order the results by the review date in ascending order.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at ASC;

[User] Just show the latest pending audit for that user, displaying the user_id, status, and reviewed_at date.

[Assistant] SELECT user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at DESC LIMIT 1;

[User] Show me the top 5 users with the most KYC audits, along with their latest audit status.

[Assistant] SELECT user_id, status, COUNT(*) as audit_count FROM trading_platform.kyc_audit GROUP BY user_id, status ORDER BY audit_count DESC LIMIT 5;

[User] Now modify the query to show only users whose latest KYC status was rejected.

[Assistant] WITH latest_audit AS (SELECT user_id, status, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY reviewed_at DESC) as rn FROM trading_platform.kyc_audit) SELECT user_id, status FROM latest_audit WHERE rn = 1 AND status = 'rejected' LIMIT 5;

[User] Actually, I want to see the count of rejected audits per user instead of just the latest status.

[Assistant] SELECT user_id, COUNT(*) as rejected_count FROM trading_platform.kyc_audit WHERE status = 'rejected' GROUP BY user_id ORDER BY rejected_count DESC LIMIT 5;

[User] List all users who have had their KYC status changed from 'approved' to 'rejected', along with the timestamps of both audits.

[Assistant] SELECT a.user_id, a.reviewed_at AS approved_time, r.reviewed_at AS rejected_time FROM trading_platform.kyc_audit a JOIN trading_platform.kyc_audit r ON a.user_id = r.user_id WHERE a.status = 'approved' AND r.status = 'rejected' AND a.reviewed_at < r.reviewed_at AND NOT EXISTS (SELECT 1 FROM trading_platform.kyc_audit x WHERE x.user_id = a.user_id AND x.reviewed_at > a.reviewed_at AND x.reviewed_at < r.reviewed_at);

[User] Now modify the query to only include cases where the status change happened within 30 days.

[Assistant] SELECT a.user_id, a.reviewed_at AS approved_time, r.reviewed_at AS rejected_time FROM trading_platform.kyc_audit a JOIN trading_platform.kyc_audit r ON a.user_id = r.user_id WHERE a.status = 'approved' AND r.status = 'rejected' AND a.reviewed_at < r.reviewed_at AND r.reviewed_at <= a.reviewed_at + INTERVAL '30 days' AND NOT EXISTS (SELECT 1 FROM trading_platform.kyc_audit x WHERE x.user_id = a.user_id AND x.reviewed_at > a.reviewed_at AND x.reviewed_at < r.reviewed_at);

[User] Can you also include the users' email addresses and calculate the number of days between approval and rejection?

[Assistant] SELECT a.user_id, u.email, a.reviewed_at AS approved_time, r.reviewed_at AS rejected_time, EXTRACT(DAY FROM (r.reviewed_at - a.reviewed_at)) AS days_between FROM trading_platform.kyc_audit a JOIN trading_platform.kyc_audit r ON a.user_id = r.user_id JOIN trading_platform.users u ON a.user_id = u.user_id WHERE a.status = 'approved' AND r.status = 'rejected' AND a.reviewed_at < r.reviewed_at AND r.reviewed_at <= a.reviewed_at + INTERVAL '30 days' AND NOT EXISTS (SELECT 1 FROM trading_platform.kyc_audit x WHERE x.user_id = a.user_id AND x.reviewed_at > a.reviewed_at AND x.reviewed_at < r.reviewed_at);

[User] Show assets of type 'token', including their name, symbol, and any associated metadata key and value.

[Assistant] SELECT t1.name, t1.symbol, t2.key, t2.value FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token';

[User] For the results from the previous query, only include metadata entries where the key is 'website'.

[Assistant] SELECT t1.name, t1.symbol, t2.key, t2.value FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token' AND t2.key = 'website';

[User] Instead of listing metadata, count how many assets of type 'token' have a metadata entry with key 'website'.

[Assistant] SELECT COUNT(DISTINCT t1.asset_id) FROM trading_platform.assets AS t1 INNER JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token' AND t2.key = 'website';

[User] Also, provide the total count of assets with type 'token'.

[Assistant] SELECT COUNT(DISTINCT t1.asset_id) FILTER (WHERE t2.key = 'website') AS token_with_website_metadata_count, COUNT(DISTINCT t1.asset_id) AS total_token_count FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token';

[User] Count the number of assets for each asset type.

[Assistant] SELECT type, COUNT(*) FROM trading_platform.assets GROUP BY type;

[User] Show me all users who had their KYC rejected along with when their review was completed.

[Assistant] SELECT user_id, reviewed_at FROM trading_platform.kyc_audit WHERE status = 'rejected';

[User] List the names of all DApps whose description contains the word 'auction' along with the user IDs of anyone who has had a KYC audit.

[Assistant]
SELECT d.name AS dapp_name, k.user_id
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
ORDER BY d.name, k.user_id;

[User] Just show KYC audits with a status that is not 'approved'.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id;

[User] Actually, I want to include the reviewed_at time for each audit result too.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] Filter further to only show audits reviewed after January 1, 2024.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
  AND k.reviewed_at > '2024-01-01'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] Show me the names and URLs of all DApps, and for each DApp, list the KYC status and last review date for all users who have an audit entry.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
ORDER BY d.name, k.user_id;

[User] I only want DApps whose name includes the word 'market', and for KYC audits, show only those with status 'approved'.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.name ILIKE '%market%' AND k.status = 'approved'
ORDER BY d.name, k.user_id;

[User] How many unique users have a KYC audit record with status 'pending'?

[Assistant]
SELECT COUNT(DISTINCT user_id) AS pending_kyc_users
FROM trading_platform.kyc_audit
WHERE status = 'pending';

[User] Show a list of all asset names along with the current KYC status of each user, including the asset symbol. Join the assets and kyc_audit tables.

[Assistant]
SELECT a.name AS asset_name, a.symbol, k.user_id, k.status AS kyc_status
FROM trading_platform.assets a
JOIN trading_platform.kyc_audit k ON 1=1

[User] I only want the result for users whose KYC status is 'approved' and for assets where the symbol is at least 3 characters long.

[Assistant]
SELECT a.name AS asset_name, a.symbol, k.user_id, k.status AS kyc_status
FROM trading_platform.assets a
JOIN trading_platform.kyc_audit k ON 1=1
WHERE k.status = 'approved' AND LENGTH(a.symbol) >= 3


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_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 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, 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 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 integer NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
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_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) 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, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

[User] List the token IDs and names of all NFTs minted by the wallet '0x1234...' on Ethereum.

[Assistant] SELECT token_id, name FROM nft_metadata WHERE minter = '0x1234...' AND blockchain = 'Ethereum';

[User] Now, for each of those NFTs, show also the collection name by joining to nft_collections.

[Assistant] SELECT nm.token_id, nm.name, nc.name AS collection_name FROM nft_metadata nm LEFT JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum' WHERE nm.minter = '0x1234...' AND nm.blockchain = 'Ethereum';

[User] Only include NFTs where the rarity rank is below 100.

[Assistant] SELECT nm.token_id, nm.name, nc.name AS collection_name FROM nft_metadata nm LEFT JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum' WHERE nm.minter = '0x1234...' AND nm.blockchain = 'Ethereum' AND nm.rarity_rank < 100;

[User] Show me all ERC20 tokens (from token_metas) with a total supply over 1,000,000, including their contract address and symbol.

[Assistant] SELECT contract_address, symbol FROM token_metas WHERE is_erc20 = 1 AND CAST(total_supply AS FLOAT) > 1000000;

[User] Please also give me the name and decimals for each token.

[Assistant] SELECT contract_address, symbol, name, decimals FROM token_metas WHERE is_erc20 = 1 AND CAST(total_supply AS FLOAT) > 1000000;

[User] Add the latest price for each token by joining with token_prices_latest.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tm.symbol = tpl.symbol WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS FLOAT) > 1000000;

[User] I'm interested only in tokens where the price is over $0.5.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tm.symbol = tpl.symbol WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS FLOAT) > 1000000 AND tpl.price > 0.5;

[User] For all NFT collections on the Ethereum blockchain, show me the collection name and the current floor price. Sort by floor price descending.

[Assistant] SELECT name, floor_price FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Include also the collection symbol and the number of tokens in each collection.

[Assistant] SELECT name, symbol, floor_price, token_count FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Can you also show the owner of each collection in the result?

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Now only include collections whose floor price is greater than 1 ETH.

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' AND CAST(floor_price AS FLOAT) > 1 AND floor_price_symbol = 'ETH' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Show me wallet addresses that hold more than 1000 of any ERC20 token, along with the token symbol and amount.

[Assistant] SELECT eb.wallet_address, tm.symbol, eb.amount FROM erc20_balances eb JOIN token_metas tm ON eb.contract_address = tm.contract_address WHERE CAST(eb.amount AS decimal) > 1000;

[User] Can you join this with the token_prices_latest table to include the current price of each token and sort by amount in descending order?

[Assistant] SELECT eb.wallet_address, tm.symbol, eb.amount, tpl.price FROM erc20_balances eb JOIN token_metas tm ON eb.contract_address = tm.contract_address JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE CAST(eb.amount AS decimal) > 1000 ORDER BY CAST(eb.amount AS decimal) DESC;

[User] Show me the object ID, coin type, and balance for all SUI coins where the status is 'active'.

[Assistant] SELECT object_id, coin_type, balance FROM sui_coins WHERE status = 'active'

[User] Also, include the owner address in the result.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active'

[User] Filter the results to only show coins where the balance is greater than '100000000000'.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND CAST(balance AS NUMERIC) > 100000000000

[User] Sort the results by balance in descending order and limit the output to 10.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND CAST(balance AS NUMERIC) > 100000000000 ORDER BY CAST(balance AS NUMERIC) DESC LIMIT 10

[User] Find the contract address and name for all NFT collections listed on the 'Ethereum' blockchain.

[Assistant] SELECT contract_address, name FROM nft_collections WHERE blockchain = 'Ethereum'

[User] For these collections, can you show the count of unique wallet addresses holding NFTs in each collection by joining with nft_holders?

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name

[User] Please filter the results to only include collections that have more than 100 unique holders.

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name HAVING COUNT(DISTINCT T2.wallet_address) > 100

[User] List all ERC20 token symbols and their latest prices for tokens where the total supply is greater than '100000000000000000000'.

[Assistant] SELECT T1.symbol, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000

[User] Can you also include the token name and decimals in the result?

[Assistant] SELECT T1.symbol, T1.name, T1.decimals, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000

[User] Now, only show tokens where the latest price is above 100.

[Assistant] SELECT T1.symbol, T1.name, T1.decimals, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000 AND T2.price > 100

[User] Finally, sort the results by price descending and limit to the top 10.

[Assistant] SELECT T1.symbol, T1.name, T1.decimals, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000 AND T2.price > 100 ORDER BY T2.price DESC LIMIT 10

[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.1.

[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.1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] I think there's an error in your query - it should be 'tpl.symbol' not 'tm.symbol'. Also, can you add the decimals to the results?

[Assistant] SELECT tm.name, tm.contract_address, tm.decimals, tm.total_supply, tpl.symbol, 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.1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] Now filter these results to only show tokens with decimals equal to 18.

[Assistant] SELECT tm.name, tm.contract_address, tm.decimals, tm.total_supply, tpl.symbol, 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.1 AND tm.decimals = 18 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] List the top 5 Avalanche tokens by total transfer volume in token_activities_avalanche.

[Assistant]
SELECT tick, SUM(amt) AS total_volume
FROM token_activities_avalanche
GROUP BY tick
ORDER BY total_volume DESC
LIMIT 5;

[User] Also include the count of distinct senders and receivers for each token.

[Assistant]
SELECT tick,
       SUM(amt) AS total_volume,
       COUNT(DISTINCT from_address) AS sender_count,
       COUNT(DISTINCT to_address) AS receiver_count
FROM token_activities_avalanche
GROUP BY tick
ORDER BY total_volume DESC
LIMIT 5;

[User] Join with token_balances_avalanche to include the total_supply for each token and filter for transfers over 100 units in the last 7 days.

[Assistant]
SELECT a.tick,
       SUM(a.amt) AS total_volume,
       COUNT(DISTINCT a.from_address) AS sender_count,
       COUNT(DISTINCT a.to_address) AS receiver_count,
       b.total_supply
FROM token_activities_avalanche a
JOIN token_balances_avalanche b
  ON a.tick = b.tick
 AND b.block_number = (
   SELECT MAX(block_number)
   FROM token_balances_avalanche
   WHERE tick = a.tick
 )
WHERE a.amt > 100
  AND a.block_timestamp >= NOW() - INTERVAL '7 days'
GROUP BY a.tick, b.total_supply
ORDER BY total_volume DESC
LIMIT 5;

[User] Show me all NFT collections on Ethereum with more than 10,000 tokens, including their names and contract addresses.

[Assistant] SELECT name, contract_address FROM nft_collections WHERE blockchain = 'Ethereum' AND token_count > 10000;

[User] Can you also include the floor price and filter to only show ERC721 collections?

[Assistant] SELECT name, contract_address, floor_price FROM nft_collections WHERE blockchain = 'Ethereum' AND token_count > 10000 AND erc_type = 'ERC721';

[User] Now join this with the token_prices table to include the current price of the floor price token.

[Assistant] SELECT nc.name, nc.contract_address, nc.floor_price, tp.price FROM nft_collections nc JOIN token_prices tp ON nc.floor_price_contract = tp.address WHERE nc.blockchain = 'Ethereum' AND nc.token_count > 10000 AND nc.erc_type = 'ERC721';