System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] Find documents that have the same document_name but are associated with different cases. Show the document name and the two different case IDs.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id;

[User] Actually, only show pairs where at least one of the documents is of document_type 'Contract'.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract');

[User] Also, only include pairs where both documents were uploaded in the year 2024.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract') AND YEAR(d1.upload_timestamp) = 2024 AND YEAR(d2.upload_timestamp) = 2024;

[User] List document names, types, and upload timestamps for documents uploaded after '2024-01-01'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01'

[User] Filter the results to only include documents of type 'Contract'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract'

[User] Only show documents with version 3.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' AND version  =  3

[User] Remove the version filter, add the document description, and order by upload timestamp.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp ,  description FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' ORDER BY upload_timestamp

[User] List the document name, upload timestamp, and the full name of the lawyer who uploaded it, for all documents associated with case number 'CASE123'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123'

[User] Only include documents of type 'Pleading'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading'

[User] Also show the version and restrict results to documents with version greater than 1.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T1.version ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading' AND T1.version  >  1

[User] Find pairs of documents within the same case that were uploaded on the same day but by different lawyers. Show the case_id, upload_date, document_id and uploader_id for both documents in the pair.

[Assistant] SELECT d1.case_id, DATE(d1.upload_timestamp) AS upload_date, d1.document_id AS document1_id, d1.uploaded_by_lawyer_id AS lawyer1_id, d2.document_id AS document2_id, d2.uploaded_by_lawyer_id AS lawyer2_id FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.case_id = d2.case_id AND DATE(d1.upload_timestamp) = DATE(d2.upload_timestamp) AND d1.uploaded_by_lawyer_id <> d2.uploaded_by_lawyer_id WHERE d1.document_id < d2.document_id;

[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 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 social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )

[User] How many users have followed more than one person in total?

[Assistant]
SELECT follower_user_id, COUNT(DISTINCT following_user_id) AS following_count
FROM social_media.follows
GROUP BY follower_user_id
HAVING COUNT(DISTINCT following_user_id) > 1;

[User] Find users who followed at least two different people on the same calendar day. For each such user, list their ID, the IDs of the two people they followed, and the creation times of those two follow events.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at);

[User] Also, only include pairs of follows where the two follow events happened within 30 minutes of each other on that same day.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at) AND ABS(EXTRACT(EPOCH FROM (f1.created_at - f2.created_at))) <= 1800;

[User] List all unique pairs of users where one follows the other, showing both the follower and following user ID.

[Assistant]
SELECT DISTINCT follower_user_id, following_user_id
FROM social_media.follows;

[User] Only include pairs where the follower_user_id is alphabetically less than the following_user_id.

[Assistant]
SELECT DISTINCT follower_user_id, following_user_id
FROM social_media.follows
WHERE follower_user_id < following_user_id;

[User] Show me all users who started following someone in May 2024, along with both the user ID of the follower and the followed user.

[Assistant]
SELECT follower_user_id, following_user_id
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01';

[User] Can you also include the follow_id and the exact follow creation timestamp?

[Assistant]
SELECT follow_id, follower_user_id, following_user_id, created_at
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01';

[User] Now only show follows where both the follower and following user IDs start with 'U2'.

[Assistant]
SELECT follow_id, follower_user_id, following_user_id, created_at
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01'
  AND follower_user_id LIKE 'U2%' AND following_user_id LIKE 'U2%';

[User] Order them by the creation time in descending order.

[Assistant]
SELECT follow_id, follower_user_id, following_user_id, created_at
FROM social_media.follows
WHERE created_at >= '2024-05-01' AND created_at < '2024-06-01'
  AND follower_user_id LIKE 'U2%' AND following_user_id LIKE 'U2%'
ORDER BY created_at DESC;

[User] How many users does each user follow? Show the follower user ID and the count.

[Assistant] SELECT follower_user_id, count(*) FROM social_media.follows GROUP BY follower_user_id;

[User] Find pairs of user IDs (A, B) such that user A follows user B, and user B also follows user A (mutual follows). List user A's ID and user B's ID.

[Assistant] SELECT T1.follower_user_id AS user_a, T1.following_user_id AS user_b FROM social_media.follows AS T1 JOIN social_media.follows AS T2 ON T1.follower_user_id = T2.following_user_id AND T1.following_user_id = T2.follower_user_id;

[User] Only show pairs where user B started following user A after user A started following user B. Also include the follow dates for both.

[Assistant] SELECT T1.follower_user_id AS user_a, T1.following_user_id AS user_b, T1.created_at AS user_a_follows_b_date, T2.created_at AS user_b_follows_a_date FROM social_media.follows AS T1 JOIN social_media.follows AS T2 ON T1.follower_user_id = T2.following_user_id AND T1.following_user_id = T2.follower_user_id WHERE T2.created_at > T1.created_at;

[User] Order the results by the date user B followed user A, from oldest to newest.

