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 manufacturing.materials (
    material_id character varying(64) NOT NULL,  -- unique identifier for the material
    material_name character varying(128) NOT NULL, -- common name (e.g., Titanium Alloy Grade 5, Carbon Fiber Prepreg)
    specification character varying(255), -- specification standard (e.g., AMS 4928)
    description text, -- detailed description of properties
    density_kg_m3 numeric(10, 4), -- density in kg per cubic meter
    tensile_strength_mpa integer, -- tensile strength in Megapascals
    PRIMARY KEY (material_id)
)
CREATE TABLE manufacturing.assembly_steps (
    step_id character varying(64) NOT NULL, -- unique identifier for an assembly step/task
    line_id character varying(64) NOT NULL, -- FK to the assembly line where this step occurs
    step_number integer NOT NULL, -- sequence number of the step on the line
    step_name character varying(255) NOT NULL, -- name of the task (e.g., Install Wing Root Fairing)
    description text, -- detailed instructions or description
    standard_duration_hours numeric(8,2), -- estimated time to complete the step
    required_skill_level character varying(50), -- skill level needed (e.g., 'Mechanic II', 'Electrician I')
    workstation character varying(100), -- specific workstation or area for the step
    PRIMARY KEY (step_id)
)

[User] 特定の材料を使用しているコンポーネントの組み立て手順を確認したいです。材料IDと材料名、組み立て手順のステップ名と説明を含めてください。

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id';

[User] さらに、特定のスキルレベルが必要な手順だけを表示するようにできますか？例えば「Mechanic II」のみ。

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id'
AND s.required_skill_level = 'Mechanic II';

[User] もし標準作業時間が2時間以上の手順だけを絞り込みたい場合はどうすればいいですか？

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id'
AND s.required_skill_level = 'Mechanic II'
AND s.standard_duration_hours >= 2;

[User] 最後に、ステップ番号順に並べ替えて結果を表示してください。

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id'
AND s.required_skill_level = 'Mechanic II'
AND s.standard_duration_hours >= 2
ORDER BY s.step_number;

[User] 特定のラインIDに関連する組み立て手順と、使用されている材料の情報を取得したいです。ラインID、ステップ名、材料名、材料の説明を含めてください。

[Assistant]
SELECT s.line_id, s.step_name, m.material_name, m.description
FROM manufacturing.assembly_steps s
JOIN manufacturing.materials m ON s.step_id = m.material_id
WHERE s.line_id = 'specific_line_id';

[User] さらに、特定の作業場所での手順だけを表示するようにできますか？例えば「Workstation_A」のみ。

[Assistant]
SELECT s.line_id, s.step_name, m.material_name, m.description
FROM manufacturing.assembly_steps s
JOIN manufacturing.materials m ON s.step_id = m.material_id
WHERE s.line_id = 'specific_line_id'
AND s.workstation = 'Workstation_A';

[User] もし標準作業時間が1時間未満の手順を除外したい場合はどうすればいいですか？

[Assistant]
SELECT s.line_id, s.step_name, m.material_name, m.description
FROM manufacturing.assembly_steps s
JOIN manufacturing.materials m ON s.step_id = m.material_id
WHERE s.line_id = 'specific_line_id'
AND s.workstation = 'Workstation_A'
AND s.standard_duration_hours >= 1;

[User] 最後に、ステップ番号を基準に昇順で並べ替えてください。

[Assistant]
SELECT s.line_id, s.step_name, m.material_name, m.description
FROM manufacturing.assembly_steps s
JOIN manufacturing.materials m ON s.step_id = m.material_id
WHERE s.line_id = 'specific_line_id'
AND s.workstation = 'Workstation_A'
AND s.standard_duration_hours >= 1
ORDER BY s.step_number ASC;

[User] 特定の材料の詳細情報を取得したいです。材料ID、材料名、仕様、密度を取得してください。

[Assistant]
SELECT material_id, material_name, specification, density_kg_m3
FROM manufacturing.materials
WHERE material_id = 'specific_material_id';

[User] さらに、引張強度が500MPa以上の材料だけを表示するようにできますか？

[Assistant]
SELECT material_id, material_name, specification, density_kg_m3
FROM manufacturing.materials
WHERE material_id = 'specific_material_id'
AND tensile_strength_mpa >= 500;

