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.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )

[User] For each access level, count the number of employees. Return access_level and the corresponding employee_count.

[Assistant] SELECT access_level, COUNT(*) AS employee_count FROM government_services.employees GROUP BY access_level;

[User] List the full names and hire dates of all employees who report directly to a manager with the job title 'Director'.

[Assistant]
SELECT e.first_name, e.last_name, e.hire_date
FROM government_services.employees e
JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE m.job_title = 'Director';

[User] Find all currently employed staff whose managers are no longer employed. Show the employee's full name, hire date, the manager's full name, and the manager's termination_date.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.hire_date, m.first_name || ' ' || m.last_name AS manager_name, m.termination_date FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.termination_date IS NULL AND m.termination_date IS NOT NULL;

[User] List all employees whose job titles differ from their direct managers. Provide each employee's full name, their job title, the manager's full name, and the manager's job title.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.job_title AS employee_job_title, m.first_name || ' ' || m.last_name AS manager_name, m.job_title AS manager_job_title FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.job_title <> m.job_title;

[User] Show a list of departments with more than 5 employees. Include the department name and the count.

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

[User] Also, only include departments where at least one employee's access level is 'Admin'.

[Assistant]
SELECT department, COUNT(*) AS employee_count
FROM government_services.employees
WHERE department IN (
    SELECT department
    FROM government_services.employees
    WHERE access_level = 'Admin'
)
GROUP BY department
HAVING COUNT(*) > 5;

[User] Could you provide the average hire date for each of those departments as well?

[Assistant]
SELECT department, COUNT(*) AS employee_count, AVG(hire_date) AS avg_hire_date
FROM government_services.employees
WHERE department IN (
    SELECT department
    FROM government_services.employees
    WHERE access_level = 'Admin'
)
GROUP BY department
HAVING COUNT(*) > 5;

[User] I got an error that AVG(hire_date) is not allowed. Please return the earliest (MIN) hire date instead.

[Assistant]
SELECT department, COUNT(*) AS employee_count, MIN(hire_date) AS earliest_hire_date
FROM government_services.employees
WHERE department IN (
    SELECT department
    FROM government_services.employees
    WHERE access_level = 'Admin'
)
GROUP BY department
HAVING COUNT(*) > 5;

[User] Which employees are managers themselves? Show their employee ID, full name, and job title.

[Assistant]
SELECT DISTINCT m.employee_id, m.first_name || ' ' || m.last_name AS full_name, m.job_title
FROM government_services.employees m
JOIN government_services.employees e ON e.manager_employee_id = m.employee_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 gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )

[User] Show the maximum and minimum current_players for each server status.

[Assistant] SELECT status, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status;

[User] Please also provide the total number of servers for each status.

[Assistant] SELECT status, COUNT(*) AS total_servers, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status;

[User] Could you sort the results by total_servers in descending order?

[Assistant] SELECT status, COUNT(*) AS total_servers, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status ORDER BY total_servers DESC;

[User] Can you show me the number of servers in each region, as well as the total max_players for each region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players FROM gaming_technology.servers GROUP BY region;

[User] Actually, can you also include the average number of current players per region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players, AVG(current_players) AS avg_current_players FROM gaming_technology.servers GROUP BY region;

[User] Show me all servers where current_players is 0, and include their server_id, server_name, and region.

[Assistant] SELECT server_id, server_name, region FROM gaming_technology.servers WHERE current_players = 0;

[User] Add the max_players and status columns.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0;

[User] Only show servers where status is not 'offline'.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline';

[User] Now sort the results by region ascending and max_players descending.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline' ORDER BY region ASC, max_players DESC;

[User] List all pairs of servers in the same region that are both 'online', showing server1_name, server2_name, and the absolute difference in current_players.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
WHERE s1.server_id <> s2.server_id
  AND s1.status = 'online'
  AND s2.status = 'online';

[User] Actually, only include each pair once (server1_id < server2_id) and where player_diff is less than 20.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
    AND s1.server_id < s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 20;

[User] Now, only include pairs where both servers have max_players greater than 100.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
    AND s1.server_id < s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 20
  AND s1.max_players > 100
  AND s2.max_players > 100;

[User] Show me all pairs of servers that are located in the same region, listing both server names and their region.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id;

[User] Filter this list to only include pairs where both servers are currently 'online'.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] For these pairs, also show the current_players for both servers.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] Order the results by region ascending, then by the current players of the first server in the pair ascending.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online' ORDER BY s1.region ASC, s1.current_players ASC;

[User] Find pairs of servers that are currently 'online' and share the same game_id, listing their server names and the shared game_id.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] For these pairs, show the sum of their current_players and the sum of their max_players.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id, (s1.current_players + s2.current_players) AS combined_current_players, (s1.max_players + s2.max_players) AS combined_max_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] Order the results by game_id and then by the combined current players in descending order.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id, (s1.current_players + s2.current_players) AS combined_current_players, (s1.max_players + s2.max_players) AS combined_max_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online' ORDER BY s1.game_id, combined_current_players 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.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    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)
)
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)