[Assistant] SELECT T1.follower_user_id AS user_a, T1.following_user_id AS user_b, T1.created_at AS user_a_follows_b_date, T2.created_at AS user_b_follows_a_date FROM social_media.follows AS T1 JOIN social_media.follows AS T2 ON T1.follower_user_id = T2.following_user_id AND T1.following_user_id = T2.follower_user_id WHERE T2.created_at > T1.created_at ORDER BY user_b_follows_a_date ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] List all medications with a description that includes the word 'antibiotic'.

[Assistant] SELECT * FROM healthcare.medications WHERE description ILIKE '%antibiotic%';

[User] Retrieve all pairs of medications that share the same generic_name but have different NDC codes. Show the first medication's ID, name, the second medication's ID, name, and the shared generic_name.

[Assistant] SELECT m1.medication_id AS med1_id, m1.medication_name AS med1_name, m2.medication_id AS med2_id, m2.medication_name AS med2_name, m1.generic_name FROM healthcare.medications m1 JOIN healthcare.medications m2 ON m1.generic_name = m2.generic_name AND m1.ndc_code <> m2.ndc_code WHERE m1.medication_id < m2.medication_id;

[User] Show the medication ID, medication name, and manufacturer for all entries where the generic name is not listed.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name IS NULL OR generic_name = '';

[User] For all medications, list the medication name, generic name, and the length of the description, but only for descriptions longer than 50 characters.

[Assistant] SELECT medication_name, generic_name, LENGTH(description) AS description_length FROM healthcare.medications WHERE LENGTH(description) > 50;

[User] I want to see pairs of medications that share the same manufacturer. Show each medication's name and its peer's medication_name along with the manufacturer.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer;

[User] Exclude any rows where a medication is paired with itself.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer AND t1.medication_id <> t2.medication_id;

[User] Now only include manufacturers 'Pfizer' or 'Moderna'.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer AND t1.medication_id <> t2.medication_id WHERE t1.manufacturer IN ('Pfizer','Moderna');

[User] I’m seeing duplicate pairs for reversed order. Remove reversed duplicates.

[Assistant] SELECT t1.medication_name AS med1_name, t2.medication_name AS med2_name, t1.manufacturer FROM healthcare.medications t1 JOIN healthcare.medications t2 ON t1.manufacturer = t2.manufacturer AND t1.medication_id < t2.medication_id WHERE t1.manufacturer IN ('Pfizer','Moderna');

[User] Show me the medication_id, medication_name, and manufacturer for all medications where the generic_name contains the word 'azole'.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE generic_name ILIKE '%azole%';

[User] Can you also include the ndc_code and only show medications where the manufacturer field is not null?

[Assistant] SELECT medication_id, medication_name, manufacturer, ndc_code FROM healthcare.medications WHERE generic_name ILIKE '%azole%' AND manufacturer IS NOT NULL;

[User] List the medication IDs and names for all entries where the description is missing or empty.

[Assistant] SELECT medication_id, medication_name FROM healthcare.medications WHERE description IS NULL OR description = '';

[User] For those medications, please also show the manufacturer and sort the results by medication name in ascending order.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE description IS NULL OR description = '' ORDER BY medication_name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] Show me the total hours spent by each lawyer for each case, along with the case number and lawyer ID.

[Assistant]
SELECT t.case_id, c.case_number, t.lawyer_id, SUM(t.hours_spent) AS total_hours
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
GROUP BY t.case_id, c.case_number, t.lawyer_id;

[User] Only include lawyers who have logged more than 10 hours on a given case.

[Assistant]
SELECT t.case_id, c.case_number, t.lawyer_id, SUM(t.hours_spent) AS total_hours
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
GROUP BY t.case_id, c.case_number, t.lawyer_id
HAVING SUM(t.hours_spent) > 10;

[User] Additionally, restrict to cases that are currently 'Open'.

[Assistant]
SELECT t.case_id, c.case_number, t.lawyer_id, SUM(t.hours_spent) AS total_hours
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
WHERE c.status = 'Open'
GROUP BY t.case_id, c.case_number, t.lawyer_id
HAVING SUM(t.hours_spent) > 10;

[User] List all appointments with their subject and associated case number for appointments that have both a case_id and a non-null location.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL AND a.location IS NOT NULL;

[User] Show only those appointments where the status is not 'cancelled'.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL AND a.location IS NOT NULL AND (a.status IS NULL OR a.status <> 'cancelled');

[User] Also, only show appointments starting after June 1st, 2024.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL
  AND a.location IS NOT NULL
  AND (a.status IS NULL OR a.status <> 'cancelled')
  AND a.start_time > '2024-06-01';

[User] Remove any appointments that are linked to cases with a status of 'Closed'.