[User] もし密度が2000kg/m3未満の材料を除外したい場合はどうすればいいですか？

[Assistant]
SELECT material_id, material_name, specification, density_kg_m3
FROM manufacturing.materials
WHERE material_id = 'specific_material_id'
AND tensile_strength_mpa >= 500
AND density_kg_m3 >= 2000;

[User] 最後に、材料名をアルファベット順に並べ替えてください。

[Assistant]
SELECT material_id, material_name, specification, density_kg_m3
FROM manufacturing.materials
WHERE material_id = 'specific_material_id'
AND tensile_strength_mpa >= 500
AND density_kg_m3 >= 2000
ORDER BY material_name;


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.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)

[User] How many clients are registered with an active status?

[Assistant] SELECT COUNT(*) FROM legal_services.clients WHERE status = 'active';

[User] Could you also tell me the average number of days since registration for these active clients?

[Assistant] SELECT AVG(EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - date_registered)) / 86400) AS average_days_since_registration FROM legal_services.clients WHERE status = 'active';

[User] What about clients with a 'prospect' status? Show me the count and the average registration duration in days for them as well.

[Assistant] SELECT COUNT(*), AVG(EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - date_registered)) / 86400) AS average_days_since_registration FROM legal_services.clients WHERE status = 'prospect';

[User] Can you show me both statuses ('active' and 'prospect') in the same query, listing the status, count, and average duration, and order by count descending?

[Assistant] SELECT status, COUNT(*), AVG(EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - date_registered)) / 86400) AS average_days_since_registration FROM legal_services.clients WHERE status IN ('active', 'prospect') GROUP BY status ORDER BY count DESC;

[User] List the names of all clients that are associated with cases led by lawyers specializing in 'Intellectual Property'.

[Assistant]
SELECT DISTINCT c.first_name, c.last_name
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE l.specialization ILIKE '%Intellectual Property%';

[User] Actually, I also want to see the lawyer's full name and their specialization next to each client.

[Assistant]
SELECT DISTINCT c.first_name AS client_first_name, c.last_name AS client_last_name, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, l.specialization
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE l.specialization ILIKE '%Intellectual Property%';

[User] Can you further filter this to only show clients who registered after January 1, 2023?

[Assistant]
SELECT DISTINCT c.first_name AS client_first_name, c.last_name AS client_last_name, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, l.specialization
FROM legal_services.cases cs
JOIN legal_services.clients c ON cs.client_id = c.client_id
JOIN legal_services.lawyers l ON cs.lead_lawyer_id = l.lawyer_id
WHERE l.specialization ILIKE '%Intellectual Property%'
  AND c.date_registered > '2023-01-01';

[User] Show all law firms with more than one partner assigned. Display the law firm name and the number of partners.

[Assistant]
SELECT lf.firm_name, COUNT(l.lawyer_id) AS partner_count
FROM legal_services.law_firms lf
JOIN legal_services.lawyers l ON lf.firm_id = l.firm_id
WHERE l.is_partner = true
GROUP BY lf.firm_name
HAVING COUNT(l.lawyer_id) > 1;

[User] Show me the full name of all partner lawyers and the total hours they have spent on all time entries.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.lawyers l JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id WHERE l.is_partner = true GROUP BY l.lawyer_id, l.first_name, l.last_name;

[User] Actually, only include hours logged in the year 2023.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.lawyers l JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id WHERE l.is_partner = true AND EXTRACT(YEAR FROM te.date_worked) = 2023 GROUP BY l.lawyer_id, l.first_name, l.last_name;

[User] Also, only show partners who logged more than 50 hours in 2023, and order the results by total hours descending.

[Assistant] SELECT l.first_name, l.last_name, SUM(te.hours_spent) AS total_hours FROM legal_services.lawyers l JOIN legal_services.time_entries te ON l.lawyer_id = te.lawyer_id WHERE l.is_partner = true AND EXTRACT(YEAR FROM te.date_worked) = 2023 GROUP BY l.lawyer_id, l.first_name, l.last_name HAVING SUM(te.hours_spent) > 50 ORDER BY total_hours DESC;

[User] Which clients have not had any appointments scheduled? Please list their first name, last name, and email.

[Assistant]
SELECT c.first_name, c.last_name, c.email
FROM legal_services.clients c
LEFT JOIN legal_services.appointments a ON c.client_id = a.client_id
WHERE a.appointment_id IS NULL;


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.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
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 )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )

[User] Show me the total number of hours worked by each lawyer for each case.

[Assistant]
SELECT t.lawyer_id, t.case_id, SUM(t.hours_spent) AS total_hours
FROM legal_services.time_entries t
GROUP BY t.lawyer_id, t.case_id;

[User] Can you include the case name in the results as well?

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

[User] Now only show cases where the total hours is greater than 20, and sort by total hours descending.

[Assistant]
SELECT t.lawyer_id, t.case_id, cs.case_name, SUM(t.hours_spent) AS total_hours
FROM legal_services.time_entries t
JOIN legal_services.cases cs ON t.case_id = cs.case_id
GROUP BY t.lawyer_id, t.case_id, cs.case_name
HAVING SUM(t.hours_spent) > 20
ORDER BY total_hours DESC;

[User] How many documents of each type exist in the system? Show the document type and the count.

[Assistant]
SELECT document_type, COUNT(*) AS document_count
FROM legal_services.documents
group BY document_type;

[User] Which clients have at least one open case, and what are the names and numbers of those cases?

[Assistant]
SELECT c.first_name, c.last_name, cs.case_name, cs.case_number
FROM legal_services.clients c
JOIN legal_services.cases cs ON c.client_id = cs.client_id
WHERE cs.status = 'Open';

[User] List the case_number, case_name, and the total amount invoiced for each case.

[Assistant]
SELECT ca.case_number, ca.case_name, SUM(i.total_amount) AS total_invoiced
FROM legal_services.cases ca
LEFT JOIN legal_services.invoices i ON ca.case_id = i.case_id
GROUP BY ca.case_number, ca.case_name;

[User] For each appointment, show the appointment subject, start time, the client's name, and the lawyer's email.

[Assistant]
SELECT a.appointment_id, a.subject, a.start_time, c.first_name || ' ' || c.last_name AS client_name, l.email AS lawyer_email
FROM legal_services.appointments a
JOIN legal_services.clients c ON a.client_id = c.client_id
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_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('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}

[User] I need to find passengers who have a specific phone number prefix '+1555'. Can you help with that?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })

[User] Can you also filter these results to include only passengers born before 1995?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })

[User] Can you limit the results to the first 5 passengers?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 }).limit(5)

[User] Can you help me retrieve the details of passengers who are part of a specific loyalty program with ID 'LOYALTY123'?

[Assistant] db.passengers.find({ loyalty_program_id: 'LOYALTY123' }, { first_name: 1, last_name: 1, email: 1, phone_number: 1, date_of_birth: 1, loyalty_program_id: 1, _id: 0 })

[User] Can you modify the query to include only passengers who were registered after January 1, 2023?