[User] Show me the average base rate for each room type across all properties. Include the room type name and the calculated average rate.

[Assistant] SELECT type_name, AVG(base_rate) FROM hospitality_technology.room_types GROUP BY type_name;

[User] Actually, I need to see this breakdown per property as well.

[Assistant] SELECT p.property_name, rt.type_name, AVG(rt.base_rate) FROM hospitality_technology.room_types rt JOIN hospitality_technology.properties p ON rt.property_id = p.property_id GROUP BY p.property_name, rt.type_name;

[User] Can you filter the results to only show room types with an average base rate greater than 200?

[Assistant] SELECT p.property_name, rt.type_name, AVG(rt.base_rate) FROM hospitality_technology.room_types rt JOIN hospitality_technology.properties p ON rt.property_id = p.property_id GROUP BY p.property_name, rt.type_name HAVING AVG(rt.base_rate) > 200;

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

[Assistant] SELECT 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;

[User] List all reservations made by guests from 'US', showing the reservation ID, guest first name, last name, and the property name.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US';

[User] Only show reservations with status 'Confirmed'.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US' AND T1.status = 'Confirmed';

[User] Also include the check-in and check-out dates, and order by check-in date descending.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name, T1.check_in_date, T1.check_out_date FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US' AND T1.status = 'Confirmed' ORDER BY T1.check_in_date DESC;

[User] List all guests who placed a service order with a total price greater than 200, including their first name, last name, and the order ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.order_id FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.service_orders AS T2 ON T1.guest_id = T2.guest_id WHERE T2.total_price > 200;

[User] Show me all staff members hired in 2022, including their first name, last name, and hire date.

[Assistant] SELECT first_name, last_name, hire_date FROM hospitality_technology.staff WHERE EXTRACT(YEAR FROM hire_date) = 2022;

[User] Only include staff members whose position is 'Manager' or 'Supervisor'.

[Assistant] SELECT first_name, last_name, hire_date FROM hospitality_technology.staff WHERE EXTRACT(YEAR FROM hire_date) = 2022 AND position IN ('Manager', 'Supervisor');

[User] Show me all reservations, including the guest's full name, the room number, check-in date, and check-out date.

[Assistant] SELECT T1.first_name, T1.last_name, T3.room_number, T2.check_in_date, T2.check_out_date FROM hospitality_technology.reservations AS T2 JOIN hospitality_technology.guests AS T1 ON T2.guest_id = T1.guest_id JOIN hospitality_technology.rooms AS T3 ON T2.room_id = T3.room_id;

[User] Only include reservations with a check-in date in 2024.

[Assistant] SELECT T1.first_name, T1.last_name, T3.room_number, T2.check_in_date, T2.check_out_date FROM hospitality_technology.reservations AS T2 JOIN hospitality_technology.guests AS T1 ON T2.guest_id = T1.guest_id JOIN hospitality_technology.rooms AS T3 ON T2.room_id = T3.room_id WHERE T2.check_in_date >= '2024-01-01' AND T2.check_in_date < '2025-01-01';

[User] Also, only show reservations for rooms on floors higher than 5.

[Assistant] SELECT T1.first_name, T1.last_name, T3.room_number, T2.check_in_date, T2.check_out_date FROM hospitality_technology.reservations AS T2 JOIN hospitality_technology.guests AS T1 ON T2.guest_id = T1.guest_id JOIN hospitality_technology.rooms AS T3 ON T2.room_id = T3.room_id WHERE T2.check_in_date >= '2024-01-01' AND T2.check_in_date < '2025-01-01' AND T3.floor > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Show me all loans with a term longer than 36 months, including their loan_id, account_id, and principal_amount.

[Assistant] SELECT loan_id, account_id, principal_amount FROM financial_services.loans WHERE term_months > 36;

[User] Can you also include their origination_date and current_principal_balance?

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36;

[User] Filter to only show loans that are not yet matured (maturity_date > CURRENT_DATE).

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36 AND maturity_date > CURRENT_DATE;

[User] For each loan type, show the total outstanding principal balance and the number of active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type;

[User] Sort the result by total_outstanding_balance in ascending order.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type ORDER BY total_outstanding_balance ASC;

[User] Only include loan types where there are more than 10 active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type HAVING COUNT(*) > 10 ORDER BY total_outstanding_balance ASC;

[User] Show all loans with a maturity date in the next 60 days, along with their account_id, principal_amount, interest_rate, and maturity_date.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] Only include loans where the status is not 'CLOSED' or 'PAID_OFF'.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] Also, display the loan_type in the result.

[Assistant] SELECT loan_id, account_id, loan_type, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] What is the average interest rate for auto loans (loan_type = 'Auto') with a principal amount between $20,000 and $50,000?

[Assistant] SELECT AVG(interest_rate) AS avg_interest_rate FROM financial_services.loans WHERE loan_type = 'Auto' AND principal_amount BETWEEN 20000 AND 50000;