[Assistant]
SELECT a.appointment_id, a.subject, a.case_id, c.case_number
FROM legal_services.appointments a
JOIN legal_services.cases c ON a.case_id = c.case_id
WHERE a.case_id IS NOT NULL
  AND a.location IS NOT NULL
  AND (a.status IS NULL OR a.status <> 'cancelled')
  AND a.start_time > '2024-06-01'
  AND c.status <> 'Closed';

[User] Show the total billed hours and total billed amount for each case that has at least one billed and billable time entry.

[Assistant]
SELECT t.case_id, c.case_number, SUM(t.hours_spent) AS total_billed_hours, SUM(t.hours_spent * t.billing_rate) AS total_billed_amount
FROM legal_services.time_entries t
JOIN legal_services.cases c ON t.case_id = c.case_id
WHERE t.is_billable = TRUE AND t.is_billed = TRUE
GROUP BY t.case_id, c.case_number
HAVING COUNT(*) >= 1;

[User] Show me all cases where the description contains the word 'agreement'. Display the case ID, case name, and description.

[Assistant] SELECT case_id, case_name, description FROM legal_services.cases WHERE description ILIKE '%agreement%';

[User] Also include cases where the description contains 'contract', and make sure the status is 'Pending'.

[Assistant] SELECT case_id, case_name, description FROM legal_services.cases WHERE (description ILIKE '%agreement%' OR description ILIKE '%contract%') AND status = 'Pending';

[User] Now, show only those cases from the previous list that were opened in the last 90 days.

[Assistant] SELECT case_id, case_name, description FROM legal_services.cases WHERE (description ILIKE '%agreement%' OR description ILIKE '%contract%') AND status = 'Pending' AND date_opened >= CURRENT_DATE - INTERVAL '90 days';

[User] Finally, order the results by date opened descending and only show the case name and description.

[Assistant] SELECT case_name, description FROM legal_services.cases WHERE (description ILIKE '%agreement%' OR description ILIKE '%contract%') AND status = 'Pending' AND date_opened >= CURRENT_DATE - INTERVAL '90 days' ORDER BY date_opened DESC;

[User] List the case ID, case number, and case name for all cases with status 'Open'.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open';

[User] Now, only show those cases opened in the year 2023.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023;

[User] Great, could you also show the lead lawyer ID and count how many open cases each of those lawyers has opened in 2023, displaying this count alongside the case details for each case? Order the results by date opened ascending.

[Assistant] SELECT c.case_id, c.case_number, c.case_name, c.lead_lawyer_id, lawyer_case_counts.case_count FROM legal_services.cases AS c JOIN ( SELECT lead_lawyer_id, COUNT(*) AS case_count FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023 GROUP BY lead_lawyer_id ) AS lawyer_case_counts ON c.lead_lawyer_id = lawyer_case_counts.lead_lawyer_id WHERE c.status = 'Open' AND EXTRACT(YEAR FROM c.date_opened) = 2023 ORDER BY c.date_opened ASC;

[User] Calculate the average number of days cases stay open before being closed, grouped by case type. Only consider cases that have a date closed.

[Assistant] SELECT case_type, AVG(DATE_PART('day', date_closed - date_opened)) AS average_duration_days FROM legal_services.cases WHERE status = 'Closed' AND date_closed IS NOT NULL GROUP BY case_type;

[User] Exclude case types where the average duration is less than 100 days and order the results by average duration descending.

[Assistant] SELECT case_type, AVG(DATE_PART('day', date_closed - date_opened)) AS average_duration_days FROM legal_services.cases WHERE status = 'Closed' AND date_closed IS NOT NULL GROUP BY case_type HAVING AVG(DATE_PART('day', date_closed - date_opened)) >= 100 ORDER BY average_duration_days 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.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )

[User] Show each staff member's first name, last name, and the average base rate of room types available at the property where they work.

[Assistant] SELECT T1.first_name, T1.last_name, T2.avg_base_rate FROM hospitality_technology.staff AS T1 JOIN (SELECT property_id, AVG(base_rate) AS avg_base_rate FROM hospitality_technology.room_types GROUP BY property_id) AS T2 ON T1.property_id = T2.property_id

[User] List all staff members hired in 2024, showing 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) = 2024

[User] Now, only include those whose position is 'Manager'.

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

[User] Retrieve all room types with a base_rate above 150 for each property.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150;

[User] Also filter to only include room types with max_occupancy >= 3.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150
  AND max_occupancy >= 3;

[User] Finally, show guest first and last names of guests created after '2023-01-01' who could book these room types.

[Assistant]
SELECT g.first_name, g.last_name, rt.property_id, rt.type_name, rt.base_rate
FROM hospitality_technology.room_types rt
CROSS JOIN hospitality_technology.guests g
WHERE rt.base_rate > 150
  AND rt.max_occupancy >= 3
  AND g.created_at > '2023-01-01';

[User] Which room types have a base rate above 250 USD, and what are their maximum occupancies?

[Assistant]
SELECT room_type_id, type_name, base_rate, max_occupancy
FROM hospitality_technology.room_types
WHERE base_rate > 250;

