System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )

[User] I need a list of genres and pairs of game titles in the same genre.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre;

[User] Please avoid duplicate pairs by ensuring each pair appears only once.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title;

[User] Only include genres that have at least three games.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  );

[User] Also sort the output by genre ascending and game1 ascending.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  )
ORDER BY g1.genre ASC, g1.title ASC;

[User] List each game along with the title and release_date of the next game released by the same developer.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Actually, only include next games released within one year of the original game.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Also show the gap in days between the two release dates.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date,
       (g2.release_date - g1.release_date) AS days_gap
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY days_gap DESC;

[User] Finally, limit to developers who have at least 5 games.

[Assistant]
WITH dev_counts AS (
  SELECT developer_id, COUNT(*) AS game_count
  FROM gaming_technology.games
  GROUP BY developer_id
  HAVING COUNT(*) >= 5
)
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date,
       (g2.release_date - g1.release_date) AS days_gap
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
JOIN dev_counts dc
  ON g1.developer_id = dc.developer_id
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Can you list each game alongside another game in the same genre but by a different developer?

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id;

[User] Exclude any pairs where either game was released before 2019.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01';

[User] Limit the output to the first 10 pairs ordered by genre and developer_id.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01'
ORDER BY g1.genre, g1.developer_id
LIMIT 10;

[User] I need a count of games per platform and the earliest release date on each platform.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform;

[User] Actually, only include platforms with at least 5 games.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5;

[User] Also, order the results by first_release ascending.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5
ORDER BY first_release ASC;

[User] And please exclude any records where platform is null.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
WHERE platform IS NOT NULL
GROUP BY platform
HAVING COUNT(*) >= 5
ORDER BY first_release ASC;

[User] How many games are there per platform, and what is the earliest release_date for each platform?

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform;

[User] Only include platforms with at least 10 games.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10;

[User] Sort the results by game_count descending.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10
ORDER BY game_count DESC;

[User] Also include the number of unique genres available on each platform.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release,
       COUNT(DISTINCT genre) AS genre_count
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10
ORDER BY game_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )

[User] Can you list the names of agencies that do not have a parent agency assigned, ordered by their established date?

[Assistant]
SELECT agency_id, agency_name, established_date
FROM government_services.agencies
WHERE parent_agency_id IS NULL
ORDER BY established_date;

[User] How many agencies exist at each jurisdiction level?

[Assistant]
SELECT jurisdiction_level, COUNT(*) AS agency_count
FROM government_services.agencies
GROUP BY jurisdiction_level;

[User] Now exclude jurisdiction levels that have fewer than 5 agencies.

[Assistant]
SELECT jurisdiction_level, COUNT(*) AS agency_count
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5;

[User] Also, show me the average establishment year for those jurisdiction levels.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5;

[User] Sort the results by agency_count descending and limit to 3.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5
ORDER BY agency_count DESC
LIMIT 3;

[User] I would like to see a list of agencies and the names of their respective parent agencies.

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id;

[User] Could you only show agencies that actually have a parent agency, and order the result by the agency name?

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
ORDER BY a.agency_name;

[User] List each child agency ID and name along with its parent agency ID and name.

[Assistant]
SELECT c.agency_id AS child_id,
       c.agency_name AS child_name,
       p.agency_id AS parent_id,
       p.agency_name AS parent_name
FROM government_services.agencies AS c
JOIN government_services.agencies AS p
  ON c.parent_agency_id = p.agency_id;

[User] Show me all agencies established after 2020 and their jurisdiction level.

[Assistant]
SELECT agency_id, agency_name, jurisdiction_level, established_date
FROM government_services.agencies
WHERE established_date > '2020-12-31';

[User] Can you also include their parent agency's name in the result?

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31';

[User] Only show agencies where the parent agency's jurisdiction level is 'Federal'.

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31' AND p.jurisdiction_level = 'Federal';

[User] Sort the list by established date descending and show only the top 5 agencies.

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31' AND p.jurisdiction_level = 'Federal'
ORDER BY a.established_date DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] Show me all invoice numbers together with the client IDs and related case IDs for invoices issued after March 1st, 2024.

[Assistant] SELECT invoice_number, client_id, case_id FROM legal_services.invoices WHERE issue_date > '2024-03-01';