[User] Show me the total principal amount for each loan type, along with the count of loans and average monthly payment, but only for loans originated in the last 5 years.

[Assistant] SELECT loan_type, SUM(principal_amount) AS total_principal, COUNT(loan_id) AS loan_count, AVG(monthly_payment) AS avg_monthly_payment FROM financial_services.loans WHERE origination_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY loan_type;

[User] What is the average interest rate for loans of type 'Mortgage'?

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage'

[User] Refine this to only include loans with status 'Active'.

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage' AND status = 'Active'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )

[User] List the usernames and email addresses of users who have published posts with media_type 'video', along with the creation time of each post.

[Assistant]
SELECT u.username, u.email, p.created_at
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_type = 'video';

[User] Actually, I'd like to see how many hashtags each of those posts has. Include a column hashtag_count.

[Assistant]
SELECT u.username, u.email, p.created_at, COUNT(ph.post_hashtag_id) AS hashtag_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
LEFT JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
WHERE p.media_type = 'video'
GROUP BY u.username, u.email, p.created_at;

[User] Show a list of group chat names with their conversation_id, the total number of participants, and the total number of messages sent in each group chat.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name;

[User] Please filter to include only group chats that have at least 5 participants.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(cp.participant_id) >= 5;

[User] Now order the results by message_count descending and limit to the top 10 group chats.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(cp.participant_id) AS participant_count,
       COUNT(m.message_id) AS message_count
FROM social_media.conversations c
JOIN social_media.conversation_participants cp ON c.conversation_id = cp.conversation_id
LEFT JOIN social_media.messages m ON c.conversation_id = m.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(cp.participant_id) >= 5
ORDER BY message_count DESC
LIMIT 10;

[User] I want to see each user's username and the number of posts they've made that include a media attachment of type 'image'.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username;

[User] Only include users with more than 2 image posts.

[Assistant]
SELECT u.username, COUNT(*) AS image_post_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL
  AND p.media_type = 'image'
GROUP BY u.username
HAVING COUNT(*) > 2;

[User] Retrieve the usernames and email addresses of users who updated their profiles in the last 30 days.

[Assistant]
SELECT username, email
FROM social_media.users
WHERE updated_at >= NOW() - INTERVAL '30 days';

[User] List all posts along with the user emails of the authors.

[Assistant]
SELECT p.post_id, p.content, u.email
FROM social_media.posts p
JOIN social_media.users u ON p.user_id = u.user_id;

[User] Show me all users and the posts they have created, including the user's username and the post content.

[Assistant]
SELECT u.username, p.post_id, p.content
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id;

[User] Actually, can you please also include the post creation time and only show posts that have a media attachment?

[Assistant]
SELECT u.username, p.post_id, p.content, p.created_at
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )

[User] What is the total investment_value per fundraising round for the year 2023? Order by total investment descending.

[Assistant]
SELECT
  substr(investment_date,1,7) AS month,
  rounds_name,
  SUM(investment_value) AS total_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%'
GROUP BY substr(investment_date,1,7), rounds_name
ORDER BY total_investment DESC;

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

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

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

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

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

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

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

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

[User] How many projects raised funds in 2023?

[Assistant]
SELECT COUNT(*) AS project_count
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] Also provide the average investment_value for these projects.

[Assistant]
SELECT COUNT(*) AS project_count, AVG(investment_value) AS avg_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] Which projects raised funds in January 2022?

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] Please also show their introductions.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] List all fundraising rounds where the average investment amount exceeded $10M, and show how many projects participated in each round.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000;

[User] Now, only consider rounds with at least 3 projects.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3;

[User] Add the total raised amount in each selected round.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment, SUM(investment_value) AS total_raised FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3;

[User] Show the result ordered by total_raised in descending order, and only the top 2 rounds.

[Assistant] SELECT rounds_name, project_count, avg_investment, total_raised FROM (SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment, SUM(investment_value) AS total_raised FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3) t ORDER BY total_raised DESC LIMIT 2;

[User] Which project raised the highest investment_value in each fundraising round?

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Can you also include the project's valuation and introduction?

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Now, filter to only rounds where the maximum investment_value is greater than 2000000.

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
    HAVING MAX(investment_value) > 2000000
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Actually, only consider rounds in 2022 and order the results by the maximum investment_value descending.

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022-%'
    GROUP BY rounds_name
    HAVING MAX(investment_value) > 2000000
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment
ORDER BY m.max_investment 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 financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )

[User] Can you show me all pairs of customers living in the same city but with different last names? Show both customer IDs, both full names, and their city.

[Assistant] SELECT a.customer_id AS customer_id_a, CONCAT(a.first_name, ' ', a.last_name) AS full_name_a, b.customer_id AS customer_id_b, CONCAT(b.first_name, ' ', b.last_name) AS full_name_b, a.city FROM financial_services.customers a JOIN financial_services.customers b ON a.city = b.city AND a.last_name <> b.last_name AND a.customer_id < b.customer_id;