[User] For these room types, can you also add the property_id?

[Assistant]
SELECT room_type_id, property_id, type_name, base_rate, max_occupancy
FROM hospitality_technology.room_types
WHERE base_rate > 250;

[User] Now join this with the payments table to show the total payment amount for each property where such a room type exists.

[Assistant]
SELECT r.property_id, SUM(p.amount) AS total_payment_amount
FROM hospitality_technology.room_types r
JOIN hospitality_technology.payments p ON r.property_id = p.reservation_id
WHERE r.base_rate > 250
GROUP BY r.property_id;

[User] Show all service orders with the service_id, guest's full name, and the status of each order.

[Assistant]
SELECT so.order_id, so.service_id, g.first_name, g.last_name, so.status
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id;

[User] Only display service orders with status 'InProgress' or 'Pending', and sort them by order_timestamp ascending.

[Assistant]
SELECT so.order_id, so.service_id, g.first_name, g.last_name, so.status
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
WHERE so.status IN ('InProgress', 'Pending')
ORDER BY so.order_timestamp ASC;

[User] List all reviews that have a staff response, including the review comment, staff response text, and the ID of the staff who responded.

[Assistant] SELECT comment, staff_response, response_staff_id FROM hospitality_technology.reviews WHERE staff_response IS NOT NULL

[User] Filter this list to only include reviews submitted in 2023 with an overall rating of 3 or less.

[Assistant] SELECT comment, staff_response, response_staff_id FROM hospitality_technology.reviews WHERE staff_response IS NOT NULL AND EXTRACT(YEAR FROM review_date) = 2023 AND rating_overall <= 3

[User] Now, only show responses from staff members whose position is 'Front Desk'.

[Assistant] SELECT r.comment, r.staff_response, s.staff_id, s.first_name, s.last_name, s.position FROM hospitality_technology.reviews r JOIN hospitality_technology.staff s ON r.response_staff_id = s.staff_id WHERE r.staff_response IS NOT NULL AND EXTRACT(YEAR FROM r.review_date) = 2023 AND r.rating_overall <= 3 AND s.position = 'Front Desk'


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 smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )

[User] Show me the top 5 smart money addresses by profit on the Ethereum chain, along with their most profitable token and ROI, but only include addresses with a realized profit ratio above 70%.

[Assistant] SELECT address, most_profit_token, roi FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 ORDER BY profit DESC LIMIT 5;

[User] Can you also include their rank and filter to only show addresses with ROI greater than 50%?

[Assistant] SELECT address, most_profit_token, roi, rank FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 70 AND roi > 50 ORDER BY profit DESC LIMIT 5;

[User] How many distinct addresses achieved a realized_ratio higher than 0.9 last month?

[Assistant] SELECT COUNT(DISTINCT address) FROM smart_money_profit WHERE realized_ratio > 0.9;

[User] Can you also break down the count by chain?

[Assistant] SELECT chain, COUNT(DISTINCT address) AS address_count FROM smart_money_profit WHERE realized_ratio > 0.9 GROUP BY chain;

[User] Show the top 3 addresses by ROI on the Polygon chain, including profit and the most profitable token.

[Assistant] SELECT address, roi, profit, most_profit_token FROM smart_money_profit WHERE chain = 'Polygon' ORDER BY roi DESC LIMIT 3;

[User] Now, also include addresses from Arbitrum and display the chain in the results.

[Assistant] SELECT address, chain, roi, profit, most_profit_token FROM smart_money_profit WHERE chain IN ('Polygon', 'Arbitrum') ORDER BY roi DESC LIMIT 3;

[User] I got repeated addresses from both chains. Please show the top 3 per chain separately.

[Assistant] SELECT address, chain, roi, profit, most_profit_token FROM ( SELECT address, chain, roi, profit, most_profit_token, ROW_NUMBER() OVER (PARTITION BY chain ORDER BY roi DESC) AS rn FROM smart_money_profit WHERE chain IN ('Polygon', 'Arbitrum') ) t WHERE rn <= 3 ORDER BY chain, roi DESC;

[User] Add the last_trade_time to your output.

[Assistant] SELECT address, chain, roi, profit, most_profit_token, last_trade_time FROM ( SELECT address, chain, roi, profit, most_profit_token, last_trade_time, ROW_NUMBER() OVER (PARTITION BY chain ORDER BY roi DESC) AS rn FROM smart_money_profit WHERE chain IN ('Polygon', 'Arbitrum') ) t WHERE rn <= 3 ORDER BY chain, roi DESC;

[User] Calculate the average realized_ratio across all addresses.

[Assistant]
SELECT AVG(realized_ratio) AS average_realized_ratio
FROM smart_money_profit;

[User] Show me the top 5 smart money addresses by profit on the Ethereum chain, along with their most profitable token and ROI, but only include addresses with a realized profit ratio above 80%.