[User] I only want to include invoices that have a total_amount greater than 5000. Can you update the query?

[Assistant] SELECT invoice_number, client_id, case_id FROM legal_services.invoices WHERE issue_date > '2024-03-01' AND total_amount > 5000;

[User] Add the invoice status to the result, and only show invoices where the status is either 'Overdue' or 'Partially Paid'.

[Assistant] SELECT invoice_number, client_id, case_id, status FROM legal_services.invoices WHERE issue_date > '2024-03-01' AND total_amount > 5000 AND status IN ('Overdue', 'Partially Paid');

[User] Give me a count of invoices issued for each case this year, and show the case ID with the count.

[Assistant]
SELECT case_id, COUNT(*) AS invoice_count
FROM legal_services.invoices
WHERE EXTRACT(YEAR FROM issue_date) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY case_id;

[User] Some cases might not have any invoices yet—can you modify the query to include such cases as well, showing 0 for those without invoices?

[Assistant]
SELECT cases.case_id, COALESCE(COUNT(invoices.invoice_id), 0) AS invoice_count
FROM cases
LEFT JOIN legal_services.invoices ON cases.case_id = invoices.case_id AND EXTRACT(YEAR FROM invoices.issue_date) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY cases.case_id;

[User] Now, only show cases where the invoice_count is less than 2.

[Assistant]
SELECT cases.case_id, COALESCE(COUNT(invoices.invoice_id), 0) AS invoice_count
FROM cases
LEFT JOIN legal_services.invoices ON cases.case_id = invoices.case_id AND EXTRACT(YEAR FROM invoices.issue_date) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY cases.case_id
HAVING COALESCE(COUNT(invoices.invoice_id), 0) < 2;

[User] List pairs of invoice_number for invoices that share the same due_date.

[Assistant]
SELECT a.due_date,
       a.invoice_number AS invoice1,
       b.invoice_number AS invoice2
FROM legal_services.invoices a
JOIN legal_services.invoices b
  ON a.due_date = b.due_date
  AND a.invoice_id < b.invoice_id;

[User] Only include pairs where the due_date is in March 2024.

[Assistant]
SELECT a.due_date,
       a.invoice_number AS invoice1,
       b.invoice_number AS invoice2
FROM legal_services.invoices a
JOIN legal_services.invoices b
  ON a.due_date = b.due_date
  AND a.invoice_id < b.invoice_id
WHERE a.due_date BETWEEN '2024-03-01' AND '2024-03-31';

[User] Can you list the invoice numbers, issue dates, and due dates for all invoices, sorted by issue date ascending?

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices ORDER BY issue_date ASC;

[User] I only want to see invoices with a due date in May 2024. Please modify the query.

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' ORDER BY issue_date ASC;

[User] Also, only include invoices that have not been paid in full yet (amount_paid < total_amount).

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' AND amount_paid < total_amount ORDER BY issue_date ASC;

[User] Add the status column and sort the results by due_date descending.

[Assistant] SELECT invoice_number, issue_date, due_date, status FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' AND amount_paid < total_amount ORDER BY due_date DESC;

[User] Show me the total number of appointments grouped by status.

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

[User] Focus only on statuses 'Scheduled' and 'Completed'.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM legal_services.appointments
WHERE status IN ('Scheduled', 'Completed')
GROUP BY status;

[User] Include only those that start in the last month.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM legal_services.appointments
WHERE status IN ('Scheduled', 'Completed')
  AND start_time >= CURRENT_DATE - INTERVAL '1 month'
GROUP BY status;

[User] Order the groups by the count in ascending order.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM legal_services.appointments
WHERE status IN ('Scheduled', 'Completed')
  AND start_time >= CURRENT_DATE - INTERVAL '1 month'
GROUP BY status
ORDER BY appointment_count ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] Find the total payment amount and payment count made by citizen with national ID number 'A123456789'.

[Assistant]
SELECT SUM(p.amount) AS total_amount, COUNT(p.payment_id) AS payment_count
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
WHERE c.national_id_number = 'A123456789';