[User] Add a filter to only include pairs where both customers are in the same state as well.

[Assistant] SELECT a.customer_id AS customer_id_a, CONCAT(a.first_name, ' ', a.last_name) AS full_name_a, b.customer_id AS customer_id_b, CONCAT(b.first_name, ' ', b.last_name) AS full_name_b, a.city, a.state FROM financial_services.customers a JOIN financial_services.customers b ON a.city = b.city AND a.state = b.state AND a.last_name <> b.last_name AND a.customer_id < b.customer_id;

[User] Please further restrict results to only pairs where both customers have a status of 'Active'.

[Assistant] SELECT a.customer_id AS customer_id_a, CONCAT(a.first_name, ' ', a.last_name) AS full_name_a, b.customer_id AS customer_id_b, CONCAT(b.first_name, ' ', b.last_name) AS full_name_b, a.city, a.state FROM financial_services.customers a JOIN financial_services.customers b ON a.city = b.city AND a.state = b.state AND a.last_name <> b.last_name AND a.status = 'Active' AND b.status = 'Active' AND a.customer_id < b.customer_id;

[User] List all customers in California ('CA'). Show their full name, city, and date of birth.

[Assistant] SELECT first_name, last_name, city, date_of_birth FROM financial_services.customers WHERE state = 'CA'

[User] Also include customers from New York ('NY').

[Assistant] SELECT first_name, last_name, city, date_of_birth FROM financial_services.customers WHERE state = 'CA' OR state = 'NY'

[User] Sort the results by state ascending, then by date of birth ascending.

[Assistant] SELECT first_name, last_name, city, date_of_birth FROM financial_services.customers WHERE state = 'CA' OR state = 'NY' ORDER BY state ASC, date_of_birth ASC

[User] Find all distinct pairs of customers having the same first_name but living in different cities. Display a.customer_id, a.first_name, a.city AS city_a, b.customer_id, b.city AS city_b.

[Assistant]
SELECT a.customer_id AS customer_id_a,
       a.first_name,
       a.city      AS city_a,
       b.customer_id AS customer_id_b,
       b.city      AS city_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.first_name = b.first_name
 AND a.city <> b.city
 AND a.customer_id < b.customer_id;

[User] Only include pairs where both customers have status 'Active'.

[Assistant]
SELECT a.customer_id AS customer_id_a,
       a.first_name,
       a.city      AS city_a,
       b.customer_id AS customer_id_b,
       b.city      AS city_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.first_name = b.first_name
 AND a.city <> b.city
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active';

[User] Sort the output by first_name ascending and then by customer_id_a ascending.

[Assistant]
SELECT a.customer_id AS customer_id_a,
       a.first_name,
       a.city      AS city_a,
       b.customer_id AS customer_id_b,
       b.city      AS city_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.first_name = b.first_name
 AND a.city <> b.city
 AND a.customer_id < b.customer_id
WHERE a.status = 'Active'
  AND b.status = 'Active'
ORDER BY a.first_name ASC,
         customer_id_a ASC;

[User] Show me all customers (customer_id, first_name, last_name, email) who were born after 1985 (date_of_birth > '1985-12-31') and have an email address ending with '@yahoo.com', along with their city and state information.

[Assistant] SELECT customer_id, first_name, last_name, email, city, state FROM financial_services.customers WHERE date_of_birth > '1985-12-31' AND email LIKE '%@yahoo.com';

[User] What is the average age of customers by risk_profile for those in status 'Active'?

