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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)

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

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

[User] Find employees who work in the same department as their manager. Display the employee's full name, the manager's full name, and the department they share.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_full_name, m.first_name || ' ' || m.last_name AS manager_full_name, e.department FROM government_services.employees AS e JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id WHERE e.department = m.department;

[User] Find employees who were hired after their managers. Display the employee's full name, their hire date, the manager's full name, and the manager's hire date.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.hire_date AS employee_hire_date, m.first_name || ' ' || m.last_name AS manager_name, m.hire_date AS manager_hire_date FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.hire_date > m.hire_date;

[User] List the first name and last name of each employee, along with the first and last name of their manager.

[Assistant] SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM government_services.employees AS e LEFT JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id;

[User] I need a list of departments and the number of current employees in each department.

[Assistant]
SELECT department,
       COUNT(*) AS employee_count
FROM government_services.employees
WHERE termination_date IS NULL
GROUP BY department;

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

[Assistant]
SELECT department,
       COUNT(*) AS employee_count
FROM government_services.employees
WHERE termination_date IS NULL
GROUP BY department
HAVING COUNT(*) > 3;

[User] Now include the earliest hire date for each department as well.

[Assistant]
SELECT department,
       COUNT(*) AS employee_count,
       MIN(hire_date) AS earliest_hire_date
FROM government_services.employees
WHERE termination_date IS NULL
GROUP BY department
HAVING COUNT(*) > 3;

[User] Also exclude employees whose access_level is 'Intern'.

[Assistant]
SELECT department,
       COUNT(*) AS employee_count,
       MIN(hire_date) AS earliest_hire_date
FROM government_services.employees
WHERE termination_date IS NULL
  AND access_level <> 'Intern'
GROUP BY department
HAVING COUNT(*) > 3;

[User] List all distinct job titles present in the organization.

[Assistant] SELECT DISTINCT job_title FROM government_services.employees;

[User] Could you show me each employee's full name along with their manager's full name?

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

[User] Actually, only include employees who were hired after January 1, 2020.

[Assistant]
SELECT e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       m.employee_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name
FROM government_services.employees e
LEFT JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE e.hire_date > '2020-01-01';

[User] List the first name, last name, and job title of each employee, along with the job title of their manager.

[Assistant] SELECT e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.job_title AS employee_job_title, m.job_title AS manager_job_title FROM government_services.employees AS e LEFT JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id;

[User] Which department has the highest number of employees currently employed?

[Assistant] SELECT department FROM government_services.employees WHERE termination_date IS NULL GROUP BY department ORDER BY COUNT(*) DESC LIMIT 1;

[User] How many employees were hired in each year?

[Assistant] SELECT EXTRACT(YEAR FROM hire_date) AS hire_year ,  COUNT(*) AS employee_count FROM employees GROUP BY hire_year

[User] Show only the years where more than 50 employees were hired.

[Assistant] SELECT EXTRACT(YEAR FROM hire_date) AS hire_year ,  COUNT(*) AS employee_count FROM employees GROUP BY hire_year HAVING COUNT(*)  >  50

[User] For these years, also show the number of employees with 'Admin' access level.

[Assistant] SELECT EXTRACT(YEAR FROM hire_date) AS hire_year ,  COUNT(*) AS employee_count ,  COUNT(CASE WHEN access_level  =  'Admin' THEN 1 ELSE NULL END) AS admin_count FROM employees GROUP BY hire_year HAVING COUNT(*)  >  50

[User] Order the results by the total number of employees hired in the year, descending.

[Assistant] SELECT EXTRACT(YEAR FROM hire_date) AS hire_year ,  COUNT(*) AS employee_count ,  COUNT(CASE WHEN access_level  =  'Admin' THEN 1 ELSE NULL END) AS admin_count FROM employees GROUP BY hire_year HAVING COUNT(*)  >  50 ORDER BY employee_count DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List all staff members who are not managers, including their first name, last name, position, and the name of the property they work at.

[Assistant] SELECT T1.first_name, T1.last_name, T1.position, T2.property_name FROM hospitality_technology.staff AS T1 INNER JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.staff_id NOT IN (SELECT DISTINCT manager_id FROM hospitality_technology.staff WHERE manager_id IS NOT NULL);

[User] Show each room type with their maximum occupancy and the total number of rooms of that type across all properties.

[Assistant]
SELECT rt.room_type_id, rt.type_name, rt.max_occupancy, COUNT(r.room_id) AS total_rooms
FROM hospitality_technology.room_types rt
LEFT JOIN hospitality_technology.rooms r ON rt.room_type_id = r.room_type_id
GROUP BY rt.room_type_id, rt.type_name, rt.max_occupancy;

[User] Only include room types where maximum occupancy is greater than 2.

[Assistant]
SELECT rt.room_type_id, rt.type_name, rt.max_occupancy, COUNT(r.room_id) AS total_rooms
FROM hospitality_technology.room_types rt
LEFT JOIN hospitality_technology.rooms r ON rt.room_type_id = r.room_type_id
WHERE rt.max_occupancy > 2
GROUP BY rt.room_type_id, rt.type_name, rt.max_occupancy;

[User] Also, display the property name for each room type.

[Assistant]
SELECT rt.room_type_id, rt.type_name, rt.max_occupancy, COUNT(r.room_id) AS total_rooms, p.property_name
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
LEFT JOIN hospitality_technology.rooms r ON rt.room_type_id = r.room_type_id
WHERE rt.max_occupancy > 2
GROUP BY rt.room_type_id, rt.type_name, rt.max_occupancy, p.property_name;

[User] For each staff member who placed a service order, show their full name and the total revenue generated from those orders.

[Assistant] SELECT S.first_name, S.last_name, SUM(SO.total_price) AS total_generated_revenue FROM hospitality_technology.staff AS S JOIN hospitality_technology.service_orders AS SO ON S.staff_id = SO.staff_id_ordered GROUP BY S.staff_id, S.first_name, S.last_name;

[User] Only show staff members whose placed orders generated more than 500 in total revenue.

[Assistant] SELECT S.first_name, S.last_name, SUM(SO.total_price) AS total_generated_revenue FROM hospitality_technology.staff AS S JOIN hospitality_technology.service_orders AS SO ON S.staff_id = SO.staff_id_ordered GROUP BY S.staff_id, S.first_name, S.last_name HAVING SUM(SO.total_price) > 500;

[User] List each property with its manager's full name and the count of currently available services it offers.

[Assistant]
SELECT p.property_id,
       p.property_name,
       CONCAT(m.first_name, ' ', m.last_name) AS manager_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.staff m ON p.manager_staff_id = m.staff_id
LEFT JOIN hospitality_technology.services s ON p.property_id = s.property_id AND s.is_available = TRUE
GROUP BY p.property_id, p.property_name, manager_name;

[User] Only include properties offering at least 5 available services.

[Assistant]
SELECT p.property_id,
       p.property_name,
       CONCAT(m.first_name, ' ', m.last_name) AS manager_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.staff m ON p.manager_staff_id = m.staff_id