[Assistant] SELECT address, most_profit_token, roi FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 80 ORDER BY profit DESC LIMIT 5;

[User] Can you also include the last trade time for these addresses and filter to only show results with ROI greater than 100%?

[Assistant] SELECT address, most_profit_token, roi, last_trade_time FROM smart_money_profit WHERE chain = 'Ethereum' AND realized_ratio > 80 AND roi > 100 ORDER BY profit DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] Count the number of passengers in each month of the year 2024 based on their created_at date.

[Assistant]
SELECT EXTRACT(MONTH FROM created_at) AS month, COUNT(*) AS passenger_count
FROM transportation.passengers
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
GROUP BY EXTRACT(MONTH FROM created_at)
ORDER BY month;

[User] Now, only include months where the passenger_count exceeds 50.

[Assistant]
SELECT EXTRACT(MONTH FROM created_at) AS month, COUNT(*) AS passenger_count
FROM transportation.passengers
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
GROUP BY EXTRACT(MONTH FROM created_at)
HAVING COUNT(*) > 50
ORDER BY month;

[User] I want to see how many passengers were created each month.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers GROUP BY month;

[User] Only include months after January 2021.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' GROUP BY month;

[User] Also exclude records where email is NULL.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' AND email IS NOT NULL GROUP BY month;

[User] Sort the results in descending order by passenger_count and limit to the top 6 months.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' AND email IS NOT NULL GROUP BY month ORDER BY passenger_count DESC LIMIT 6;

[User] Show each pair of passengers who share the same loyalty_program_id but have different registration times. Return p1.first_name AS earlier, p2.first_name AS later, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Actually, only include pairs where the earlier registration happened before '2023-01-01'.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.created_at < '2023-01-01';

[User] List each passenger's first_name, last_name along with another passenger's first_name and last_name who share the same loyalty_program_id. Label them as member and peer.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id;

[User] I only want pairs where the member registered before the peer and include their created_at timestamps.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at;

[User] Then sort the result by member_created ascending and peer_created descending.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at
ORDER BY p1.created_at ASC, p2.created_at DESC;

[User] List pairs of passengers where one registered before another, including both their first names, created_at timestamps, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Only include pairs where both passengers are in a loyalty_program and the time difference between their registrations is more than 30 days.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.loyalty_program_id IS NOT NULL
  AND p2.loyalty_program_id IS NOT NULL
  AND p2.created_at - p1.created_at > INTERVAL '30 days';

[User] Now also order the results by the time difference descending and limit to the top 5.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.loyalty_program_id IS NOT NULL
  AND p2.loyalty_program_id IS NOT NULL
  AND p2.created_at - p1.created_at > INTERVAL '30 days'
ORDER BY (p2.created_at - p1.created_at) DESC
LIMIT 5;

[User] List the first and last names of passengers who share the same loyalty_program_id with at least one other passenger.

[Assistant]
SELECT DISTINCT p1.first_name, p1.last_name
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id AND p1.passenger_id <> p2.passenger_id
WHERE p1.loyalty_program_id IS NOT NULL;

[User] Now refine this list to only include passengers who joined after January 1, 2023.

[Assistant]
SELECT DISTINCT p1.first_name, p1.last_name
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id AND p1.passenger_id <> p2.passenger_id
WHERE p1.loyalty_program_id IS NOT NULL
  AND p1.created_at >= '2023-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
Index 'suppliers'. Mapping: { properties: { supplier_id: { type: 'keyword' }, supplier_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, address: { type: 'text' }, country: { type: 'keyword' }, contact_person: { type: 'text', index: false }, contact_email: { type: 'keyword' }, quality_rating: { type: 'float' }, certified_date: { type: 'date' } } }. Document _id can be supplier_id.

[User] 특정 품질 등급 이상의 공급업체를 조회하고 싶습니다. 품질 등급, 공급업체 이름, 국가를 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "range": {
      "quality_rating": {
        "gte": 4.0
      }
    }
  },
  "_source": ["supplier_name", "country", "quality_rating"]
}

[User] 특정 국가에 속한 공급업체만 추가로 필터링하고 싶습니다. 예를 들어, 일본 소속 공급업체로 제한하고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating"]
}

[User] 연락처 담당자 이름과 인증 날짜도 결과에 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating", "contact_person", "certified_date"]
}

[User] 인증 날짜를 기준으로 오름차순 정렬을 추가해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating", "contact_person", "certified_date"],
  "sort": [
    {
      "certified_date": {
        "order": "asc"
      }
    }
  ]
}

[User] 특정 국가의 모든 공급업체 정보를 조회하고 싶습니다. 국가 이름, 공급업체 이름, 주소, 품질 등급을 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "term": {
      "country": "Korea"
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 품질 등급이 3.5 이상인 공급업체만 보고 싶습니다. 어떻게 수정해야 하나요?

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 인증 날짜가 2020년 이후인 공급업체만 추가로 필터링하고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"]
}