[Assistant]
SELECT risk_profile,
       AVG(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS avg_age
FROM financial_services.customers
WHERE status = 'Active'
GROUP BY risk_profile;

[User] Exclude risk_profiles with fewer than 10 active customers.

[Assistant]
SELECT risk_profile,
       AVG(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS avg_age
FROM financial_services.customers
WHERE status = 'Active'
GROUP BY risk_profile
HAVING COUNT(*) >= 10;

[User] Also include the minimum and maximum age in the result.

[Assistant]
SELECT risk_profile,
       AVG(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS avg_age,
       MIN(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS min_age,
       MAX(DATE_PART('year', AGE(CURRENT_DATE, date_of_birth))) AS max_age
FROM financial_services.customers
WHERE status = 'Active'
GROUP BY risk_profile
HAVING COUNT(*) >= 10;

[User] Can you give me a breakdown of the number of customers in each country and their average age? I want the result to also show the total number of unique states per country.

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers GROUP BY country;

[User] That's helpful. Please add the minimum and maximum age for each country as well.

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, MIN(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS min_age, MAX(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS max_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers GROUP BY country;

[User] Only include countries where the total number of customers is greater than 50. Can you sort the result by customer_count descending?

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, MIN(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS min_age, MAX(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS max_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers GROUP BY country HAVING COUNT(*) > 50 ORDER BY customer_count DESC;

[User] I notice some countries are missing because their names are null. Please exclude rows with null country values.

[Assistant] SELECT country, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS average_age, MIN(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS min_age, MAX(EXTRACT(YEAR FROM age(current_date, date_of_birth))) AS max_age, COUNT(DISTINCT state) AS unique_states FROM financial_services.customers WHERE country IS NOT NULL GROUP BY country HAVING COUNT(*) > 50 ORDER BY customer_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 social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )

[User] How many users have non-empty full_name and bio fields? Return only the count.

[Assistant]
SELECT COUNT(*)
FROM social_media.users
WHERE full_name IS NOT NULL
  AND full_name <> ''
  AND bio IS NOT NULL
  AND bio <> '';

[User] Count how many users have not specified a value for their bio.

[Assistant] SELECT COUNT(*) FROM social_media.users WHERE bio IS NULL OR bio = '';

[User] List usernames and the length of their 'bio' field for users whose 'is_verified' status is true.

[Assistant] SELECT username, LENGTH(bio) AS bio_length FROM social_media.users WHERE is_verified IS TRUE;

[User] Show me the usernames and full names of all users who have updated their profile after April 1, 2024, and have specified a location.

[Assistant] SELECT username, full_name FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '';

[User] Actually, I also want to see their email addresses.

[Assistant] SELECT username, full_name, email FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '';

[User] Now, only show users whose profiles are verified.

[Assistant] SELECT username, full_name, email FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '' AND is_verified = true;

[User] Sort the results by username in ascending order.

[Assistant] SELECT username, full_name, email FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '' AND is_verified = true ORDER BY username ASC;

[User] Show the usernames of users who have used any hashtag in their posts, along with the tag name.

[Assistant] SELECT DISTINCT T1.username, T4.tag_name FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id JOIN hashtags AS T4 ON T3.hashtag_id = T4.hashtag_id;

[User] Only include users who have used hashtags more than 3 times across all their posts.

[Assistant] SELECT T1.username, COUNT(T3.hashtag_id) AS hashtag_usage_count FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id GROUP BY T1.username HAVING COUNT(T3.hashtag_id) > 3;

[User] Show the username, full name, and location for all users who registered before January 1, 2024 and are not verified.

[Assistant] SELECT username, full_name, location FROM social_media.users WHERE created_at < '2024-01-01' AND is_verified = false;

[User] Only include those who have a non-empty location.

[Assistant] SELECT username, full_name, location FROM social_media.users WHERE created_at < '2024-01-01' AND is_verified = false AND location IS NOT NULL AND location <> '';


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 web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )

[User] List all failed transactions where the gas_used is greater than 100,000, including the transaction_id and timestamp.

[Assistant] SELECT transaction_id, timestamp FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000;

[User] Actually, I also need to see the from_address and the value of these transactions.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000;

[User] There's a typo in your SQL, it should be '100000' not '100,000'. Also, sort the results by timestamp in descending order.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 ORDER BY timestamp DESC;

[User] Now filter to only show transactions from the last 30 days.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 AND timestamp >= NOW() - INTERVAL '30 days' ORDER BY timestamp DESC;

[User] For each transaction, find the next transaction initiated by the same sender. List the original transaction_id, the next transaction_id, the sender address, and the time difference in hours between them.

[Assistant]
SELECT t1.transaction_id AS original_tx,
       t2.transaction_id AS next_tx,
       t1.from_address,
       EXTRACT(EPOCH FROM (t2.timestamp - t1.timestamp)) / 3600 AS hours_diff
FROM transactions t1
JOIN transactions t2
  ON t1.from_address = t2.from_address
 AND t2.timestamp = (
       SELECT MIN(timestamp)
       FROM transactions t3
       WHERE t3.from_address = t1.from_address
         AND t3.timestamp > t1.timestamp
   );

[User] List all pairs of transactions within the same block where the from_address of one transaction is the to_address of another transaction. Show both transaction_ids, the block_number, from_address, and to_address.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.block_number, t1.from_address, t1.to_address
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.block_number = t2.block_number
  AND t1.from_address = t2.to_address
  AND t1.to_address = t2.from_address;

[User] Count the number of transactions for each status.

[Assistant]
SELECT status, COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY status;

[User] Actually, only include statuses with more than 1000 transactions.

[Assistant]
SELECT status, COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY status
HAVING COUNT(*) > 1000;

[User] For each transaction, find the next transaction by the same sender. Show the original transaction_id as current_tx, the next transaction_id as next_tx, from_address, and the time difference in minutes between them.

[Assistant]
SELECT t1.transaction_id AS current_tx,
       t2.transaction_id AS next_tx,
       t1.from_address,
       EXTRACT(EPOCH FROM (t2.timestamp - t1.timestamp)) / 60 AS diff_minutes
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
  AND t2.timestamp = (
    SELECT MIN(t3.timestamp)
    FROM web3.transactions t3
    WHERE t3.from_address = t1.from_address
      AND t3.timestamp > t1.timestamp
  );

[User] Show all transactions where the transaction value is greater than the average value of all transactions, including transaction_id, from_address, to_address, value, and timestamp.

[Assistant]
SELECT transaction_id, from_address, to_address, value, timestamp
FROM web3.transactions
WHERE value > (SELECT AVG(value) FROM web3.transactions);


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 )

[User] What is the average and maximum standard fee for services in each category?

[Assistant] SELECT category, AVG(standard_fee) AS avg_standard_fee, MAX(standard_fee) AS max_standard_fee FROM government_services.services GROUP BY category;

[User] Could you list pairs of services that belong to different agencies but share the same category? Provide the service names and their agency_ids.

[Assistant]
SELECT s1.service_name AS service_name_1, s1.agency_id AS agency_id_1, s2.service_name AS service_name_2, s2.agency_id AS agency_id_2
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.agency_id <> s2.agency_id;

[User] Actually, show only those pairs where both services are active.

[Assistant]
SELECT s1.service_name AS service_name_1, s1.agency_id AS agency_id_1, s2.service_name AS service_name_2, s2.agency_id AS agency_id_2
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.agency_id <> s2.agency_id
WHERE s1.is_active = TRUE
  AND s2.is_active = TRUE;

[User] What is the average processing time in days for each service category?

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
GROUP BY category;

[User] Only include categories where the average_processing_time_days is greater than 5.

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
GROUP BY category
HAVING AVG(average_processing_time_days) > 5;

[User] Also include only active services in the calculation.

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
WHERE is_active = TRUE
GROUP BY category
HAVING AVG(average_processing_time_days) > 5;

[User] Sort the results by avg_processing_time in descending order.

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
WHERE is_active = TRUE
GROUP BY category
HAVING AVG(average_processing_time_days) > 5
ORDER BY avg_processing_time DESC;

[User] Find for each category the service with the highest standard_fee and the service with the lowest standard_fee. Display the category, highest_fee_service, and lowest_fee_service.

[Assistant]
SELECT m.category,
       s_max.service_name AS highest_fee_service,
       s_min.service_name AS lowest_fee_service
FROM (
  SELECT category,
         MAX(standard_fee) AS max_fee,
         MIN(standard_fee) AS min_fee
  FROM government_services.services
  GROUP BY category
) m
JOIN government_services.services s_max
  ON s_max.category = m.category
  AND s_max.standard_fee = m.max_fee
JOIN government_services.services s_min
  ON s_min.category = m.category
  AND s_min.standard_fee = m.min_fee;

[User] Which active services have a standard fee less than 100, and what are the agency IDs and categories for these services?

[Assistant] SELECT service_name, agency_id, category FROM government_services.services WHERE is_active = TRUE AND standard_fee < 100;

[User] List all services whose eligibility criteria mention 'citizen'.

[Assistant] SELECT service_id, service_name, eligibility_criteria FROM government_services.services WHERE eligibility_criteria ILIKE '%citizen%';


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.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )

[User] I want to retrieve the agent ID, first and last name, along with their manager's contact email and phone number.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id;

[User] Please filter to only agents who have a non-null manager and whose hire_date is after '2022-06-30'.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30';

[User] Additionally, sort the results by the agent's hire_date in ascending order.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30'
ORDER BY a.hire_date ASC;

[User] Finally, limit the result to 10 rows.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30'
ORDER BY a.hire_date ASC
LIMIT 10;

[User] What is the average commission_rate for each agent status and only show statuses with an average commission_rate above 0.05?

[Assistant]
SELECT status,
       AVG(commission_rate) AS avg_commission_rate
FROM insurance.agents
GROUP BY status
HAVING AVG(commission_rate) > 0.05;

[User] Please list the agent ID, agent's name, and manager's email for all agents who have a commission_rate greater than 0.12.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, m.contact_email AS manager_email
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.12;

[User] Filter these results to only include agents whose own status is 'active'.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, m.contact_email AS manager_email
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.12 AND a.status = 'active';

[User] Find all agents hired after '2021-01-01', including their first_name, last_name, hire_date, and their manager's full name.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2021-01-01';

[User] Actually, include only those whose manager is in the same license_state as the agent.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01';

[User] I need only those with commission_rate above 0.05 and status 'Active'.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active';

[User] Sort the results by commission_rate descending and limit to the top 10.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active'
ORDER BY a.commission_rate DESC
LIMIT 10;

[User] Find managers who have at least one agent reporting to them whose status is 'inactive'. List the manager's full name and the full name of the inactive agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Could you also include the inactive agent's termination date in the results?

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Filter the results to only include cases where the manager is currently 'active'.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive' AND T2.status = 'active'

[User] Retrieve a list of agents who were hired in 2024. Include agent_id, first_name, last_name, hire_date.

[Assistant]
SELECT agent_id, first_name, last_name, hire_date
FROM insurance.agents
WHERE hire_date >= '2024-01-01' AND hire_date < '2025-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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
Collection 'inspections'. Document structure: { _id: <ObjectId (or inspection_id)>, inspection_id: String, build_id: String (reference), component_id: String (reference, optional), step_id: String (reference, optional), inspection_type: String, inspector_employee_id: String (reference), inspection_timestamp: ISODate, result: String, remarks: String }. Required: inspection_id, build_id, inspection_type, inspector_employee_id, inspection_timestamp, result. Indexes on build_id, component_id, step_id, inspector_employee_id, result.

[User] 我想查看所有检查记录中检查员的ID和检查结果，同时统计每个检查员的检查次数。

[Assistant]
db.inspections.aggregate([
  {
    $group: {
      _id: '$inspector_employee_id',
      total_inspections: { $count: {} },
      results: { $push: '$result' }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      total_inspections: 1,
      results: 1,
      _id: 0
    }
  }
]);

[User] 如果我想只统计检查结果为'Fail'的次数，应该怎么改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Fail'
    }
  },
  {
    $group: {
      _id: '$inspector_employee_id',
      failed_inspections: { $count: {} }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      failed_inspections: 1,
      _id: 0
    }
  }
]);

[User] Can you help me retrieve all inspection records for a specific build ID, including the inspection type, result, and the timestamp of the inspection, along with the associated component ID if available?

[Assistant] db.inspections.find({ build_id: 'specific_build_id' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 })

[User] Can you modify the query to include only inspections that occurred after a specific date, say January 1, 2022?

[Assistant] db.inspections.find({ build_id: 'specific_build_id', inspection_timestamp: { $gt: ISODate('2022-01-01T00:00:00Z') } }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 })