LEFT JOIN hospitality_technology.services s ON p.property_id = s.property_id AND s.is_available = TRUE
GROUP BY p.property_id, p.property_name, manager_name
HAVING COUNT(s.service_id) >= 5;

[User] Also order the results by service_count descending.

[Assistant]
SELECT p.property_id,
       p.property_name,
       CONCAT(m.first_name, ' ', m.last_name) AS manager_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.staff m ON p.manager_staff_id = m.staff_id
LEFT JOIN hospitality_technology.services s ON p.property_id = s.property_id AND s.is_available = TRUE
GROUP BY p.property_id, p.property_name, manager_name
HAVING COUNT(s.service_id) >= 5
ORDER BY service_count DESC;

[User] List all payments processed in the last 90 days, showing payment ID, amount, currency, method, and status.

[Assistant] SELECT payment_id, amount, currency_code, payment_method, status FROM hospitality_technology.payments WHERE payment_timestamp >= CURRENT_DATE - INTERVAL '90 day';

[User] Now, only show payments with status 'Failed' or 'Canceled'.

[Assistant] SELECT payment_id, amount, currency_code, payment_method, status FROM hospitality_technology.payments WHERE payment_timestamp >= CURRENT_DATE - INTERVAL '90 day' AND (status = 'Failed' OR status = 'Canceled');

[User] List the names of properties and the number of services they offer in the 'Spa' department.

[Assistant] SELECT P.property_name, COUNT(S.service_id) AS spa_service_count FROM hospitality_technology.properties AS P JOIN hospitality_technology.services AS S ON P.property_id = S.property_id WHERE S.department = 'Spa' GROUP BY P.property_id, P.property_name;

[User] Only show properties that offer more than 2 'Spa' services.

[Assistant] SELECT P.property_name, COUNT(S.service_id) AS spa_service_count FROM hospitality_technology.properties AS P JOIN hospitality_technology.services AS S ON P.property_id = S.property_id WHERE S.department = 'Spa' GROUP BY P.property_id, P.property_name HAVING COUNT(S.service_id) > 2;

[User] Instead of the count, can you show me the average price of 'Spa' services for those properties, along with the property name?

[Assistant] SELECT P.property_name, AVG(S.price) AS average_spa_price FROM hospitality_technology.properties AS P JOIN hospitality_technology.services AS S ON P.property_id = S.property_id WHERE S.department = 'Spa' GROUP BY P.property_id, P.property_name HAVING COUNT(S.service_id) > 2;

[User] Show me all staff members who are currently active, along with their property name and position.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.position, p.property_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_active = TRUE;

[User] Show all rooms that are on floor 3.

[Assistant] SELECT room_id, property_id, room_number FROM hospitality_technology.rooms WHERE floor = 3;

[User] For these rooms, include the property name and room number.

[Assistant] SELECT r.room_number, p.property_name FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id WHERE r.floor = 3;

[User] Also, include the type name and current status for each room.

[Assistant] SELECT r.room_number, p.property_name, rt.type_name, r.status FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id JOIN hospitality_technology.room_types AS rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id WHERE r.floor = 3;

[User] List all active staff members who are managers, along with their hire dates and email addresses.

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

[User] Now, include only managers who were hired in the last 5 years.

[Assistant] SELECT staff_id, first_name, last_name, position, hire_date, work_email FROM hospitality_technology.staff WHERE is_active = true AND position = 'Manager' AND hire_date >= CURRENT_DATE - INTERVAL '5 years';

[User] The query should also show how many staff members each manager supervises.

[Assistant] SELECT s1.staff_id, s1.first_name, s1.last_name, s1.position, s1.hire_date, s1.work_email, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s1 LEFT JOIN hospitality_technology.staff s2 ON s1.staff_id = s2.manager_id WHERE s1.is_active = true AND s1.position = 'Manager' AND s1.hire_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY s1.staff_id, s1.first_name, s1.last_name, s1.position, s1.hire_date, s1.work_email;

[User] Actually, I only need managers who supervise at least 5 staff members, and order them by supervised staff count in descending order.

[Assistant] SELECT s1.staff_id, s1.first_name, s1.last_name, s1.position, s1.hire_date, s1.work_email, COUNT(s2.staff_id) AS supervised_staff_count FROM hospitality_technology.staff s1 LEFT JOIN hospitality_technology.staff s2 ON s1.staff_id = s2.manager_id WHERE s1.is_active = true AND s1.position = 'Manager' AND s1.hire_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY s1.staff_id, s1.first_name, s1.last_name, s1.position, s1.hire_date, s1.work_email HAVING COUNT(s2.staff_id) >= 5 ORDER BY supervised_staff_count DESC;

[User] Show me all service orders for spa services in the last month, including the guest name and staff who delivered the service.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month';

[User] Now, include only orders with a total price over $100.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100;

[User] The query is missing the property name. Can you include that as well?

[Assistant] SELECT so.order_id, g.first_name, g.last_name, p.property_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id JOIN hospitality_technology.properties p ON so.property_id = p.property_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100;

[User] Actually, I need to see the reservation ID and check-in date for these orders too, and order by total price in descending order.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, p.property_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, r.reservation_id, r.check_in_date, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id JOIN hospitality_technology.properties p ON so.property_id = p.property_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100 ORDER BY so.total_price DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] For each vehicle that appears in both the maintenance logs and fuel logs tables, calculate the total maintenance cost and the total fuel cost. Display the vehicle ID and these two total costs.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(T2.total_cost) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id

[User] Now, only include vehicles where the total maintenance cost exceeds 5000.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(T2.total_cost) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id HAVING SUM(T1.cost)  >  5000

[User] Also, only consider fuel log entries from the year 2023 for the fuel cost calculation.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(CASE WHEN STRFTIME('%Y', T2.log_timestamp) = '2023' THEN T2.total_cost ELSE 0 END) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id HAVING SUM(T1.cost)  >  5000

[User] Show me the first name, last name, and email address for all passengers who are part of the loyalty program with ID 'Gold'.

[Assistant] SELECT first_name ,  last_name ,  email FROM transportation.passengers WHERE loyalty_program_id  =  'Gold'

[User] Now, narrow this list to only include those passengers whose record was created after January 1, 2023.

[Assistant] SELECT first_name ,  last_name ,  email FROM transportation.passengers WHERE loyalty_program_id  =  'Gold' AND created_at  >  '2023-01-01'

[User] List all routes with a total distance traveled greater than 10,000 km, showing the route number and total distance accumulated across all trips on that route.

[Assistant]
SELECT r.route_number, SUM(r.distance_km) AS total_distance
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number
HAVING SUM(r.distance_km) > 10000;

[User] Can you also include the total fuel cost recorded for trips on each qualifying route?

[Assistant]
SELECT r.route_number, SUM(r.distance_km) AS total_distance, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY r.route_number
HAVING SUM(r.distance_km) > 10000;