[User] List the employee full names, the department they work in, and the number of notifications sent to citizens who have made payments for the services managed by these employees' agencies.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS employee_full_name, e.department, COUNT(n.notification_id) AS notification_count
FROM government_services.employees e
JOIN government_services.services s ON e.agency_id = s.agency_id
JOIN government_services.payments p ON s.service_id = p.service_id
JOIN government_services.notifications n ON p.citizen_id = n.citizen_id
GROUP BY e.employee_id, e.first_name, e.last_name, e.department;

[User] Show the full names and contact emails of all citizens who have made a payment for an application that is currently in 'Pending' status.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
WHERE a.status = 'Pending';

[User] Show the appointment ID, scheduled start time, and the full name of the citizen for all appointments related to services with a standard fee greater than 150.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, c.first_name || ' ' || c.last_name AS full_name
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.payments p ON a.citizen_id = p.citizen_id AND a.service_id = p.service_id
WHERE p.amount > 150;

[User] How many payments were made using the payment method 'Credit Card'?

[Assistant]
SELECT COUNT(*) AS credit_card_payments
FROM government_services.payments
WHERE payment_method = 'Credit Card';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address text NOT NULL, city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, status character varying(32) NOT NULL, risk_profile character varying(50), PRIMARY KEY (customer_id) )
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] Show me all trades with their corresponding ticker_symbol and security_name for trades executed in the last 7 days.

[Assistant]
SELECT tr.trade_id, tr.account_id, tr.trade_type, tr.quantity, tr.price_per_unit, tr.total_amount,
       tr.commission, tr.trade_timestamp,
       s.ticker_symbol, s.security_name
FROM financial_services.trades tr
JOIN financial_services.securities s ON tr.security_id = s.security_id
WHERE tr.trade_timestamp >= now() - INTERVAL '7 days';

[User] Only include trades where commission is greater than 50 and status is 'Completed'.

[Assistant]
SELECT tr.trade_id, tr.account_id, tr.trade_type, tr.quantity, tr.price_per_unit, tr.total_amount,
       tr.commission, tr.trade_timestamp,
       s.ticker_symbol, s.security_name
FROM financial_services.trades tr
JOIN financial_services.securities s ON tr.security_id = s.security_id
WHERE tr.trade_timestamp >= now() - INTERVAL '7 days'
  AND tr.commission > 50
  AND tr.status = 'Completed';

[User] Could you provide the sum of Deposit and Withdrawal amounts for each customer, showing their first and last names?

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name,
       SUM(CASE WHEN t.transaction_type = 'Deposit' THEN t.amount ELSE 0 END) AS total_deposits,
       SUM(CASE WHEN t.transaction_type = 'Withdrawal' THEN t.amount ELSE 0 END) AS total_withdrawals
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
GROUP BY c.customer_id, c.first_name, c.last_name;

[User] Actually, please only consider transactions that have status 'Completed'.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name,
       SUM(CASE WHEN t.transaction_type = 'Deposit' THEN t.amount ELSE 0 END) AS total_deposits,
       SUM(CASE WHEN t.transaction_type = 'Withdrawal' THEN t.amount ELSE 0 END) AS total_withdrawals
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE t.status = 'Completed'
GROUP BY c.customer_id, c.first_name, c.last_name;

[User] Summarize the total principal amount for loans, grouped by customer and their account type. Include the customer's full name.

[Assistant] SELECT T1.first_name, T1.last_name, T2.account_type, SUM(T3.principal_amount) FROM financial_services.customers AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id = T2.customer_id JOIN financial_services.loans AS T3 ON T2.account_id = T3.account_id GROUP BY T1.customer_id, T1.first_name, T1.last_name, T2.account_type;

[User] Only include accounts and loans that are currently 'Active'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.account_type, SUM(T3.principal_amount) FROM financial_services.customers AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id = T2.customer_id JOIN financial_services.loans AS T3 ON T2.account_id = T3.account_id WHERE T2.status = 'Active' AND T3.status = 'Active' GROUP BY T1.customer_id, T1.first_name, T1.last_name, T2.account_type;

[User] For each security, show the average daily volume from market data and the total quantity traded across all trades.