[User] What if I want to further filter the results to show only inspections with a 'Pass' result?

[Assistant] db.inspections.find({ build_id: 'specific_build_id', inspection_timestamp: { $gt: ISODate('2022-01-01T00:00:00Z') }, result: 'Pass' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 })

[User] Can you also sort the results by inspection timestamp in descending order?

[Assistant] db.inspections.find({ build_id: 'specific_build_id', inspection_timestamp: { $gt: ISODate('2022-01-01T00:00:00Z') }, result: 'Pass' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, component_id: 1, _id: 0 }).sort({ inspection_timestamp: -1 })

[User] Can you help me retrieve inspection records for a specific step ID, including the inspection type, result, timestamp, and the associated build ID?

[Assistant] db.inspections.find({ step_id: 'specific_step_id' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, build_id: 1, _id: 0 })

[User] Can you add a filter to show only inspections with a result of 'Fail'?

[Assistant] db.inspections.find({ step_id: 'specific_step_id', result: 'Fail' }, { inspection_type: 1, result: 1, inspection_timestamp: 1, build_id: 1, _id: 0 })

[User] What if I want to further narrow it down to inspections performed after March 1, 2023?

[Assistant] db.inspections.find({ step_id: 'specific_step_id', result: 'Fail', inspection_timestamp: { $gt: ISODate('2023-03-01T00:00:00Z') } }, { inspection_type: 1, result: 1, inspection_timestamp: 1, build_id: 1, _id: 0 })