[User] Add the number of trips on each route and order the results by total fuel cost descending.

[Assistant]
SELECT r.route_number, COUNT(t.trip_id) AS trip_count, SUM(r.distance_km) AS total_distance, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY r.route_number
HAVING SUM(r.distance_km) > 10000
ORDER BY total_fuel_cost DESC;

[User] Show me the total fuel cost for each trip along with the trip's route number and the type of the route.

[Assistant]
SELECT t.trip_id, r.route_number, r.type, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, r.route_number, r.type;

[User] Modify the query to only include trips on routes of type 'Express', and show results ordered by total fuel cost descending.

[Assistant]
SELECT t.trip_id, r.route_number, r.type, SUM(f.total_cost) AS total_fuel_cost
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
WHERE r.type = 'Express'
GROUP BY t.trip_id, r.route_number, r.type
ORDER BY total_fuel_cost DESC;

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

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

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

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

[User] Show me the number of vehicles for each make in the system.

[Assistant]
SELECT make, COUNT(*) AS vehicle_count
FROM transportation.vehicles
GROUP BY make

[User] Now, only show makes that have more than 3 vehicles and order them by vehicle_count descending.

[Assistant]
SELECT make, COUNT(*) AS vehicle_count
FROM transportation.vehicles
GROUP BY make
HAVING COUNT(*) > 3
ORDER BY vehicle_count DESC

[User] List all bookings with the first and last name of the passenger and trip_id.

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

[User] Add the date when the booking was made and the booking status.

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

[User] Filter to only show bookings where the status is either 'Pending' or 'Confirmed'.

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status IN ('Pending', 'Confirmed');

[User] Can you sort the results by booking_time in descending order and limit to the 10 most recent?

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status IN ('Pending', 'Confirmed')
ORDER BY b.booking_time DESC
LIMIT 10;

[User] For each trip, can you show the trip_id, number of passengers, and the make and model of the assigned vehicle?

[Assistant]
SELECT b.trip_id, COUNT(b.passenger_id) AS passenger_count, v.make, v.model
FROM transportation.bookings b
JOIN transportation.vehicles v ON b.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs WHERE vehicle_id = v.vehicle_id
)
GROUP BY b.trip_id, v.make, v.model;

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

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

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

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


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.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )

[User] Count the number of logs for each action type.

[Assistant]
SELECT action,
       COUNT(*) AS count
FROM trading_platform.logs
GROUP BY action;

[User] For each user, retrieve their most recent log entry, including the action and timestamp.

[Assistant] SELECT l.user_id, l.action, l.logged_at FROM trading_platform.logs l JOIN (SELECT user_id, MAX(logged_at) AS max_time FROM trading_platform.logs GROUP BY user_id) m ON l.user_id = m.user_id AND l.logged_at = m.max_time;

[User] Exclude any logs where the action contains the word 'error'.

[Assistant] SELECT l.user_id, l.action, l.logged_at FROM trading_platform.logs l JOIN (SELECT user_id, MAX(logged_at) AS max_time FROM trading_platform.logs GROUP BY user_id) m ON l.user_id = m.user_id AND l.logged_at = m.max_time WHERE l.action NOT ILIKE '%error%';

[User] Count the number of logs for each distinct action type.

[Assistant] SELECT action, COUNT(*) AS log_count FROM trading_platform.logs GROUP BY action;

[User] Get the total number of logs per user for July 2024.

[Assistant]
SELECT user_id,
       COUNT(*) AS log_count
FROM trading_platform.logs
WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
GROUP BY user_id;

[User] Only include users who have at least 20 logs in that period.

[Assistant]
SELECT user_id,
       COUNT(*) AS log_count
FROM trading_platform.logs
WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
GROUP BY user_id
HAVING COUNT(*) >= 20;

[User] Also include the earliest log date for each of those users.

[Assistant]
SELECT t.user_id,
       t.log_count,
       e.first_log
FROM (
    SELECT user_id,
           COUNT(*) AS log_count
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
    HAVING COUNT(*) >= 20
) t
JOIN (
    SELECT user_id,
           MIN(logged_at) AS first_log
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
) e ON t.user_id = e.user_id;

[User] Sort by log_count descending and limit to top 5 users.

[Assistant]
SELECT t.user_id,
       t.log_count,
       e.first_log
FROM (
    SELECT user_id,
           COUNT(*) AS log_count
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
    HAVING COUNT(*) >= 20
) t
JOIN (
    SELECT user_id,
           MIN(logged_at) AS first_log
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
) e ON t.user_id = e.user_id
ORDER BY t.log_count DESC
LIMIT 5;

[User] Show the earliest and latest timestamp recorded in the logs table.

[Assistant] SELECT MIN(logged_at), MAX(logged_at) FROM trading_platform.logs;

[User] For each user, list all the distinct actions they have performed along with the count of each action.

[Assistant] SELECT user_id, action, COUNT(*) FROM trading_platform.logs GROUP BY user_id, action ORDER BY user_id, action;

[User] Now, only show users who have performed more than 5 distinct actions.

[Assistant] SELECT user_id FROM trading_platform.logs GROUP BY user_id HAVING COUNT(DISTINCT action) > 5 ORDER BY user_id;

[User] Show me all log entries for user ID 'user123'.

[Assistant] SELECT log_id, user_id, action, details, logged_at FROM trading_platform.logs WHERE user_id = 'user123' ORDER BY logged_at DESC;

[User] Show only the logs for that user where the action contains 'trade' and the log entry was created after '2024-07-01'.

[Assistant] SELECT log_id, user_id, action, details, logged_at FROM trading_platform.logs WHERE user_id = 'user123' AND action LIKE '%trade%' AND logged_at > '2024-07-01' ORDER BY logged_at DESC;

[User] Instead of listing the logs, just count how many logs for user 'user123' meet the criteria (action contains 'trade' and logged after '2024-07-01').

[Assistant] SELECT COUNT(*) FROM trading_platform.logs WHERE user_id = 'user123' AND action LIKE '%trade%' AND logged_at > '2024-07-01';

[User] Now, for that user ('user123') and timeframe (after '2024-07-01'), count how many unique action types containing 'trade' they performed.

[Assistant] SELECT COUNT(DISTINCT action) FROM trading_platform.logs WHERE user_id = 'user123' AND action LIKE '%trade%' AND logged_at > '2024-07-01';

[User] Show the number of users registered each month for 2024.

[Assistant]
SELECT
  date_trunc('month', created_at) AS month,
  COUNT(*) AS user_count
FROM trading_platform.users
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;

[User] List the user IDs and usernames for all users who registered in the year 2024.

[Assistant] SELECT user_id, username FROM trading_platform.users WHERE created_at >= '2024-01-01 00:00:00' AND created_at < '2025-01-01 00:00:00';

[User] From that list, also filter to only include users whose username starts with 'alpha'.

[Assistant] SELECT user_id, username FROM trading_platform.users WHERE created_at >= '2024-01-01 00:00:00' AND created_at < '2025-01-01 00:00:00' AND username LIKE 'alpha%';