[User] 결과를 품질 등급 기준으로 내림차순 정렬해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"],
  "sort": [
    {
      "quality_rating": {
        "order": "desc"
      }
    }
  ]
}

[User] 특정 공급업체 ID로 공급업체의 세부 정보를 조회하고 싶습니다. 모든 필드를 포함해 주세요.

[Assistant] GET suppliers/_doc/{supplier_id}

[User] 만약 여러 공급업체 ID를 한 번에 조회하고 싶다면 어떻게 해야 하나요?

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  }
}

[User] 조회 결과에서 공급업체 이름과 연락처 이메일만 보고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  },
  "_source": ["supplier_name", "contact_email"]
}

[User] 결과를 공급업체 이름 기준으로 오름차순 정렬해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  },
  "_source": ["supplier_name", "contact_email"],
  "sort": [
    {
      "supplier_name.keyword": {
        "order": "asc"
      }
    }
  ]
}


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.

[User] 特定の職種の従業員情報を取得したいです。従業員ID、名前、職種、雇用日を表示してください。

[Assistant]
db.employees.find(
    { job_title: '<specific_job_title>' },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用日が2020年1月1日以降の従業員だけに絞り込むことはできますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') }
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用ステータスが「Active」の従業員だけをさらに条件に加えられますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] スキル認定情報も結果に含めてください。

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, skill_certifications: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 特定の組み立てラインに関連するすべての手順を取得したいです。ラインIDと手順名、手順番号、必要なスキルレベルを含めてください。

[Assistant]
db.assembly_steps.find(
    { line_id: '<specific_line_id>' },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] さらに、必要なスキルレベルが「Senior Technician」以上の手順だけを表示できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 標準作業時間が3時間以上の手順も条件に追加できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 }
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 最後に、作業場所が「Workstation_B」の手順だけに絞り込んでください。

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 },
        workstation: 'Workstation_B'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 特定の組み立てラインに割り当てられた従業員とそのラインの手順情報を取得したいです。従業員ID、名前、職種と手順名、手順番号を含めてください。