[Assistant] WITH MarketDataAgg AS ( SELECT security_id, AVG(volume) AS avg_daily_volume FROM financial_services.market_data GROUP BY security_id ), TradesAgg AS ( SELECT security_id, SUM(quantity) AS total_quantity_traded FROM financial_services.trades GROUP BY security_id ) SELECT T1.ticker_symbol, T1.security_name, T2.avg_daily_volume, T3.total_quantity_traded FROM financial_services.securities AS T1 LEFT JOIN MarketDataAgg AS T2 ON T1.security_id = T2.security_id LEFT JOIN TradesAgg AS T3 ON T1.security_id = T3.security_id WHERE T2.avg_daily_volume IS NOT NULL OR T3.total_quantity_traded IS NOT NULL;

[User] Only include securities where the average daily volume is above 500000 and the total quantity traded is above 10000.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, a.account_number, a.balance, s.ticker_symbol, s.security_name
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.securities s ON a.currency = s.currency
ORDER BY c.last_name, c.first_name, a.account_number, s.ticker_symbol;

[User] Add the customer's city and state to the output. Also, show only accounts with a balance greater than 5000.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, c.city, c.state, a.account_number, a.balance, s.ticker_symbol, s.security_name
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.securities s ON a.currency = s.currency
WHERE a.balance > 5000
ORDER BY c.last_name, c.first_name, a.account_number, s.ticker_symbol;

[User] I only want customers who have at least one account in EUR currency. Could you update the query accordingly?

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, c.city, c.state, a.account_number, a.balance, s.ticker_symbol, s.security_name
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.securities s ON a.currency = s.currency
WHERE a.balance > 5000
  AND c.customer_id IN (SELECT customer_id FROM financial_services.accounts WHERE currency = 'EUR')
ORDER BY c.last_name, c.first_name, a.account_number, s.ticker_symbol;

[User] Now restrict it to only include securities traded on the 'Euronext' exchange.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, c.city, c.state, a.account_number, a.balance, s.ticker_symbol, s.security_name
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.securities s ON a.currency = s.currency
WHERE a.balance > 5000
  AND c.customer_id IN (SELECT customer_id FROM financial_services.accounts WHERE currency = 'EUR')
  AND s.exchange = 'Euronext'
ORDER BY c.last_name, c.first_name, a.account_number, s.ticker_symbol;


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 text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    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, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] Retrieve the service names, location names, and cities for active services offered at accessible locations in California.

[Assistant]
SELECT s.service_name,
       sl.location_name,
       sl.city
FROM government_services.services AS s
JOIN government_services.service_locations AS sl
  ON s.agency_id = sl.agency_id
WHERE s.is_active = TRUE
  AND sl.is_accessible = TRUE
  AND sl.state = 'California';

[User] Count the number of documents for each document type.

[Assistant] SELECT document_type, COUNT(*) FROM government_services.documents GROUP BY document_type;

[User] Only include document types that have more than 50 documents.

[Assistant] SELECT document_type, COUNT(*) FROM government_services.documents GROUP BY document_type HAVING COUNT(*) > 50;

[User] Exclude documents that have an expiry date in the past.

[Assistant] SELECT document_type, COUNT(*) FROM government_services.documents WHERE expiry_date IS NULL OR expiry_date >= CURRENT_DATE GROUP BY document_type HAVING COUNT(*) > 50;

[User] Show the results ordered by the count in descending order.

[Assistant] SELECT document_type, COUNT(*) FROM government_services.documents WHERE expiry_date IS NULL OR expiry_date >= CURRENT_DATE GROUP BY document_type HAVING COUNT(*) > 50 ORDER BY COUNT(*) DESC;

[User] List the first name and last name of citizens along with the type and verification status of their documents.

[Assistant] SELECT T1.first_name, T1.last_name, T2.document_type, T2.verification_status FROM government_services.citizens AS T1 JOIN government_services.documents AS T2 ON T1.citizen_id = T2.citizen_id;

[User] List the names of service locations and categories of active services offered by the same agency.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE;

[User] Please exclude service locations that are not accessible.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE
  AND sl.is_accessible = TRUE;

[User] List the names of services available at service locations that are accessible and located in the state of 'California'.

[Assistant] SELECT T1.service_name, T2.location_name FROM government_services.services AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE AND T2.state = 'California';

[User] Modify to only include services that are active.