[User] Show the email address and the creation date for every user, ordered by their username alphabetically.

[Assistant] SELECT email, created_at FROM trading_platform.users ORDER BY username ASC;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id text PRIMARY KEY, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )

[User] What are the specific tools or equipment used during the maintenance with record_id 'REC456'?

[Assistant] I'm sorry, but I can't provide information about the specific tools or equipment used during a maintenance record. The data in the maintenance_records table does not include details about tools or equipment used.

[User] What are the personal contact details of the staff member associated with staff_id 'STAFF789' who worked on a specific maintenance record?

[Assistant] I'm sorry, but I can't provide personal contact details of staff members as this information is not stored in the maintenance_records table and is outside the scope of the available data.

[User] What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

[Assistant] I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories.

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

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

[User] What are the qualifications or training history of the staff member who performed the maintenance with record_id 'REC123'?

[Assistant] I'm sorry, but I can't provide information about the qualifications or training history of staff members as this data is not stored in the maintenance_records table. This table only contains details about maintenance activities, such as asset information, maintenance type, dates, and costs. If you have another question or need assistance with data available in this table, I'm happy to help.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the payment ID, amount, and the name of the service for all payments associated with services in the 'Licensing' category.

[Assistant] SELECT p.payment_id, p.amount, s.service_name FROM government_services.payments p JOIN government_services.services s ON p.service_id = s.service_id WHERE s.category = 'Licensing';

[User] For each type of entity a notification can be related to, how many notifications have been successfully sent?

[Assistant] SELECT related_entity_type, COUNT(*) AS sent_notification_count FROM government_services.notifications WHERE status = 'Sent' GROUP BY related_entity_type;

[User] What is the average number of appointments assigned per employee for each job title?

[Assistant] SELECT e.job_title, CAST(COUNT(a.appointment_id) AS REAL) / COUNT(DISTINCT e.employee_id) AS average_appointments_per_employee FROM government_services.employees e LEFT JOIN government_services.appointments a ON e.employee_id = a.employee_id GROUP BY e.job_title;

[User] Show the count of applications submitted per day for the last 7 days. Include the date and application_count, ordered by date ascending.

[Assistant]
SELECT CAST(submitted_at AS date) AS date,
       COUNT(*) AS application_count
FROM government_services.applications
WHERE submitted_at >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY CAST(submitted_at AS date)
ORDER BY date ASC;

[User] For each application, show the application ID, the full name of the assigned employee, and the number of payments made for that application.

[Assistant]
SELECT a.application_id, CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name, COUNT(p.payment_id) AS payment_count
FROM government_services.applications a
LEFT JOIN government_services.payments p ON a.application_id = p.application_id
LEFT JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
GROUP BY a.application_id, e.first_name, e.last_name;

[User] For each service location, show the location name, city, and the number of appointments scheduled at that location.

[Assistant]
SELECT sl.location_name, sl.city, COUNT(a.appointment_id) AS appointment_count
FROM government_services.service_locations sl
LEFT JOIN government_services.appointments a ON sl.location_id = a.location_id
GROUP BY sl.location_name, sl.city;

[User] Find the citizen ID and document ID for documents with a 'Proof of Address' document type, for citizens who have also received at least one notification. Show distinct combinations.

[Assistant] SELECT DISTINCT d.citizen_id, d.document_id FROM government_services.documents AS d JOIN government_services.notifications AS n ON d.citizen_id = n.citizen_id WHERE d.document_type = 'Proof of Address';

[User] List the full names and job titles of all employees who have not verified any documents.

[Assistant] SELECT e.first_name, e.last_name, e.job_title FROM government_services.employees AS e LEFT JOIN government_services.documents AS d ON e.employee_id = d.verified_by_employee_id WHERE d.document_id IS NULL;

[User] Provide a count of appointments grouped by the booking method.

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

[User] For each service category, show the category and the number of distinct citizens who have scheduled at least one appointment for a service in that category. Order the results by the number of citizens in descending order.

[Assistant]
SELECT s.category,
       COUNT(DISTINCT a.citizen_id) AS distinct_citizen_count
FROM government_services.appointments a
JOIN government_services.services s ON a.service_id = s.service_id
GROUP BY s.category
ORDER BY distinct_citizen_count DESC;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE train_station_management.staff ( staff_id text PRIMARY KEY, first_name text, last_name text, role text, primary_station_id text, employee_number text UNIQUE, hire_date date, contact_email text UNIQUE, contact_phone text, is_active boolean )

[User] What are the training programs or certifications completed by a staff member with the role of Platform Supervisor?

[Assistant] I'm sorry, but I don't have access to information about the training programs or certifications completed by staff members. The data available to me only includes basic staff details such as name, role, and contact information. For details on training or certifications, please refer to the HR department or relevant training records.

[User] What is the current job satisfaction level or feedback from staff members working at a specific train station?

[Assistant] I'm sorry, but I can't provide information on job satisfaction levels or feedback from staff members as this data is not included in the staff table.

[User] What are the specific job responsibilities and daily tasks for a staff member with the role of Station Master?

[Assistant] I'm sorry, but I can't provide information about the specific job responsibilities or daily tasks for a Station Master. The data in the staff table only includes basic identification and contact details, role titles, and employment status, without details on job descriptions or duties.

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)

[User] List each item's name, type, and rarity, along with the currency in which it can be purchased and its cost.

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items;

[User] Show only the items that have a cost greater than 0 and a non-null cost_currency.

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE cost_amount > 0 AND cost_currency IS NOT NULL;

[User] I got an error about null values in cost_amount, could you make the query handle those cases?

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE cost_currency IS NOT NULL AND cost_amount IS NOT NULL AND cost_amount > 0;

[User] Finally, could you sort the results by cost_amount from highest to lowest?

[Assistant] SELECT item_name, item_type, rarity, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE cost_currency IS NOT NULL AND cost_amount IS NOT NULL AND cost_amount > 0 ORDER BY cost_amount DESC;

[User] For every game, can you provide the count of unique item types and the average item cost?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost FROM gaming_technology.in_game_items GROUP BY game_id;

[User] Could you also add the lowest item cost for each game?

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost, MIN(cost_amount) AS min_item_cost FROM gaming_technology.in_game_items GROUP BY game_id;

[User] Now, please only show games with at least 2 different item types.

[Assistant] SELECT game_id, COUNT(DISTINCT item_type) AS num_unique_types, AVG(cost_amount) AS avg_item_cost, MIN(cost_amount) AS min_item_cost FROM gaming_technology.in_game_items GROUP BY game_id HAVING COUNT(DISTINCT item_type) >= 2;

[User] List the names and rarity of all items with a cost above 50.

[Assistant]
SELECT item_name, rarity
FROM gaming_technology.in_game_items
WHERE cost_amount > 50;

[User] Now, only include items where the rarity is 'Epic' or 'Legendary'.