[Assistant] db.passengers.find({ loyalty_program_id: 'LOYALTY123', created_at: { $gt: ISODate('2023-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, email: 1, phone_number: 1, date_of_birth: 1, loyalty_program_id: 1, _id: 0 })

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

[Assistant] db.passengers.find({ loyalty_program_id: 'LOYALTY123', created_at: { $gt: ISODate('2023-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, email: 1, phone_number: 1, date_of_birth: 1, loyalty_program_id: 1, _id: 0 }).sort({ created_at: -1 })

[User] Can you show me the total number of passengers registered in the database?

[Assistant] db.passengers.countDocuments({})


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.token_transfers ( transfer_id character varying(64) NOT NULL, token_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128) NOT NULL, value numeric(38,14) NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (transfer_id) )
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)

[User] Show all token transfers including the token symbol and the address of the contract that created each token. List the transfer id, token id, value, transaction id, the contract address, and the token symbol.

[Assistant]
SELECT tt.transfer_id, tt.token_id, tt.value, tt.transaction_id, t.contract_id AS contract_address, t.token_symbol
FROM web3.token_transfers tt
JOIN web3.tokens t ON tt.token_id = t.token_id;

[User] Find all events emitted by contracts that are also associated with token transfers. Show the event id, contract id, event name, emitted_at, transaction id, and also include the corresponding transfer id from token_transfers.

[Assistant]
SELECT e.event_id, e.contract_id, e.event_name, e.emitted_at, e.transaction_id, tt.transfer_id
FROM web3.events e
JOIN web3.token_transfers tt ON e.transaction_id = tt.transaction_id;

[User] List all transactions along with the user ID and username of the sender, if available. Show transaction id, from_address, user id, and username.

[Assistant]
SELECT tx.transaction_id, tx.from_address, w.user_id, u.username
FROM web3.transactions tx
LEFT JOIN web3.wallets w ON tx.from_address = w.address
LEFT JOIN web3.users u ON w.user_id = u.user_id;

[User] Actually, only include transactions where we can match the sender to a user, and sort the results by username.

[Assistant]
SELECT tx.transaction_id, tx.from_address, w.user_id, u.username
FROM web3.transactions tx
JOIN web3.wallets w ON tx.from_address = w.address
JOIN web3.users u ON w.user_id = u.user_id
ORDER BY u.username;

[User] Show all token transfers where the token_symbol contains 'ETH' and include the transfer id, value, transaction id, and the contract address where the token was created.

[Assistant]
SELECT tt.transfer_id, tt.value, tt.transaction_id, t.contract_address
FROM web3.token_transfers tt
JOIN web3.tokens t ON tt.token_id = t.token_id
WHERE t.token_symbol LIKE '%ETH%';

[User] Show all token transfers where the token was created by a contract with status 'active'. Include transfer ID, token symbol, value, and the contract address.

[Assistant]
SELECT tt.transfer_id, tk.token_symbol, tt.value, tk.contract_address
FROM web3.token_transfers tt
JOIN web3.tokens tk ON tt.token_id = tk.token_id
JOIN web3.contracts c ON tk.contract_address = c.address
WHERE c.status = 'active'
ORDER BY tt.transfer_id;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] Can you list all appointments along with the scheduled start time, purpose, and booking method, as well as the employee ID and location ID for each appointment?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, skill_certifications text, hire_date date, assigned_line_id text, employment_status text, supervisor_employee_id text )

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id text, model_name text, manufacturer text, passenger_capacity integer, max_range_km integer, engine_type text, wingspan_m numeric, status text, first_flight_date date )

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

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

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

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

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

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

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

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

[User] What is the current market price of a Boeing 737 MAX aircraft?

[Assistant] I'm sorry, but I don't have access to the current market price of aircraft models. The data I have is limited to technical specifications and general information about aircraft models such as passenger capacity, range, and status. For pricing information, you may need to consult with manufacturers or industry reports.


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] For each case, show the total amount of all invoices and the number of scheduled appointments. Only include cases that have both an invoice and at least one appointment.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] How many such users are there?

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

[User] For each user, show their user ID and the count of unique wallet addresses they own.

[Assistant] SELECT user_id, COUNT(DISTINCT address) FROM wallets GROUP BY user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar NOT NULL, tick varchar NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(62) NOT NULL, to_address varchar(62) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the first and last names of citizens along with the reference numbers of the applications they have submitted.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.reference_number FROM government_services.citizens AS T1 JOIN government_services.applications AS T2 ON T1.citizen_id  =  T2.citizen_id

[User] List the names of active services offered by agencies with at least one accessible service location in the state of 'New York'. Show the service name, category, agency name, and the location name.

[Assistant] SELECT T1.service_name, T1.category, T2.agency_name, T3.location_name FROM government_services.services AS T1 JOIN government_services.agencies AS T2 ON T1.agency_id = T2.agency_id JOIN government_services.service_locations AS T3 ON T2.agency_id = T3.agency_id WHERE T1.is_active IS TRUE AND T3.is_accessible IS TRUE AND T3.state = 'New York';

[User] How many employees are currently not terminated?

[Assistant] SELECT COUNT(*) FROM government_services.employees WHERE termination_date IS NULL;

[User] Retrieve each employee's first and last name along with the count of applications they've been assigned that are currently in the 'Under Review' status.

[Assistant]
SELECT e.first_name,
       e.last_name,
       COUNT(app.application_id) AS under_review_count
FROM government_services.employees e
LEFT JOIN government_services.applications app ON e.employee_id = app.assigned_employee_id
    AND app.status = 'Under Review'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] List the names of agencies and their established dates, but only for agencies that offer at least one service.

[Assistant] SELECT DISTINCT T1.agency_name ,  T1.established_date FROM government_services.agencies AS T1 JOIN government_services.services AS T2 ON T1.agency_id  =  T2.agency_id