[Assistant] SELECT T1.service_name, T2.location_name FROM government_services.services AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE AND T2.state = 'California' AND T1.is_active = TRUE;


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_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )

[User] List tokens on the 'Arbitrum' chain with a 24-hour trading volume greater than 1,000,000 USD. Show symbol, volume, and price.

[Assistant] SELECT token_symbol, volume_24h, price FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000

[User] Can you also include the liquidity for these tokens?

[Assistant] SELECT token_symbol, volume_24h, price, liquidity FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000

[User] Now, filter these results to only include tokens where the liquidity is also greater than $500,000. Order by volume descending and show the top 10.

[Assistant] SELECT token_symbol, volume_24h, price, liquidity FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000 AND liquidity > 500000 ORDER BY volume_24h DESC LIMIT 10

[User] Add the 24-hour price change percentage and only include tokens where the price change is positive.

[Assistant] SELECT token_symbol, volume_24h, price, liquidity, price_change_percentage_24h FROM token_dexpool_info WHERE chain = 'Arbitrum' AND volume_24h > 1000000 AND liquidity > 500000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 10

[User] What is the average market cap and average 24-hour trading volume for tokens on each chain?

[Assistant] SELECT chain, AVG(market_cap) AS average_market_cap, AVG(volume_24h) AS average_volume_24h FROM token_dexpool_info GROUP BY chain

[User] Can you also include the count of tokens for each chain and filter out chains with less than 100 tokens?

[Assistant] SELECT chain, AVG(market_cap) AS average_market_cap, AVG(volume_24h) AS average_volume_24h, COUNT(token_symbol) AS token_count FROM token_dexpool_info GROUP BY chain HAVING COUNT(token_symbol) >= 100

[User] List all tokens with a liquidity over $1 million and a negative 1-hour price change percentage on the Binance chain.

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_1h, liquidity FROM token_dexpool_info WHERE chain = 'Binance' AND liquidity > 1000000 AND price_change_percentage_1h < 0;

[User] Can you also include their 24-hour trading volume and filter for tokens with a market cap under $50 million?

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_1h, liquidity, volume_24h FROM token_dexpool_info WHERE chain = 'Binance' AND liquidity > 1000000 AND price_change_percentage_1h < 0 AND market_cap < 50000000;

[User] Actually, I want to see tokens with a positive 6-hour price change instead.

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_6h, liquidity, volume_24h FROM token_dexpool_info WHERE chain = 'Binance' AND liquidity > 1000000 AND price_change_percentage_6h > 0 AND market_cap < 50000000;

[User] Now order these results by 24-hour trading volume in descending order.

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_6h, liquidity, volume_24h FROM token_dexpool_info WHERE chain = 'Binance' AND liquidity > 1000000 AND price_change_percentage_6h > 0 AND market_cap < 50000000 ORDER BY volume_24h DESC;

[User] Show me the top 5 tokens by 24-hour trading volume on the Ethereum chain, along with their price and 24-hour price change percentage.

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_24h, volume_24h FROM token_dexpool_info WHERE chain = 'Ethereum' ORDER BY volume_24h DESC LIMIT 5;

[User] Can you also include the market cap and liquidity for these tokens?

[Assistant] SELECT token_name, token_symbol, price, price_change_percentage_24h, volume_24h, market_cap, liquidity FROM token_dexpool_info WHERE chain = 'Ethereum' ORDER BY volume_24h DESC LIMIT 5;

[User] Which tokens have the highest liquidity on the Ethereum chain and what are their current prices and 24-hour trading volumes?

[Assistant] SELECT token_symbol, price, liquidity, volume_24h FROM token_dexpool_info WHERE chain = 'Ethereum' ORDER BY liquidity DESC LIMIT 10;

[User] Can you also show their trend rank and market cap in the result?

[Assistant] SELECT token_symbol, price, liquidity, volume_24h, trend_rank, market_cap FROM token_dexpool_info WHERE chain = 'Ethereum' ORDER BY liquidity DESC LIMIT 10;

[User] I am seeing tokens with very low market cap. Please only include tokens where market_cap is greater than 50,000,000.