[Assistant]
SELECT item_name, rarity
FROM gaming_technology.in_game_items
WHERE cost_amount > 50
AND rarity IN ('Epic', 'Legendary');

[User] Also show the item_type and order by cost_amount descending.

[Assistant]
SELECT item_name, item_type, rarity, cost_amount
FROM gaming_technology.in_game_items
WHERE cost_amount > 50
AND rarity IN ('Epic', 'Legendary')
ORDER BY cost_amount DESC;

[User] Can you show me the number of items per rarity and item type combination, along with the minimum and maximum cost for each group?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity;

[User] Could you only show the combinations where there are more than 2 items in that group?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity HAVING COUNT(*) > 2;

[User] Additionally, can you add the average cost for each group to the results?

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost FROM gaming_technology.in_game_items GROUP BY item_type, rarity HAVING COUNT(*) > 2;

[User] Now, please only include groups where rarity is not null and order the output by avg_cost descending.

[Assistant] SELECT item_type, rarity, COUNT(*) AS num_items, MIN(cost_amount) AS min_cost, MAX(cost_amount) AS max_cost, AVG(cost_amount) AS avg_cost FROM gaming_technology.in_game_items WHERE rarity IS NOT NULL GROUP BY item_type, rarity HAVING COUNT(*) > 2 ORDER BY avg_cost DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )

[User] Show me each staff member's first and last name along with their manager's first and last name.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       m.staff_id AS manager_id,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff AS s
LEFT JOIN hospitality_technology.staff AS m
  ON s.manager_id = m.staff_id;

[User] Actually, only include active staff and their active managers and sort by the staff last name.

[Assistant]
SELECT s.staff_id,
       s.first_name,
       s.last_name,
       m.staff_id AS manager_id,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff AS s
LEFT JOIN hospitality_technology.staff AS m
  ON s.manager_id = m.staff_id
WHERE s.is_active = true
  AND m.is_active = true
ORDER BY s.last_name;

[User] List all staff members along with their direct manager's first and last names.

[Assistant]
SELECT s.staff_id,
       s.first_name AS staff_first_name,
       s.last_name AS staff_last_name,
       m.first_name AS manager_first_name,
       m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m
  ON s.manager_id = m.staff_id;

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

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

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

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

[User] Show me the email addresses and hire dates for all staff who have a manager.

[Assistant]
SELECT work_email, hire_date
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL;

[User] Only include staff who were hired after January 1, 2023.

[Assistant]
SELECT work_email, hire_date
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL AND hire_date > '2023-01-01';

[User] What is the number of active staff members in each position?

[Assistant]
SELECT position,
       COUNT(*) AS staff_count
FROM hospitality_technology.staff
WHERE is_active = true
GROUP BY position;

[User] Now, only include positions with more than 3 active staff and order the result by staff_count descending.

[Assistant]
SELECT position,
       COUNT(*) AS staff_count
FROM hospitality_technology.staff
WHERE is_active = true
GROUP BY position
HAVING COUNT(*) > 3
ORDER BY staff_count DESC;

[User] Which staff members have terminated employment? Show their names, hire and termination dates, and the property ID.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL;

[User] Only include those who worked at properties with an access_level of at least 4.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL AND access_level >= 4;

[User] Actually, show only the staff whose employment lasted less than 2 years.

[Assistant]
SELECT staff_id, first_name, last_name, hire_date, termination_date, property_id
FROM hospitality_technology.staff
WHERE termination_date IS NOT NULL
  AND access_level >= 4
  AND (termination_date - hire_date) < INTERVAL '2 years';

[User] Show me all staff members who have a manager assigned, along with each manager's full name.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.manager_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE s.manager_id IS NOT NULL;

[User] Actually, only include managers who are currently active.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.manager_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
LEFT JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE s.manager_id IS NOT NULL AND m.is_active = TRUE;

[User] List staff members who were hired in the last calendar year, showing their full name, position, and hire date.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date);

[User] Now, only include those staff members who are not managers and have an access level greater than 3.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date) AND position != 'Manager' AND access_level > 3;

[User] Find all staff members who are managers and list their direct reports. Show the manager's first name, last name, and the direct report's first name, last name, and position.

[Assistant] SELECT m.first_name AS manager_first_name, m.last_name AS manager_last_name, s.first_name AS report_first_name, s.last_name AS report_last_name, s.position AS report_position FROM hospitality_technology.staff s JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id WHERE m.position = 'Manager';

[User] List all staff who report directly to a manager with access_level 5. Include staff full name, position, and the name of their manager.

[Assistant]
SELECT s.staff_id, s.first_name AS staff_first_name, s.last_name AS staff_last_name, s.position, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE m.access_level = 5;

[User] Show only those staff who were hired after 2023-01-01.

[Assistant]
SELECT s.staff_id, s.first_name AS staff_first_name, s.last_name AS staff_last_name, s.position, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE m.access_level = 5 AND s.hire_date > '2023-01-01';

[User] Also add their work_email in the results, and sort by staff last_name alphabetically.

[Assistant]
SELECT s.staff_id, s.first_name AS staff_first_name, s.last_name AS staff_last_name, s.position, s.work_email, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m ON s.manager_id = m.staff_id
WHERE m.access_level = 5 AND s.hire_date > '2023-01-01'
ORDER BY s.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 cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )

[User] Which exchanges hold the largest total USD value of tokens on the BSC chain in the most recent snapshot, and what is the top token (by usd_value) held by each exchange?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] Can you add the number of distinct tokens each exchange holds on BSC in the latest snapshot to the result?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value,
    COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  e.token_count,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] I'd like the results filtered so only exchanges holding more than $2,000,000 in total on BSC are included.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value,
    COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
  HAVING SUM(c.usd_value) > 2000000
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  e.token_count,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] How many unique tokens are recorded for each chain in the latest snapshot in cex_token_balance?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT
  chain,
  COUNT(DISTINCT token_symbol) AS unique_token_count
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
GROUP BY chain
ORDER BY unique_token_count DESC;

[User] What is the total USD value of tokens held by each exchange on Ethereum and Polygon chains in the latest snapshot? Please show exchange, chain, and total usd_value.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT
  exchange,
  chain,
  SUM(usd_value) AS total_usd_value
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
WHERE chain IN ('Ethereum', 'Polygon')
GROUP BY exchange, chain
ORDER BY chain, total_usd_value DESC;

[User] Can you add the number of distinct tokens each exchange holds on those chains to the result?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT
  exchange,
  chain,
  SUM(usd_value) AS total_usd_value,
  COUNT(DISTINCT token_symbol) AS token_count
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
WHERE chain IN ('Ethereum', 'Polygon')
GROUP BY exchange, chain
ORDER BY chain, total_usd_value DESC;