[Assistant]
db.employees.aggregate([
    { $match: { assigned_line_id: '<specific_line_id>' } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 従業員の雇用ステータスが「Active」のデータだけに絞り込むことはできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 手順の必要なスキルレベルが「Junior Technician」以上のものだけを表示するようにできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 最後に、従業員の雇用日も結果に含めて、雇用日順に並べ替えてください。

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        hire_date: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { hire_date: -1, 'steps.step_number': 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 legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )

[User] Show me the names, founding dates, and websites of all law firms whose name contains the word 'Legal' and were founded after the year 2005. Sort the results by their founding date.

[Assistant] SELECT firm_name, founded_date, website FROM legal_services.law_firms WHERE firm_name LIKE '%Legal%' AND founded_date > '2005-12-31' ORDER BY founded_date ASC;

[User] List pairs of law firms that are located at the same address. Display the names of both firms and the shared address, ensuring the address is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL;

[User] Only show pairs where both firms were founded before 2020.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL AND EXTRACT(YEAR FROM t1.founded_date) < 2020 AND EXTRACT(YEAR FROM t2.founded_date) < 2020;

[User] Show me the count of law firms grouped by the year they were founded. Include the founding year and the number of firms.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL
GROUP BY
  founding_year;

[User] Only include years where the firm count is greater than 3.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3;

[User] Also, restrict this count to only include firms that have a website listed.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL AND website IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3;

[User] Order the results by the founding year in ascending order.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL AND website IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3
ORDER BY
  founding_year ASC;

[User] Find all law firms that share the same address, listing each address and the two firm names.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id;

[User] Actually, only show addresses containing the word 'Street'.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id WHERE f1.address LIKE '%Street%';

[User] List all pairs of law firms founded in the same year, showing the two firm names and the shared year.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id <> f2.firm_id;

[User] Actually, only include years after 2000.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id <> f2.firm_id WHERE EXTRACT(YEAR FROM f1.founded_date) > 2000;

[User] And ensure each pair only appears once.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id < f2.firm_id WHERE EXTRACT(YEAR FROM f1.founded_date) > 2000;

[User] Find pairs of law firms that share the same managing partner. List the names of both firms and the managing partner ID, but only show pairs where the managing partner ID is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id IS NOT NULL;

[User] Refine this to only include pairs where the managing partner ID starts with 'MPG_'.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id LIKE 'MPG_%';

[User] Further filter to only show pairs where both firms were founded after 2015.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id LIKE 'MPG_%' AND EXTRACT(YEAR FROM t1.founded_date) > 2015 AND EXTRACT(YEAR FROM t2.founded_date) > 2015;


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.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

[User] List all pairs of hashtags created on the same calendar date, showing both tag names and the creation date.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Also, only include each pair once by enforcing the first tag_name to be alphabetically before the second.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.tag_name < h2.tag_name;

[User] How many hashtags were created in each month of 2024?

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

[User] List all pairs of hashtags that were created on the same date. Show both tag names and the creation date.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id;

[User] Actually, only include pairs where both tag names start with the letter 'S'.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id
WHERE a.tag_name LIKE 'S%'
  AND b.tag_name LIKE 'S%';

[User] Count the total number of hashtags.

[Assistant] SELECT COUNT(*) FROM social_media.hashtags;

[User] Show me the hashtag IDs and their names.

[Assistant] SELECT hashtag_id, tag_name FROM social_media.hashtags;

[User] I also want to see when each hashtag was created.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags;

[User] Filter the list to only show hashtags whose name starts with the letter 'S'.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE tag_name LIKE 'S%';

[User] I need all pairs of hashtags that start with the same first two letters. Show both tag names.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Please filter these pairs to include only those created in the same year.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND EXTRACT(YEAR FROM h1.created_at) = EXTRACT(YEAR FROM h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Now also include the year in the output.

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Use Hashes. Key pattern: 'inv:<inventory_record_id>'. Example: HSET inv:INVREC500 component_id "component:WINGBOLT" quantity 5000 location_warehouse "WH3" batch_number "BCH778899" ... Consider Sorted Set by expiry date: ZADD component_expiry:<component_id> <expiry_timestamp> <inventory_record_id>.

[User] Can you help me fetch the inventory records for components stored in a specific warehouse, along with their expiry dates?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter this to show only records for a specific component ID?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] What if I want to exclude records with quantities below a certain threshold, like 100?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES
# Note: Filtering by quantity would require additional scripting or client-side processing as Redis does not support direct filtering on hash field values.

[User] Can you also sort the results by expiry date in descending order?

[Assistant]
HGETALL inv:<inventory_record_id>
ZREVRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you help me retrieve the inventory details for a specific component ID, including the quantity and warehouse location?

[Assistant] HGETALL inv:<inventory_record_id>

[User] Can you also include the batch number for that inventory record?

[Assistant] HGETALL inv:<inventory_record_id>

[User] If I want to check the expiry date for this component, how can I retrieve that information?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter the results to show only inventory records with an expiry date after a specific timestamp?

[Assistant] ZRANGEBYSCORE component_expiry:<component_id> <specific_timestamp> +inf WITHSCORES

[User] I need to get the inventory quantity and location for a specific batch number. Can you help with that?

[Assistant] HGETALL inv:<inventory_record_id>

[User] Can you also show me the component ID associated with this batch?

[Assistant] HGETALL inv:<inventory_record_id>

[User] If I want to retrieve multiple inventory records for the same component ID, how can I do that?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1

[User] Can you sort those records by expiry date in ascending order?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES


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.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )

[User] Show me all transactions along with the related account IDs where the transaction type is 'Transfer'.

[Assistant] SELECT transaction_id, account_id, related_account_id, transaction_type, amount, currency, transaction_date, status FROM financial_services.transactions WHERE transaction_type = 'Transfer';

[User] Further, only include transactions where the currency is 'USD'.

[Assistant] SELECT transaction_id, account_id, related_account_id, transaction_type, amount, currency, transaction_date, status FROM financial_services.transactions WHERE transaction_type = 'Transfer' AND currency = 'USD';

[User] List transactions where the description includes another transaction's reference_number, showing both transaction IDs and the referenced reference_number.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%';

[User] Only include cases where the referenced transaction has status 'COMPLETED'.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%'
WHERE t2.status = 'COMPLETED';

[User] Finally, order the output by the source transaction date ascending.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%'
WHERE t2.status = 'COMPLETED'
ORDER BY t1.transaction_date ASC;

[User] Give me the total transaction amount and the total count of transactions per day for each currency.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency;

[User] Exclude days where the summed amount is less than 50000.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000;

[User] Sort the results by the total_amount descending and limit to the top 5 records.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000
ORDER BY total_amount DESC
LIMIT 5;

[User] I want to find pairs of transactions where one transaction’s related_account_id matches the other’s account_id, indicating reciprocal transfers between accounts.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id;

[User] Actually, limit these transactions to those that occurred in the last 90 days.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id
WHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days';

[User] And make sure both transactions use the same currency.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id
WHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
  AND t1.currency = t2.currency;

[User] Finally, order the output by the outgoing transaction date descending.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id
WHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
  AND t1.currency = t2.currency
ORDER BY t1.transaction_date DESC;

[User] I want to see the total sum of transaction amounts and their average amount for each transaction_type along with the total number of transactions, grouped by currency.

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions GROUP BY transaction_type, currency;

[User] Can you filter out transactions where the status is not 'SUCCESSFUL' or 'PENDING'?

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions WHERE status IN ('SUCCESSFUL', 'PENDING') GROUP BY transaction_type, currency;

[User] Also, show only the results where the total_amount is greater than 10000.

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions WHERE status IN ('SUCCESSFUL', 'PENDING') GROUP BY transaction_type, currency HAVING SUM(amount) > 10000;

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

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions WHERE status IN ('SUCCESSFUL', 'PENDING') GROUP BY transaction_type, currency HAVING SUM(amount) > 10000 ORDER BY average_amount ASC;

[User] Show the total incoming and outgoing amounts for each account_id, along with the number of transactions for each type (incoming and outgoing). An incoming transaction is when the account_id appears as related_account_id.

[Assistant] SELECT account_id, SUM(CASE WHEN related_account_id IS NOT NULL THEN amount ELSE 0 END) AS outgoing_amount, COUNT(CASE WHEN related_account_id IS NOT NULL THEN 1 END) AS outgoing_transactions, SUM(CASE WHEN account_id IN (SELECT DISTINCT related_account_id FROM financial_services.transactions WHERE related_account_id IS NOT NULL) THEN 0 ELSE amount END) AS incoming_amount, COUNT(CASE WHEN account_id IN (SELECT DISTINCT related_account_id FROM financial_services.transactions WHERE related_account_id IS NOT NULL) THEN NULL ELSE 1 END) AS incoming_transactions FROM financial_services.transactions GROUP BY account_id;

[User] The query did not give the correct incoming transactions. Please show incoming amounts where the account_id is equal to related_account_id.

[Assistant] SELECT account_id, SUM(CASE WHEN account_id = related_account_id THEN amount ELSE 0 END) AS incoming_amount, COUNT(CASE WHEN account_id = related_account_id THEN 1 END) AS incoming_transactions, SUM(CASE WHEN account_id <> related_account_id THEN amount ELSE 0 END) AS outgoing_amount, COUNT(CASE WHEN account_id <> related_account_id THEN 1 END) AS outgoing_transactions FROM financial_services.transactions GROUP BY account_id;

[User] Now, show only accounts with more than 5 incoming transactions.

[Assistant] SELECT account_id, SUM(CASE WHEN account_id = related_account_id THEN amount ELSE 0 END) AS incoming_amount, COUNT(CASE WHEN account_id = related_account_id THEN 1 END) AS incoming_transactions, SUM(CASE WHEN account_id <> related_account_id THEN amount ELSE 0 END) AS outgoing_amount, COUNT(CASE WHEN account_id <> related_account_id THEN 1 END) AS outgoing_transactions FROM financial_services.transactions GROUP BY account_id HAVING COUNT(CASE WHEN account_id = related_account_id THEN 1 END) > 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 hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
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 text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, 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 )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

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

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

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

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

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

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

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

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

[User] Show me all staff members along with their positions and the names of the properties they work at.

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

[User] Only include staff who are not currently active.

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

[User] For each reservation, show the guest's first and last name, the property name, and the names of all services ordered during that reservation.

[Assistant]
SELECT r.reservation_id, g.first_name, g.last_name, p.property_name, s.service_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id
JOIN hospitality_technology.staff g ON r.guest_id = g.staff_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id;

[User] Only include reservations where at least 3 different services were ordered, and sort by the guest's last name ascending.

[Assistant]
SELECT r.reservation_id, g.first_name, g.last_name, p.property_name, GROUP_CONCAT(DISTINCT s.service_name) AS services_ordered
FROM hospitality_technology.reservations r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id
JOIN hospitality_technology.staff g ON r.guest_id = g.staff_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY r.reservation_id, g.first_name, g.last_name, p.property_name
HAVING COUNT(DISTINCT s.service_id) >= 3
ORDER BY g.last_name ASC;

[User] For each room, list the room number, property name, and the type name of the room.

[Assistant]
SELECT r.room_number, p.property_name, rt.type_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id;

[User] Only include rooms located on floor 1 or 2 with the feature 'Sea View'.

[Assistant]
SELECT r.room_number, p.property_name, rt.type_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.floor IN (1, 2) AND r.features ILIKE '%Sea View%';

[User] The SQL failed because 'ILIKE' is not supported. Please replace it with an alternative.

[Assistant]
SELECT r.room_number, p.property_name, rt.type_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.floor IN (1, 2) AND LOWER(r.features) LIKE '%sea view%';

[User] Show me the count of rooms by status.

[Assistant]
SELECT status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY status;

[User] Actually, I need that breakdown by property as well.

[Assistant]
SELECT property_id,
       status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY property_id, status
ORDER BY property_id, status;

[User] Get me a list of all public reviews along with the guest's full name and the staff member who responded, including the overall rating and review date.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE;

[User] Filter those to only include reviews with an overall rating above 4.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE
  AND rev.rating_overall > 4;

[User] Also sort the results by review_date in ascending order.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE
  AND rev.rating_overall > 4
ORDER BY rev.review_date ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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