[Assistant] SELECT token_symbol, price, liquidity, volume_24h, trend_rank, market_cap FROM token_dexpool_info WHERE chain = 'Ethereum' AND market_cap > 50000000 ORDER BY liquidity DESC LIMIT 10;

[User] Now, please limit the result to only the top 5 tokens by liquidity and display the 6h price change percentage as well.

[Assistant] SELECT token_symbol, price, liquidity, volume_24h, trend_rank, market_cap, price_change_percentage_6h FROM token_dexpool_info WHERE chain = 'Ethereum' AND market_cap > 50000000 ORDER BY liquidity DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )

[User] Show me all replies to comments, including the reply's comment ID, the parent comment ID, and the content.

[Assistant] SELECT comment_id, parent_comment_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] I also want to see which post each reply was made on. Can you include the post ID as well?

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] Now, only show replies made after June 1, 2024.

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL AND created_at > '2024-06-01';

[User] Show me the number of comments each user has made on each post.

[Assistant] SELECT post_id, user_id, COUNT(*) AS comment_count FROM social_media.comments GROUP BY post_id, user_id;

[User] Can you also show the creation time of the most recent comment for each post by each user?

[Assistant] SELECT post_id, user_id, COUNT(*) AS comment_count, MAX(created_at) AS latest_comment_time FROM social_media.comments GROUP BY post_id, user_id;

[User] List all top-level comments, showing their ID, post ID, user ID, and content.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL;

[User] From those, show only the ones made after June 1st, 2024.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE parent_comment_id IS NULL AND created_at > '2024-06-01';

[User] Now, for these top-level comments, can you list any replies they have received, showing the reply's ID, content, and the user ID of the reply author?

[Assistant] SELECT c.comment_id AS top_level_comment_id, r.comment_id AS reply_id, r.content AS reply_content, r.user_id AS reply_user_id FROM social_media.comments c JOIN social_media.comments r ON c.comment_id = r.parent_comment_id WHERE c.parent_comment_id IS NULL AND c.created_at > '2024-06-01';

[User] Show me all comments that have non-empty content, including their ID, post ID, user ID, and content.

[Assistant] SELECT comment_id, post_id, user_id, content FROM social_media.comments WHERE content IS NOT NULL AND content != '';

[User] Can you list all replies along with their parent comment content for post_id 'P100'?

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL;

[User] Actually, I only want replies made after '2024-07-01'.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01';

[User] Now include the original comment's created_at timestamp as well.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, parent.created_at AS parent_created_at, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01';

[User] Finally, order the results by reply creation time ascending.

[Assistant] SELECT reply.comment_id AS reply_id, parent.content AS parent_content, parent.created_at AS parent_created_at, reply.content AS reply_content FROM comments AS reply JOIN comments AS parent ON reply.parent_comment_id = parent.comment_id WHERE reply.post_id = 'P100' AND reply.parent_comment_id IS NOT NULL AND reply.created_at > '2024-07-01' ORDER BY reply.created_at 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 gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)

[User] List each genre and the number of games in that genre.

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY genre;

[User] Now filter to only include genres with more than 5 games.

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY genre
HAVING COUNT(*) > 5;

[User] Exclude entries where genre is NULL.

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
WHERE genre IS NOT NULL
GROUP BY genre
HAVING COUNT(*) > 5;

[User] Finally, order the results by game_count in descending order.

[Assistant]
SELECT genre,
       COUNT(*) AS game_count
FROM gaming_technology.games
WHERE genre IS NOT NULL
GROUP BY genre
HAVING COUNT(*) > 5
ORDER BY game_count DESC;

[User] List pairs of games that share the same publisher but belong to different genres, showing both titles and genres.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre;

[User] Exclude any pairs where the publisher_id is NULL.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre
WHERE g1.publisher_id IS NOT NULL;

[User] Further restrict to game pairs released within one year of each other.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL;

[User] Order the final result by publisher_id and then by the earliest release_date among each pair.

[Assistant]
SELECT g1.publisher_id,
       g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL
ORDER BY g1.publisher_id,
         LEAST(g1.release_date, g2.release_date) ASC;

[User] Show me all items and the total quantity held by players for each item.

[Assistant]
SELECT pi.item_id, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
GROUP BY pi.item_id;

[User] Can you filter for items where players hold at least 10 in total?