[User] Only show exchanges where total USD value is greater than 5 million on either chain, and order the results by total_usd_value descending.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_usd_values AS (
  SELECT
    exchange,
    chain,
    SUM(usd_value) AS total_usd_value,
    COUNT(DISTINCT token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE chain IN ('Ethereum', 'Polygon')
  GROUP BY exchange, chain
)
SELECT
  exchange,
  chain,
  total_usd_value,
  token_count
FROM exchange_usd_values
WHERE total_usd_value > 5000000
ORDER BY total_usd_value DESC;

[User] Show me the top 5 tokens by USD value held on the Binance Smart Chain, along with their average price and total balance.

[Assistant] SELECT token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Binance Smart Chain' GROUP BY token_symbol ORDER BY total_usd_value DESC LIMIT 5;

[User] Actually, I want to see this for the Polygon chain instead, and only include tokens with a total balance over 1000.

[Assistant] SELECT token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Can you add the exchange name to these results and filter to only show Binance holdings?

[Assistant] SELECT exchange, token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_usd_value DESC LIMIT 5;

[User] Now order these results by total balance instead of USD value.

[Assistant] SELECT exchange, token_symbol, AVG(price) as average_price, SUM(balance) as total_balance, SUM(usd_value) as total_usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND exchange = 'Binance' GROUP BY exchange, token_symbol HAVING SUM(balance) > 1000 ORDER BY total_balance DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )

[User] Could you list each player's username and the total number of sessions they have played?

[Assistant]
SELECT p.username, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
GROUP BY p.username;

[User] Now I only want players registered after '2022-01-01'.

[Assistant]
SELECT p.username, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
WHERE p.registration_date > '2022-01-01'
GROUP BY p.username;

[User] Actually, also include their country_code and order the results by total_sessions descending.

[Assistant]
SELECT p.username,
       p.country_code,
       COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
WHERE p.registration_date > '2022-01-01'
GROUP BY p.username, p.country_code
ORDER BY total_sessions DESC;

[User] Finally, only include players who have played more than 10 sessions.

[Assistant]
SELECT p.username,
       p.country_code,
       COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
WHERE p.registration_date > '2022-01-01'
GROUP BY p.username, p.country_code
HAVING COUNT(gs.session_id) > 10
ORDER BY total_sessions DESC;

[User] Show me each achievement name and the number of players who have unlocked it.

[Assistant]
SELECT a.name,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name;

[User] Now only include achievements with at least 20 unlocks, and display their points as well.

[Assistant]
SELECT a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name, a.points
HAVING COUNT(pa.player_id) >= 20;

[User] Finally, include the game_id for each achievement and sort by unlock_count descending.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.game_id, a.name, a.points
HAVING COUNT(pa.player_id) >= 20
ORDER BY unlock_count DESC;

[User] List each server's name and region along with the total number of sessions hosted on that server.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region;

[User] Filter out servers with fewer than 50 sessions.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50;

[User] Also include the average duration_seconds of those sessions per server.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50;

[User] And only for servers currently online, sorted by avg_duration descending.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
WHERE s.status = 'online'
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50
ORDER BY avg_duration DESC;

[User] For each game session, list session_id, player_id, and the number of achievements that the player had unlocked before the session start_time.

[Assistant]
```sql
SELECT
  gs.session_id,
  gs.player_id,
  COUNT(pa.achievement_id) AS achievements_before_session
FROM gaming_technology.game_sessions gs
LEFT JOIN gaming_technology.player_achievements pa
  ON gs.player_id = pa.player_id
  AND pa.unlocked_at < gs.start_time
GROUP BY
  gs.session_id,
  gs.player_id;
```

[User] Exclude sessions where achievements_before_session is zero.

[Assistant]
```sql
SELECT
  gs.session_id,
  gs.player_id,
  COUNT(pa.achievement_id) AS achievements_before_session
FROM gaming_technology.game_sessions gs
LEFT JOIN gaming_technology.player_achievements pa
  ON gs.player_id = pa.player_id
  AND pa.unlocked_at < gs.start_time
GROUP BY
  gs.session_id,
  gs.player_id
HAVING
  COUNT(pa.achievement_id) > 0;
```

[User] Finally, order by achievements_before_session descending and limit to the top 10 sessions.

[Assistant]
```sql
SELECT
  gs.session_id,
  gs.player_id,
  COUNT(pa.achievement_id) AS achievements_before_session
FROM gaming_technology.game_sessions gs
LEFT JOIN gaming_technology.player_achievements pa
  ON gs.player_id = pa.player_id
  AND pa.unlocked_at < gs.start_time
GROUP BY
  gs.session_id,
  gs.player_id
HAVING
  COUNT(pa.achievement_id) > 0
ORDER BY
  achievements_before_session DESC
LIMIT 10;
```

[User] Show each player with their player_id, username, the number of distinct in-game items they own, and the total quantity of those items.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
GROUP BY
  p.player_id,
  p.username;
```

[User] Only include inventory records acquired in the last 30 days.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
  AND i.acquired_at >= NOW() - INTERVAL '30 days'
GROUP BY
  p.player_id,
  p.username;
```

[User] Also, show only players who have more than 5 distinct items in that period.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
  AND i.acquired_at >= NOW() - INTERVAL '30 days'
GROUP BY
  p.player_id,
  p.username
HAVING
  COUNT(DISTINCT i.item_id) > 5;
```

[User] Order the results by total_quantity descending and then by username ascending.

[Assistant]
```sql
SELECT
  p.player_id,
  p.username,
  COUNT(DISTINCT i.item_id) AS distinct_item_count,
  COALESCE(SUM(i.quantity), 0)    AS total_quantity
FROM gaming_technology.players p
LEFT JOIN gaming_technology.player_inventory i
  ON p.player_id = i.player_id
  AND i.acquired_at >= NOW() - INTERVAL '30 days'
GROUP BY
  p.player_id,
  p.username
HAVING
  COUNT(DISTINCT i.item_id) > 5
ORDER BY
  total_quantity DESC,
  p.username ASC;