[User] Can you also include the remarks field and sort the results by timestamp in ascending order?

[Assistant] db.inspections.find({ step_id: 'specific_step_id', result: 'Fail', inspection_timestamp: { $gt: ISODate('2023-03-01T00:00:00Z') } }, { inspection_type: 1, result: 1, inspection_timestamp: 1, build_id: 1, remarks: 1, _id: 0 }).sort({ inspection_timestamp: 1 })

[User] 我想查询某个构建ID下的所有检查记录，包括检查类型、检查结果和检查时间，同时关联到对应的步骤信息。

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      build_id: 'specific_build_id'
    }
  },
  {
    $lookup: {
      from: 'steps',
      localField: 'step_id',
      foreignField: 'step_id',
      as: 'step_info'
    }
  },
  {
    $unwind: {
      path: '$step_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      result: 1,
      inspection_timestamp: 1,
      'step_info.step_name': 1,
      'step_info.description': 1
    }
  }
]);

[User] 如果我想进一步筛选出检查结果为'Pass'的记录，应该怎么做？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      build_id: 'specific_build_id',
      result: 'Pass'
    }
  },
  {
    $lookup: {
      from: 'steps',
      localField: 'step_id',
      foreignField: 'step_id',
      as: 'step_info'
    }
  },
  {
    $unwind: {
      path: '$step_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      result: 1,
      inspection_timestamp: 1,
      'step_info.step_name': 1,
      'step_info.description': 1
    }
  }
]);

[User] I need to get a count of inspections performed by each inspector, including their employee ID and the total number of inspections they have conducted.

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} } } }])

[User] Can you modify this to show only inspectors who have performed more than 10 inspections?

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} } } }, { $match: { totalInspections: { $gt: 10 } } }])

[User] What if I also want to include the number of failed inspections for each inspector?

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} }, failedInspections: { $sum: { $cond: [{ $eq: ['$result', 'Fail'] }, 1, 0] } } } }, { $match: { totalInspections: { $gt: 10 } } }])