[Assistant]
SELECT pi.item_id, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
GROUP BY pi.item_id
HAVING SUM(pi.quantity) >= 10;

[User] I would also like to see the most recent acquired_at time for each item.

[Assistant]
SELECT pi.item_id, SUM(pi.quantity) AS total_quantity, MAX(pi.acquired_at) AS most_recent_acquired
FROM gaming_technology.player_inventory pi
GROUP BY pi.item_id
HAVING SUM(pi.quantity) >= 10;

[User] I see duplicates in item_id columns, can you join with the in_game_items table and also show the item name instead?

[Assistant]
SELECT ii.item_name, pi.item_id, SUM(pi.quantity) AS total_quantity, MAX(pi.acquired_at) AS most_recent_acquired
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items ii ON pi.item_id = ii.item_id
GROUP BY ii.item_name, pi.item_id
HAVING SUM(pi.quantity) >= 10;

[User] Which games have at least one achievement worth exactly 75 points, and what are the names and descriptions of those achievements?

[Assistant]
SELECT g.title, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75;

[User] Also include the release date of each game in the output.

[Assistant]
SELECT g.title, g.release_date, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75;

[User] Now, only show results for games released after 2021-01-01.

[Assistant]
SELECT g.title, g.release_date, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75 AND g.release_date > '2021-01-01';

[User] Order the list by game release date ascending, then achievement name ascending.

[Assistant]
SELECT g.title, g.release_date, a.name AS achievement_name, a.description
FROM gaming_technology.games g
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
WHERE a.points = 75 AND g.release_date > '2021-01-01'
ORDER BY g.release_date ASC, a.name ASC;

[User] How many games are available on each platform?

[Assistant]
SELECT platform,
       COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY platform;

[User] Only include platforms that have more than 5 games.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) > 5;

[User] Also, show the earliest release_date for each of those platforms.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) > 5;

[User] Sort the results by game_count descending and then by earliest_release ascending.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) > 5
ORDER BY game_count DESC,
         earliest_release 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 social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
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.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] List all contracts and the number of different tokens associated with each contract address. Show contract_id, contract address, and token_count.

[Assistant]
SELECT c.contract_id, c.address, COUNT(DISTINCT t.token_id) AS token_count
FROM web3.contracts c
LEFT JOIN web3.tokens t ON c.address = t.contract_address
GROUP BY c.contract_id, c.address;

[User] Show all tokens along with the username of the deployer of the contract where each token was created. Include the token symbol, token name, contract address, and username.

[Assistant]
SELECT t.token_symbol, t.token_name, t.contract_address, u.username
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address
LEFT JOIN web3.wallets w ON c.deployer_address = w.address
LEFT JOIN web3.users u ON w.user_id = u.user_id;

[User] Which user has created the most tokens? Please show the username and the number of tokens they have created.

[Assistant]
SELECT u.username, COUNT(*) AS token_count
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address
JOIN web3.wallets w ON c.deployer_address = w.address
JOIN web3.users u ON w.user_id = u.user_id
GROUP BY u.username
ORDER BY token_count DESC
LIMIT 1;

[User] Actually, show all users and the number of tokens they have created, ordered from most to least.

[Assistant]
SELECT u.username, COUNT(*) AS token_count
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address
JOIN web3.wallets w ON c.deployer_address = w.address
JOIN web3.users u ON w.user_id = u.user_id
GROUP BY u.username
ORDER BY token_count DESC;

[User] Find the usernames of users who have deployed contracts and list the address of the contract they deployed.

[Assistant] SELECT T1.username, T3.address FROM web3.users AS T1 JOIN web3.wallets AS T2 ON T1.user_id = T2.user_id JOIN web3.contracts AS T3 ON T2.address = T3.deployer_address;

[User] List the transaction IDs that have both an event and a token transfer, along with the name of the event and the value of the token transfer.

[Assistant] SELECT T1.transaction_id, T1.event_name, T2.value FROM web3.events AS T1 JOIN web3.token_transfers AS T2 ON T1.transaction_id = T2.transaction_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 blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)

[User] Find all pairs of transactions where the sender address and the receiver address are the same, but the transactions occurred on different days. Show transaction IDs, addresses, and their timestamps.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address;