```

[User] List all in-game items that are either 'Rare' or 'Epic' rarity.

[Assistant] SELECT item_id, item_name, rarity FROM in_game_items WHERE rarity IN ('Rare', 'Epic');

[User] Include the item type and cost amount in the output.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic');

[User] Now, only show items where the cost amount is less than 500.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic') AND cost_amount < 500;

[User] Order the results by cost amount ascending.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic') AND cost_amount < 500 ORDER BY cost_amount ASC;

[User] List game titles and their developer names for games released in 2023 or later.

[Assistant] SELECT T1.title, T2.name FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T1.release_date >= '2023-01-01';

[User] Also include the genre and order the results by release date descending.

[Assistant] SELECT T1.title, T2.name, T1.genre FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T1.release_date >= '2023-01-01' ORDER BY T1.release_date DESC;

[User] Show me the title of each game and the total number of game sessions played on servers hosting that game.

[Assistant] SELECT t1.title, count(t3.session_id) FROM gaming_technology.games AS t1 JOIN gaming_technology.servers AS t2 ON t1.game_id = t2.game_id JOIN gaming_technology.game_sessions AS t3 ON t2.server_id = t3.server_id GROUP BY 1

[User] Now, filter this list to only include games with more than 1000 total sessions, and order the results by session count descending.

[Assistant] SELECT t1.title, count(t3.session_id) FROM gaming_technology.games AS t1 JOIN gaming_technology.servers AS t2 ON t1.game_id = t2.game_id JOIN gaming_technology.game_sessions AS t3 ON t2.server_id = t3.server_id GROUP BY 1 HAVING count(t3.session_id) > 1000 ORDER BY count(t3.session_id) DESC

[User] Find all in-game items that have a 'mana_cost' attribute in their attributes JSON. Show the item ID, item name, and the value of the 'mana_cost'.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost'

[User] Now, only include items where the 'mana_cost' is greater than 50.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost' AND (attributes ->> 'mana_cost')::int > 50

[User] Add the item's rarity and the title of the game it belongs to in the output.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50

[User] Filter the results to only include items from games in the 'Fantasy' genre.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50 AND t2.genre = 'Fantasy'

[User] Show me all servers and the total number of achievements available in the game they host. Include the server name and region.

[Assistant]
SELECT s.server_name, s.region, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.servers s
JOIN gaming_technology.achievements a ON s.game_id = a.game_id
GROUP BY s.server_id, s.server_name, s.region;

[User] Can you also include the server status in the results?

[Assistant]
SELECT s.server_name, s.region, s.status, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.servers s
JOIN gaming_technology.achievements a ON s.game_id = a.game_id
GROUP BY s.server_id, s.server_name, s.region, s.status;


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.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )

[User] List all unique claim handler IDs present in the claims table.

[Assistant] SELECT DISTINCT claim_handler_id FROM insurance.claims WHERE claim_handler_id IS NOT NULL

[User] Find claims where the estimated loss is greater than the average estimated loss for claims with a status of 'Closed'. Show the claim ID, incident date, estimated loss, and status.

[Assistant] SELECT claim_id, incident_date, estimated_loss, status FROM insurance.claims WHERE estimated_loss > (SELECT AVG(estimated_loss) FROM insurance.claims WHERE status = 'Closed')

[User] I need to see claims where the incident date is in 2023. Show the claim ID, incident date, and customer ID.

[Assistant] SELECT claim_id, incident_date, customer_id FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01'

[User] Can you also include the status and filter the results to only show claims with an estimated loss greater than 5000?

[Assistant] SELECT claim_id, incident_date, customer_id, status FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01' AND estimated_loss > 5000

[User] Actually, I only want claims where the status is 'Approved' or 'Settled'.

[Assistant] SELECT claim_id, incident_date, customer_id, status FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01' AND estimated_loss > 5000 AND status IN ('Approved', 'Settled')

[User] For those claims, also include the settlement amount and order the results by settlement amount descending.

[Assistant] SELECT claim_id, incident_date, customer_id, status, settlement_amount FROM insurance.claims WHERE incident_date >= '2023-01-01' AND incident_date < '2024-01-01' AND estimated_loss > 5000 AND status IN ('Approved', 'Settled') ORDER BY settlement_amount DESC

[User] What is the total estimated_loss and average settlement_amount for all claims with status 'Approved'?

[Assistant]
SELECT SUM(estimated_loss) AS total_estimated_loss,
       AVG(settlement_amount) AS average_settlement
FROM insurance.claims
WHERE status = 'Approved';

[User] Find any two claims made by the same customer on the same day. Return customer_id, the two claim IDs, and the incident date.

[Assistant]
SELECT c1.customer_id,
       c1.claim_id AS claim1_id,
       c2.claim_id AS claim2_id,
       DATE(c1.incident_date) AS incident_date
FROM insurance.claims c1
JOIN insurance.claims c2
  ON c1.customer_id = c2.customer_id
 AND DATE(c1.incident_date) = DATE(c2.incident_date)
 AND c1.claim_id < c2.claim_id;

[User] List each claim_handler_id and the number of claims they handled that were reported in 2023.

[Assistant]
SELECT claim_handler_id,
       COUNT(*) AS claims_count
FROM insurance.claims
WHERE reported_date::date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY claim_handler_id;

[User] List the claim ID, incident date, estimated loss, and the first and last name of the customer for all claims with an estimated loss greater than 5000.

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.estimated_loss, T2.first_name, T2.last_name FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id WHERE T1.estimated_loss > 5000;

[User] Also, only include claims where the incident date is in the year 2024.

[Assistant] SELECT T1.claim_id, T1.incident_date, T1.estimated_loss, T2.first_name, T2.last_name FROM insurance.claims AS T1 JOIN insurance.customers AS T2 ON T1.customer_id = T2.customer_id WHERE T1.estimated_loss > 5000 AND STRFTIME('%Y', T1.incident_date) = '2024';

[User] Show me all claims handled by agent 'AG123' along with their settlement details.

[Assistant] SELECT claim_id, policy_id, customer_id, settlement_amount, settlement_date FROM insurance.claims WHERE claim_handler_id = 'AG123';

[User] I want to see only claims that were settled for more than $10,000.

[Assistant] SELECT claim_id, policy_id, customer_id, settlement_amount, settlement_date FROM insurance.claims WHERE claim_handler_id = 'AG123' AND settlement_amount > 10000;

[User] Now include the time it took to settle these claims (difference between reported_date and settlement_date).

[Assistant] SELECT claim_id, policy_id, customer_id, settlement_amount, settlement_date, DATEDIFF(settlement_date, reported_date) AS days_to_settle FROM insurance.claims WHERE claim_handler_id = 'AG123' AND settlement_amount > 10000;

[User] Finally, order the results by the longest settlement time first.

[Assistant] SELECT claim_id, policy_id, customer_id, settlement_amount, settlement_date, DATEDIFF(settlement_date, reported_date) AS days_to_settle FROM insurance.claims WHERE claim_handler_id = 'AG123' AND settlement_amount > 10000 ORDER BY days_to_settle DESC;

[User] Retrieve customer_id for customers who have a denied claim and an approved claim on the same incident_date. Show customer_id, denied_claim_id, approved_claim_id, and incident_date.

[Assistant]
SELECT c_denied.customer_id,
       c_denied.claim_id AS denied_claim_id,
       c_approved.claim_id AS approved_claim_id,
       c_denied.incident_date::date AS incident_date
FROM insurance.claims c_denied
JOIN insurance.claims c_approved
  ON c_denied.customer_id = c_approved.customer_id
     AND c_denied.incident_date::date = c_approved.incident_date::date
WHERE c_denied.status = 'denied'
  AND c_approved.status = 'approved';

[User] Actually, restrict to only include cases where the approved claim's estimated_loss is greater than the denied claim's estimated_loss.

[Assistant]
SELECT c_denied.customer_id,
       c_denied.claim_id AS denied_claim_id,
       c_approved.claim_id AS approved_claim_id,
       c_denied.incident_date::date AS incident_date
FROM insurance.claims c_denied
JOIN insurance.claims c_approved
  ON c_denied.customer_id = c_approved.customer_id
     AND c_denied.incident_date::date = c_approved.incident_date::date
WHERE c_denied.status = 'denied'
  AND c_approved.status = 'approved'
  AND c_approved.estimated_loss > c_denied.estimated_loss;

[User] Show me the total estimated loss per claim status, and for each status, include the most recent claim's incident date.

[Assistant]
SELECT status, SUM(estimated_loss) AS total_estimated_loss, MAX(incident_date) AS most_recent_incident_date
FROM insurance.claims
GROUP BY status;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )

[User] For each server, what is the earliest and latest start time of its sessions?

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id;

[User] Only show servers where the difference between the earliest and latest session is more than 30 days.

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id HAVING MAX(start_time) - MIN(start_time) > INTERVAL '30 days';

[User] Show each player's highest score for each game they have played.

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

[User] Only include games where the player's highest score is at least 500.

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

[User] For each result, could you also include the number of sessions that player has for that game?

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

[User] Order the results by highest_score in descending order.

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

[User] Show the total session duration in seconds and the average score for each game.

[Assistant] SELECT game_id, SUM(duration_seconds), AVG(score) FROM gaming_technology.game_sessions GROUP BY game_id;

[User] Now, only include games where the total session duration is greater than 100000 seconds.

[Assistant] SELECT game_id, SUM(duration_seconds), AVG(score) FROM gaming_technology.game_sessions GROUP BY game_id HAVING SUM(duration_seconds) > 100000;

[User] How many game sessions started on each calendar day?

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) ORDER BY DATE(start_time);

[User] Only display days that had more than 100 sessions.

[Assistant] SELECT DATE(start_time), COUNT(*) FROM gaming_technology.game_sessions GROUP BY DATE(start_time) HAVING COUNT(*) > 100 ORDER BY DATE(start_time);

[User] Show the game ID and the average session duration in minutes for each game, ordered by average session duration descending.

[Assistant]
SELECT game_id, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
ORDER BY avg_duration_minutes DESC;

[User] Also, include the total number of sessions for each game.

[Assistant]
SELECT game_id, COUNT(*) AS total_sessions, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
ORDER BY avg_duration_minutes DESC;

[User] Filter to only show games with at least 100 sessions.

[Assistant]
SELECT game_id, COUNT(*) AS total_sessions, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
HAVING COUNT(*) >= 100
ORDER BY avg_duration_minutes DESC;

[User] Order by total_sessions descending, then avg_duration_minutes descending.

[Assistant]
SELECT game_id, COUNT(*) AS total_sessions, AVG(duration_seconds) / 60.0 AS avg_duration_minutes
FROM gaming_technology.game_sessions
GROUP BY game_id
HAVING COUNT(*) >= 100
ORDER BY total_sessions DESC, avg_duration_minutes DESC;

[User] What's the average session duration for each player for a given server?

[Assistant] SELECT player_id, server_id, AVG(duration_seconds) AS avg_session_duration FROM gaming_technology.game_sessions GROUP BY player_id, server_id;

[User] Only show player-server pairs with more than 2 sessions.

[Assistant] SELECT player_id, server_id, AVG(duration_seconds) AS avg_session_duration, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY player_id, server_id HAVING COUNT(*) > 2;

[User] Can you add the maximum score that player achieved on each server?

[Assistant] SELECT player_id, server_id, AVG(duration_seconds) AS avg_session_duration, COUNT(*) AS session_count, MAX(score) AS max_score FROM gaming_technology.game_sessions GROUP BY player_id, server_id HAVING COUNT(*) > 2;

[User] Can you show me the total number of sessions and the average score for each server and each game combination?

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score FROM gaming_technology.game_sessions GROUP BY server_id, game_id;

[User] Could you filter this to only include combinations where the average score is above 200?

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score FROM gaming_technology.game_sessions GROUP BY server_id, game_id HAVING AVG(score) > 200;

[User] Can you add the total duration in seconds for each combination as well?

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score, SUM(duration_seconds) AS total_duration FROM gaming_technology.game_sessions GROUP BY server_id, game_id HAVING AVG(score) > 200;

[User] Now, only show combinations where the total duration exceeds 10,000 seconds.

[Assistant] SELECT server_id, game_id, COUNT(*) AS total_sessions, AVG(score) AS average_score, SUM(duration_seconds) AS total_duration FROM gaming_technology.game_sessions GROUP BY server_id, game_id HAVING AVG(score) > 200 AND SUM(duration_seconds) > 10000;

[User] What is the average number of game sessions started per hour of the day (0-23), considering all recorded sessions? Show the hour and the average count.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour, COUNT(*)::NUMERIC / COUNT(DISTINCT DATE_TRUNC('day', start_time)) AS average_sessions FROM gaming_technology.game_sessions GROUP BY 1 ORDER BY 1;

[User] Which hour of the day typically sees the most sessions based on this average? Just show the hour.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour FROM gaming_technology.game_sessions GROUP BY 1 ORDER BY COUNT(*)::NUMERIC / COUNT(DISTINCT DATE_TRUNC('day', start_time)) DESC LIMIT 1;

[User] Instead of the average, show the total number of sessions started for each hour of the day (0-23) across *all* recorded sessions.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour, COUNT(*) AS total_sessions FROM gaming_technology.game_sessions GROUP BY 1 ORDER BY 1;

[User] Only show hours with more than 500 total sessions, and order the results by the total count in descending order.

[Assistant] SELECT EXTRACT(HOUR FROM start_time) AS session_hour, COUNT(*) AS total_sessions FROM gaming_technology.game_sessions GROUP BY 1 HAVING COUNT(*) > 500 ORDER BY total_sessions DESC;

[User] For each game, which server has hosted the most sessions?

[Assistant] SELECT game_id, server_id, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY game_id, server_id;

[User] I want the server with the highest session count per game, not all servers.

[Assistant] SELECT t.game_id, t.server_id, t.session_count FROM (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) t WHERE t.rnk = 1;

[User] If two servers have the same highest count for a game, will both be shown?

[Assistant] Yes, the RANK() function ensures all servers tied for the highest session count per game are shown. The SQL will return all such tied servers for each game where they share the top session count.

[User] Can you also show the total duration of all sessions for the top server(s) per game?

[Assistant] WITH top_servers AS (SELECT game_id, server_id, COUNT(*) AS session_count, RANK() OVER (PARTITION BY game_id ORDER BY COUNT(*) DESC) AS rnk FROM gaming_technology.game_sessions GROUP BY game_id, server_id) SELECT ts.game_id, ts.server_id, ts.session_count, SUM(gs.duration_seconds) AS total_duration FROM top_servers ts JOIN gaming_technology.game_sessions gs ON ts.game_id = gs.game_id AND ts.server_id = gs.server_id WHERE ts.rnk = 1 GROUP BY ts.game_id, ts.server_id, ts.session_count;

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

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

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

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

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

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