[User] Can you sort the results by the total number of inspections in descending order?

[Assistant] db.inspections.aggregate([{ $group: { _id: '$inspector_employee_id', totalInspections: { $count: {} }, failedInspections: { $sum: { $cond: [{ $eq: ['$result', 'Fail'] }, 1, 0] } } } }, { $match: { totalInspections: { $gt: 10 } } }, { $sort: { totalInspections: -1 } }])

[User] 我想查询所有检查结果为'Pass'的记录，包括检查类型、检查时间和检查备注，同时关联到对应的组件信息。

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Pass'
    }
  },
  {
    $lookup: {
      from: 'components',
      localField: 'component_id',
      foreignField: 'component_id',
      as: 'component_info'
    }
  },
  {
    $unwind: {
      path: '$component_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      inspection_timestamp: 1,
      remarks: 1,
      'component_info.component_name': 1,
      'component_info.description': 1
    }
  }
]);

[User] 如果我想只看检查时间在2023年1月1日之后的记录，应该怎么修改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Pass',
      inspection_timestamp: {
        $gte: ISODate('2023-01-01T00:00:00Z')
      }
    }
  },
  {
    $lookup: {
      from: 'components',
      localField: 'component_id',
      foreignField: 'component_id',
      as: 'component_info'
    }
  },
  {
    $unwind: {
      path: '$component_info',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $project: {
      inspection_type: 1,
      inspection_timestamp: 1,
      remarks: 1,
      'component_info.component_name': 1,
      'component_info.description': 1
    }
  }
]);


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.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )

[User] How many reservations have been booked each month in 2023?

[Assistant]
SELECT DATE_TRUNC('month', created_at) AS month,
       COUNT(*) AS reservation_count
FROM hospitality_technology.reservations
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY month;

[User] Actually, exclude reservations with status 'Canceled' and order by month.

[Assistant]
SELECT DATE_TRUNC('month', created_at) AS month,
       COUNT(*) AS reservation_count
FROM hospitality_technology.reservations
WHERE created_at >= '2023-01-01'
  AND created_at < '2024-01-01'
  AND status <> 'Canceled'
GROUP BY month
ORDER BY month;

[User] Find reservations where the same guest has overlapping stays in the same property.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date;

[User] Only include overlaps where the overlapping period is more than 2 days.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date
WHERE (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) > 2;

[User] Also return the exact overlap duration in days as overlap_days.

[Assistant]
SELECT r1.reservation_id AS res1,
       r2.reservation_id AS res2,
       r1.guest_id,
       r1.property_id,
       (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) AS overlap_days
FROM hospitality_technology.reservations r1
JOIN hospitality_technology.reservations r2
  ON r1.guest_id = r2.guest_id
 AND r1.property_id = r2.property_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date
WHERE (LEAST(r1.check_out_date, r2.check_out_date) - GREATEST(r1.check_in_date, r2.check_in_date)) > 2;

[User] What is the total revenue (sum of total_amount) and total amount_paid for each booking_source?

[Assistant]
SELECT booking_source,
       SUM(total_amount) AS total_revenue,
       SUM(amount_paid) AS total_paid
FROM reservations
GROUP BY booking_source;

[User] Only include sources where total revenue > 10000 and order by total_revenue descending.

[Assistant]
SELECT booking_source,
       SUM(total_amount) AS total_revenue,
       SUM(amount_paid) AS total_paid
FROM reservations
GROUP BY booking_source
HAVING SUM(total_amount) > 10000
ORDER BY total_revenue DESC;

[User] List pairs of overlapping reservations for the same room, including both reservation IDs, room_id, and each reservation's check-in and check-out dates.

[Assistant]
SELECT r1.reservation_id AS reservation_id_1,
       r2.reservation_id AS reservation_id_2,
       r1.room_id,
       r1.check_in_date AS check_in_1,
       r1.check_out_date AS check_out_1,
       r2.check_in_date AS check_in_2,
       r2.check_out_date AS check_out_2
FROM reservations r1
JOIN reservations r2
  ON r1.room_id = r2.room_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date;

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

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

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

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

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

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

[User] List reservations, including the reservation ID, check-in date, check-out date, property name, room type name, and room type base rate, for reservations with 3 or more adults.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3;

[User] Now, only include reservations made at properties with a star rating of 4 or higher and sort the results by check-in date.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3 AND T2.star_rating >= 4 ORDER BY T1.check_in_date;

[User] Further refine this list to include only reservations where the total amount is over 700, and limit the results to the top 15.

[Assistant] SELECT T1.reservation_id, T1.check_in_date, T1.check_out_date, T2.property_name, T3.type_name, T3.base_rate FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T1.room_type_id = T3.room_type_id WHERE T1.num_adults >= 3 AND T2.star_rating >= 4 AND T1.total_amount > 700 ORDER BY T1.check_in_date LIMIT 15;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] Please round avg_capacity to one decimal place.

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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