[User] Exclude pairs where the two transactions happened more than 7 days apart.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address
  AND ABS(DATE_PART('day', t1.timestamp - t2.timestamp)) <= 7;

[User] Show me transactions where the sender and receiver addresses are the same. List transaction_id, amount, and timestamp.

[Assistant] SELECT transaction_id, amount, timestamp FROM blockchain.transactions WHERE sender_address = receiver_address;

[User] Now filter these transactions to those that occurred in May 2023 with an amount greater than 1000.

[Assistant] SELECT transaction_id, amount, timestamp FROM blockchain.transactions WHERE sender_address = receiver_address AND timestamp >= '2023-05-01' AND timestamp < '2023-06-01' AND amount > 1000;

[User] For these filtered transactions, count how many times each unique address appears as both sender and receiver.

[Assistant] SELECT sender_address, COUNT(*) FROM blockchain.transactions WHERE sender_address = receiver_address AND timestamp >= '2023-05-01' AND timestamp < '2023-06-01' AND amount > 1000 GROUP BY sender_address;

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

[Assistant] SELECT sender_address, COUNT(*) FROM blockchain.transactions WHERE sender_address = receiver_address AND timestamp >= '2023-05-01' AND timestamp < '2023-06-01' AND amount > 1000 GROUP BY sender_address ORDER BY COUNT(*) DESC;

[User] List all sender and receiver address pairs that have exchanged more than 2 transactions with each other, along with the total amount transferred between them.

[Assistant]
SELECT sender_address, receiver_address, COUNT(*) AS transaction_count, SUM(amount) AS total_amount
FROM blockchain.transactions
GROUP BY sender_address, receiver_address
HAVING COUNT(*) > 2;

[User] Can you also include the earliest and latest timestamp for transactions between each pair?

[Assistant]
SELECT sender_address, receiver_address, COUNT(*) AS transaction_count, SUM(amount) AS total_amount, MIN(timestamp) AS first_transaction, MAX(timestamp) AS last_transaction
FROM blockchain.transactions
GROUP BY sender_address, receiver_address
HAVING COUNT(*) > 2;

[User] I only want pairs where the total amount transferred is greater than 5000.

[Assistant]
SELECT sender_address, receiver_address, COUNT(*) AS transaction_count, SUM(amount) AS total_amount, MIN(timestamp) AS first_transaction, MAX(timestamp) AS last_transaction
FROM blockchain.transactions
GROUP BY sender_address, receiver_address
HAVING COUNT(*) > 2 AND SUM(amount) > 5000;

[User] Now, order the results by total_amount in descending order and limit the output to the top 10 pairs.

[Assistant]
SELECT sender_address, receiver_address, COUNT(*) AS transaction_count, SUM(amount) AS total_amount, MIN(timestamp) AS first_transaction, MAX(timestamp) AS last_transaction
FROM blockchain.transactions
GROUP BY sender_address, receiver_address
HAVING COUNT(*) > 2 AND SUM(amount) > 5000
ORDER BY total_amount DESC
LIMIT 10;

[User] Show all transactions where the sender and receiver are different addresses but the transaction amount is exactly 1000. Include transaction_id, sender_address, receiver_address, and timestamp.

[Assistant]
SELECT transaction_id, sender_address, receiver_address, timestamp
FROM blockchain.transactions
WHERE sender_address <> receiver_address AND amount = 1000;

[User] List all transactions with an amount greater than 10000, showing transaction_id, block_id, sender_address, receiver_address, and amount.

[Assistant] SELECT transaction_id, block_id, sender_address, receiver_address, amount FROM blockchain.transactions WHERE amount > 10000;

[User] Filter these transactions to only include those before April 1st, 2023.

[Assistant] SELECT transaction_id, block_id, sender_address, receiver_address, amount FROM blockchain.transactions WHERE amount > 10000 AND timestamp < '2023-04-01';

[User] Order the final list by amount in descending order.

[Assistant] SELECT transaction_id, block_id, sender_address, receiver_address, amount FROM blockchain.transactions WHERE amount > 10000 AND timestamp < '2023-04-01' ORDER BY amount 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 government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] Also order the results by service_count descending.

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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