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;

[User] Can you show me a list of all agencies along with their parent agency names?

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

[User] Only show agencies that actually have a parent agency.

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

[User] Provide a count of agencies grouped by their jurisdiction level.

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

[User] I want to know the number of agencies established each year by jurisdiction level.

[Assistant]
SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
FROM government_services.agencies
group by jurisdiction_level, year
ORDER BY jurisdiction_level, year;

[User] Only show years where more than 2 agencies were established.

[Assistant]
SELECT jurisdiction_level, year, agency_count
FROM (
  SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
  FROM government_services.agencies
  GROUP BY jurisdiction_level, year
) t
WHERE agency_count > 2
ORDER BY jurisdiction_level, year;

[User] Now only include agencies in the 'State' jurisdiction level.

[Assistant]
SELECT jurisdiction_level, year, agency_count
FROM (
  SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
  FROM government_services.agencies
  WHERE jurisdiction_level = 'State'
  GROUP BY jurisdiction_level, year
) t
WHERE agency_count > 2
ORDER BY year;

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

[Assistant]
SELECT jurisdiction_level, year, agency_count
FROM (
  SELECT jurisdiction_level, EXTRACT(YEAR FROM established_date) AS year, COUNT(*) AS agency_count
  FROM government_services.agencies
  WHERE jurisdiction_level = 'State'
  GROUP BY jurisdiction_level, year
) t
WHERE agency_count > 2
ORDER BY agency_count DESC;

[User] Find parent agencies and the number of direct child agencies they have. List the parent agency name and the count of their children.

[Assistant] SELECT T1.agency_name, COUNT(T2.agency_id) FROM government_services.agencies AS T1 JOIN government_services.agencies AS T2 ON T1.agency_id = T2.parent_agency_id GROUP BY T1.agency_name ORDER BY COUNT(T2.agency_id) DESC;

[User] List all agencies that do not have a website URL specified. Return their agency_id, agency_name, and main_phone_number.

[Assistant] SELECT agency_id, agency_name, main_phone_number FROM government_services.agencies WHERE website_url IS NULL OR website_url = '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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;

[User] Which invoices have a status of 'Partially Paid' and have not reached their due date yet? Show the invoice number, client ID, due date, and amount paid.

[Assistant]
SELECT invoice_number, client_id, due_date, amount_paid
FROM legal_services.invoices
WHERE status = 'Partially Paid' AND due_date > CURRENT_DATE;

[User] Get a list of appointment_id, start_time, and invoice_number for appointments that have a related invoice.

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

[User] Also include only appointments that are completed and invoices that are fully paid (status 'Paid').

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

[User] Show me the invoice number, total amount, and due date for all invoices, along with the corresponding client ID.

[Assistant] SELECT invoice_number, total_amount, due_date, client_id FROM legal_services.invoices;

[User] I only want to see invoices that are overdue.

[Assistant] SELECT invoice_number, total_amount, due_date, client_id FROM legal_services.invoices WHERE status = 'Overdue';

[User] Can you also show the amount paid for these overdue invoices?

[Assistant] SELECT invoice_number, total_amount, due_date, amount_paid, client_id FROM legal_services.invoices WHERE status = 'Overdue';

[User] Show me the total invoice amount and the number of invoices for each client in 2024, and include the earliest and latest invoice issue date for each client.

[Assistant]
SELECT client_id, SUM(total_amount) AS total_invoice_amount, COUNT(*) AS invoice_count, MIN(issue_date) AS earliest_issue_date, MAX(issue_date) AS latest_issue_date
FROM legal_services.invoices
WHERE EXTRACT(YEAR FROM issue_date) = 2024
GROUP BY client_id;

[User] I want to see a list of invoice_number and appointment_id for each invoice that has a scheduled appointment.

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

[User] Only include those invoices whose due_date is still in the future.

[Assistant]
SELECT i.invoice_number,
       a.appointment_id
FROM legal_services.invoices i
JOIN legal_services.appointments a
  ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
  AND i.due_date > CURRENT_DATE;

[User] Finally, sort the results by the invoice issue_date in descending order.

[Assistant]
SELECT i.invoice_number,
       a.appointment_id
FROM legal_services.invoices i
JOIN legal_services.appointments a
  ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
  AND i.due_date > CURRENT_DATE
ORDER BY i.issue_date 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.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';

[User] List the names of employees and the agency they work for who have scheduled at least one appointment. Show the employee's first name, last name, and agency_id.

[Assistant]
SELECT DISTINCT e.first_name, e.last_name, e.agency_id
FROM government_services.employees e
JOIN government_services.appointments a ON e.employee_id = a.employee_id;

[User] Show me the first name and last name of citizens who have scheduled appointments for services offered by agencies whose agency_id starts with 'AG'. Also include the service name.

[Assistant]
SELECT c.first_name, c.last_name, s.service_name
FROM government_services.appointments a
JOIN government_services.services s ON a.service_id = s.service_id
JOIN government_services.applications app ON a.citizen_id = app.citizen_id AND a.service_id = app.service_id
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
WHERE s.agency_id LIKE 'AG%';

[User] Only include appointments that are booked via 'Kiosk' and scheduled after July 1, 2024.

[Assistant]
SELECT c.first_name, c.last_name, s.service_name
FROM government_services.appointments a
JOIN government_services.services s ON a.service_id = s.service_id
JOIN government_services.applications app ON a.citizen_id = app.citizen_id AND a.service_id = app.service_id
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
WHERE s.agency_id LIKE 'AG%'
  AND a.booking_method = 'Kiosk'
  AND a.scheduled_start_time > '2024-07-01';

[User] For each employee, show their first name, last name, and the total payment amount for applications they have been assigned to process.

[Assistant]
SELECT e.first_name, e.last_name, SUM(p.amount) AS total_payment_amount
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
JOIN government_services.payments p ON a.application_id = p.application_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Only consider payments with status 'Succeeded' and made after January 1, 2024.

[Assistant]
SELECT e.first_name, e.last_name, SUM(p.amount) AS total_payment_amount
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
JOIN government_services.payments p ON a.application_id = p.application_id
WHERE p.status = 'Succeeded'
  AND p.payment_timestamp > '2024-01-01'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] I got an error: missing column 'amount' in select list.

[Assistant]
SELECT e.first_name, e.last_name, COALESCE(SUM(p.amount), 0) AS total_payment_amount
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
LEFT JOIN government_services.payments p ON a.application_id = p.application_id AND p.status = 'Succeeded' AND p.payment_timestamp > '2024-01-01'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Instead of total payment, show the average payment amount per application for each employee.

[Assistant]
SELECT e.first_name, e.last_name, AVG(sub.app_payment_amount) AS avg_payment_per_application
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
LEFT JOIN (
    SELECT application_id, SUM(amount) AS app_payment_amount
    FROM government_services.payments
    WHERE status = 'Succeeded' AND payment_timestamp > '2024-01-01'
    GROUP BY application_id
) sub ON a.application_id = sub.application_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Which citizens have received notifications for applications processed by employees from the 'Legal' department? List the citizen ID, full name, and notification ID.

[Assistant]
SELECT n.citizen_id, CONCAT(e.first_name, ' ', e.last_name) AS full_name, n.notification_id
FROM government_services.notifications n
JOIN government_services.payments p ON n.application_id = p.application_id AND n.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.service_id IN (
  SELECT s.service_id
  FROM government_services.services s
  JOIN government_services.agencies a ON s.agency_id = a.agency_id
)
WHERE e.department = 'Legal';

[User] Which agencies offer services in the 'Social Assistance' category? Show the agency name and the service name.

[Assistant]
SELECT a.agency_name, s.service_name
FROM government_services.services s
JOIN government_services.agencies a ON s.agency_id = a.agency_id
WHERE s.category = 'Social Assistance';


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;

[User] Show me all accounts along with their associated customers' full names and the account status.

[Assistant]
SELECT a.account_id, a.account_number, a.account_type, a.status, c.first_name || ' ' || c.last_name AS customer_full_name
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
ORDER BY c.last_name, c.first_name, a.account_number;

[User] Limit to accounts that have been opened after 2022-01-01 and only include those with the status 'Active' or 'Open'.

[Assistant]
SELECT a.account_id, a.account_number, a.account_type, a.status, c.first_name || ' ' || c.last_name AS customer_full_name
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
WHERE a.opened_date > '2022-01-01'
  AND a.status IN ('Active', 'Open')
ORDER BY c.last_name, c.first_name, a.account_number;

[User] Also include the customer's risk_profile and only show accounts where the customer's risk_profile is not null.

[Assistant]
SELECT a.account_id, a.account_number, a.account_type, a.status, c.first_name || ' ' || c.last_name AS customer_full_name, c.risk_profile
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
WHERE a.opened_date > '2022-01-01'
  AND a.status IN ('Active', 'Open')
  AND c.risk_profile IS NOT NULL
ORDER BY c.last_name, c.first_name, a.account_number;

[User] Show the average close price and total volume for market data, grouped by source.

[Assistant] SELECT source, AVG(close_price), SUM(volume) FROM financial_services.market_data GROUP BY source;

[User] Only include data points with volume greater than 100000 and exclude sources where the total volume is less than 10000000.

[Assistant] SELECT first_name, last_name, job_title FROM financial_services.employees;

[User] Only show employees who are currently active.

[Assistant] SELECT first_name, last_name, job_title FROM financial_services.employees WHERE status = 'Active';

[User] Additionally, include their email address in the result.

[Assistant] SELECT first_name, last_name, job_title, email FROM financial_services.employees WHERE status = 'Active';

[User] Show me a summary of customers with their total account balance and the count of accounts.

[Assistant] SELECT c.first_name, c.last_name, COUNT(a.account_id) AS account_count, SUM(a.balance) AS total_account_balance FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id GROUP BY c.customer_id, c.first_name, c.last_name;

[User] Filter the results to only include customers where the combined balance across all their accounts exceeds 5000.

[Assistant] SELECT c.first_name, c.last_name, COUNT(a.account_id) AS account_count, SUM(a.balance) AS total_account_balance FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id GROUP BY c.customer_id, c.first_name, c.last_name HAVING SUM(a.balance) > 5000;

[User] Please modify the query to only count and sum balances for accounts with status 'ACTIVE'.

[Assistant] SELECT c.first_name, c.last_name, COUNT(CASE WHEN a.status = 'ACTIVE' THEN a.account_id ELSE NULL END) AS active_account_count, SUM(CASE WHEN a.status = 'ACTIVE' THEN a.balance ELSE 0 END) AS total_active_account_balance FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id GROUP BY c.customer_id, c.first_name, c.last_name HAVING SUM(CASE WHEN a.status = 'ACTIVE' THEN a.balance ELSE 0 END) > 5000;

[User] Order the results by customer last name, then first name.

[Assistant] SELECT c.first_name, c.last_name, COUNT(CASE WHEN a.status = 'ACTIVE' THEN a.account_id ELSE NULL END) AS active_account_count, SUM(CASE WHEN a.status = 'ACTIVE' THEN a.balance ELSE 0 END) AS total_active_account_balance FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id GROUP BY c.customer_id, c.first_name, c.last_name HAVING SUM(CASE WHEN a.status = 'ACTIVE' THEN a.balance ELSE 0 END) > 5000 ORDER BY c.last_name ASC, c.first_name ASC;

[User] Which securities have had the largest maximum single-day trading volume in the market_data table? Show me the ticker symbol, security name, and that maximum volume.

[Assistant]
SELECT s.ticker_symbol, s.security_name, MAX(md.volume) AS max_single_day_volume
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.security_id, s.ticker_symbol, s.security_name;

[User] Please also include the data_timestamp when the maximum volume was recorded for each security.

[Assistant]
SELECT s.ticker_symbol, s.security_name, md.volume AS max_single_day_volume, md.data_timestamp
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE (md.security_id, md.volume) IN (
  SELECT md2.security_id, MAX(md2.volume) FROM financial_services.market_data md2 GROUP BY md2.security_id
);

[User] Now limit the result to only securities in the 'Energy' sector, and show the exchange as well, sorted by max_single_day_volume descending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, s.exchange, md.volume AS max_single_day_volume, md.data_timestamp
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.sector = 'Energy'
  AND (md.security_id, md.volume) IN (
    SELECT md2.security_id, MAX(md2.volume)
    FROM financial_services.market_data md2
    GROUP BY md2.security_id
  )
ORDER BY max_single_day_volume 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.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;

[User] List all appointments showing the scheduled time, the name of the service, and the name of the location.

[Assistant] SELECT T1.scheduled_start_time, T2.service_name, T3.location_name FROM government_services.appointments AS T1 JOIN government_services.services AS T2 ON T1.service_id = T2.service_id JOIN government_services.service_locations AS T3 ON T1.location_id = T3.location_id;

[User] How many total appointments have been recorded?

[Assistant] SELECT count(*) FROM appointments;

[User] What is the count of appointments that have the status 'Completed'?

[Assistant] SELECT count(*) FROM appointments WHERE status = 'Completed';

[User] For completed appointments, list the purpose and the name of the related service.

[Assistant] SELECT T1.purpose, T2.service_name FROM appointments AS T1 JOIN services AS T2 ON T1.service_id = T2.service_id WHERE T1.status = 'Completed';

[User] Also include the location name for these completed appointments, specifically those booked via 'Online'.

[Assistant] SELECT T1.purpose, T2.service_name, T3.location_name FROM appointments AS T1 JOIN services AS T2 ON T1.service_id = T2.service_id JOIN service_locations AS T3 ON T1.location_id = T3.location_id WHERE T1.status = 'Completed' AND T1.booking_method = 'Online';

[User] Find the names of services and the locations where appointments have been scheduled for them.

[Assistant] SELECT T1.service_name, T2.location_name FROM services AS T1 JOIN appointments AS T3 ON T1.service_id = T3.service_id JOIN service_locations AS T2 ON T3.location_id = T2.location_id GROUP BY T1.service_name, T2.location_name;

[User] Only include appointments where the location is in the state of 'California'.

[Assistant] SELECT T1.service_name, T2.location_name FROM services AS T1 JOIN appointments AS T3 ON T1.service_id = T3.service_id JOIN service_locations AS T2 ON T3.location_id = T2.location_id WHERE T2.state = 'California' GROUP BY T1.service_name, T2.location_name;

[User] Find the names of service locations where services categorized as 'Licensing' have had appointments scheduled.

[Assistant] SELECT DISTINCT T1.location_name FROM service_locations AS T1 JOIN appointments AS T2 ON T1.location_id = T2.location_id JOIN services AS T3 ON T2.service_id = T3.service_id WHERE T3.category = 'Licensing';

[User] List the service name, category, and standard fee for all services offered by agencies that have at least one accessible service location in the state of 'California'.

[Assistant] SELECT DISTINCT T1.service_name, T1.category, T1.standard_fee 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';


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;

[User] List all tokens on the BSC chain with a price below $1.

[Assistant] SELECT token_symbol, token_name, price FROM token_dexpool_info WHERE chain = 'BSC' AND price < 1;

[User] Only show tokens where the 24-hour trading volume is above $200,000 and order the results by price ascending.

[Assistant] SELECT token_symbol, token_name, price FROM token_dexpool_info WHERE chain = 'BSC' AND price < 1 AND volume_24h > 200000 ORDER BY price ASC;

[User] For each chain, show the sum of smart money USD buy value and the average buy price for the 'AI' narrative, along with the top token by DEX liquidity from token_dexpool_info.

[Assistant]
WITH ai_inflow AS (
  SELECT chain, token_symbol, SUM(CASE WHEN type=1 THEN usd_value ELSE 0 END) AS total_buy_usd, AVG(CASE WHEN type=1 THEN avg_price END) AS avg_buy_price
  FROM smart_money_token_inflow
  WHERE narrative = 'AI'
  GROUP BY chain, token_symbol
),
top_liquidity AS (
  SELECT chain, token_symbol, liquidity,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY liquidity DESC) as rn
  FROM token_dexpool_info
  WHERE chain IN (SELECT DISTINCT chain FROM smart_money_token_inflow WHERE narrative='AI')
)
SELECT a.chain, a.total_buy_usd, a.avg_buy_price, t.token_symbol AS top_liquidity_token, t.liquidity
FROM (
  SELECT chain, SUM(total_buy_usd) AS total_buy_usd, AVG(avg_buy_price) AS avg_buy_price
  FROM ai_inflow
  GROUP BY chain
) a
LEFT JOIN top_liquidity t ON a.chain = t.chain AND t.rn = 1;

[User] What if I want to show the result only for chains where the total buy USD value exceeds $100,000?

[Assistant]
WITH ai_inflow AS (
  SELECT chain, token_symbol, SUM(CASE WHEN type=1 THEN usd_value ELSE 0 END) AS total_buy_usd, AVG(CASE WHEN type=1 THEN avg_price END) AS avg_buy_price
  FROM smart_money_token_inflow
  WHERE narrative = 'AI'
  GROUP BY chain, token_symbol
),
top_liquidity AS (
  SELECT chain, token_symbol, liquidity,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY liquidity DESC) as rn
  FROM token_dexpool_info
  WHERE chain IN (SELECT DISTINCT chain FROM smart_money_token_inflow WHERE narrative='AI')
)
SELECT a.chain, a.total_buy_usd, a.avg_buy_price, t.token_symbol AS top_liquidity_token, t.liquidity
FROM (
  SELECT chain, SUM(total_buy_usd) AS total_buy_usd, AVG(avg_buy_price) AS avg_buy_price
  FROM ai_inflow
  GROUP BY chain
  HAVING SUM(total_buy_usd) > 100000
) a
LEFT JOIN top_liquidity t ON a.chain = t.chain AND t.rn = 1;

[User] Can you also show the top token's 24h DEX trading volume along with liquidity?

[Assistant]
WITH ai_inflow AS (
  SELECT chain, token_symbol, SUM(CASE WHEN type=1 THEN usd_value ELSE 0 END) AS total_buy_usd, AVG(CASE WHEN type=1 THEN avg_price END) AS avg_buy_price
  FROM smart_money_token_inflow
  WHERE narrative = 'AI'
  GROUP BY chain, token_symbol
),
top_liquidity AS (
  SELECT chain, token_symbol, liquidity, volume_24h,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY liquidity DESC) as rn
  FROM token_dexpool_info
  WHERE chain IN (SELECT DISTINCT chain FROM smart_money_token_inflow WHERE narrative='AI')
)
SELECT a.chain, a.total_buy_usd, a.avg_buy_price, t.token_symbol AS top_liquidity_token, t.liquidity, t.volume_24h
FROM (
  SELECT chain, SUM(total_buy_usd) AS total_buy_usd, AVG(avg_buy_price) AS avg_buy_price
  FROM ai_inflow
  GROUP BY chain
  HAVING SUM(total_buy_usd) > 100000
) a
LEFT JOIN top_liquidity t ON a.chain = t.chain AND t.rn = 1;

[User] Show the top 3 tokens on Polygon with the greatest positive price change over the last 6 hours, including their symbol, price, 6h change, and the number of smart money buy addresses in the last 24h.

[Assistant]
SELECT tdi.token_symbol, tdi.price, tdi.price_change_percentage_6h,
  COALESCE(SUM(CASE WHEN smti.type = 1 AND smti.chain = 'Polygon' THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain = 'Polygon' AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.price, tdi.price_change_percentage_6h
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;

[User] Instead of just Polygon, can you show the top 3 tokens with the greatest positive 6h price change across both Polygon and BSC? Still include the number of smart money buys.

[Assistant]
SELECT tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h,
  COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain IN ('Polygon', 'BSC') AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;

[User] Now, only display tokens with at least 10 smart money buy addresses. Also, add their 24h trading volume.

[Assistant]
SELECT tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h, tdi.volume_24h,
  COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain IN ('Polygon', 'BSC') AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h, tdi.volume_24h
HAVING COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) >= 10
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;

[User] Show me tokens with a 24-hour trading volume over $1,000,000 from DEX pools that also have a positive net flow from smart money addresses. Display the token symbol, chain, 24h volume, and net flow.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0;

[User] Okay, now refine the results to only include tokens where the smart money ROI is greater than 5 (500%) and the realized ratio is above 0.5.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Add the token's current price from the basic info table and its narrative category to the results.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Order the final list by 24-hour trading volume descending and show the top 10.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5 ORDER BY tdi.volume_24h DESC LIMIT 10;

[User] What is the total USD value of tokens held by Binance exchange on the Ethereum chain according to the cex_token_balance table?

[Assistant] SELECT SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'Ethereum';


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;

[User] Show me the number of direct replies each top-level comment has on post 'P200'.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id;

[User] Order by reply_count descending and limit to top 5.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id ORDER BY reply_count DESC LIMIT 5;

[User] Count the total number of comments each user has made.

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

[User] Which users have commented on posts created by the users they follow? Please show the commenter user_ids and the followed user_ids.

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_user_id);

[User] Can you also include the post_id in the results?

[Assistant] SELECT DISTINCT c.user_id AS commenter_user_id, f.following_user_id AS followed_user_id, c.post_id FROM social_media.comments c JOIN social_media.follows f ON c.user_id = f.follower_user_id AND c.post_id IN (SELECT post_id FROM social_media.comments WHERE user_id = f.following_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 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;

[User] Show me the average number of current players per server for each region.

[Assistant]
SELECT region, AVG(current_players) AS avg_current_players
FROM gaming_technology.servers
GROUP BY region;

[User] Only include regions where the average is above 50.

[Assistant]
SELECT region, AVG(current_players) AS avg_current_players
FROM gaming_technology.servers
GROUP BY region
HAVING AVG(current_players) > 50;

[User] Also show the total number of servers for each region in the result.

[Assistant]
SELECT region, AVG(current_players) AS avg_current_players, COUNT(*) AS total_servers
FROM gaming_technology.servers
GROUP BY region
HAVING AVG(current_players) > 50;

[User] Sort the list by avg_current_players descending.

[Assistant]
SELECT region, AVG(current_players) AS avg_current_players, COUNT(*) AS total_servers
FROM gaming_technology.servers
GROUP BY region
HAVING AVG(current_players) > 50
ORDER BY avg_current_players DESC;

[User] Can you show me the titles and release dates of all games developed by companies founded after 2018, as well as the name and country of each developer?

[Assistant]
SELECT g.title, g.release_date, d.name AS developer_name, d.country
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE d.founded_year > 2018;

[User] And also include the platform for each game.

[Assistant]
SELECT g.title, g.release_date, g.platform, d.name AS developer_name, d.country
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE d.founded_year > 2018;

[User] For each publisher, find pairs of games they have published that belong to different genres. Include publisher_id, the genre and title of both games in each pair.

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

[User] Exclude any pairs where genre1 or genre2 is NULL.

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

[User] Make sure each pair only appears once, without reversed duplicates.

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

[User] Order the results by publisher_id and then by title1 ascending.

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

[User] List all games and the servers hosting them, showing the game title, server name, region, and status.

[Assistant] SELECT g.title, s.server_name, s.region, s.status FROM gaming_technology.games g JOIN gaming_technology.servers s ON g.game_id = s.game_id;

[User] Can you provide a list of each game's title along with the total quantity of all items players have in their inventory for that game?

[Assistant]
SELECT g.title, SUM(pi.quantity) AS total_item_quantity
FROM gaming_technology.games g
JOIN gaming_technology.in_game_items ii ON g.game_id = ii.game_id
JOIN gaming_technology.player_inventory pi ON pi.item_id = ii.item_id
GROUP BY g.title;

[User] Can you only include games where the total quantity of items in inventories is greater than 500?

[Assistant]
SELECT g.title, SUM(pi.quantity) AS total_item_quantity
FROM gaming_technology.games g
JOIN gaming_technology.in_game_items ii ON g.game_id = ii.game_id
JOIN gaming_technology.player_inventory pi ON pi.item_id = ii.item_id
GROUP BY g.title
HAVING SUM(pi.quantity) > 500;

[User] Could you also include the game platform in the results and order by total_item_quantity descending?

[Assistant]
SELECT g.title, g.platform, SUM(pi.quantity) AS total_item_quantity
FROM gaming_technology.games g
JOIN gaming_technology.in_game_items ii ON g.game_id = ii.game_id
JOIN gaming_technology.player_inventory pi ON pi.item_id = ii.item_id
GROUP BY g.title, g.platform
HAVING SUM(pi.quantity) > 500
ORDER BY total_item_quantity DESC;

[User] Actually, also show only the games released after 2021-01-01.

[Assistant]
SELECT g.title, g.platform, SUM(pi.quantity) AS total_item_quantity
FROM gaming_technology.games g
JOIN gaming_technology.in_game_items ii ON g.game_id = ii.game_id
JOIN gaming_technology.player_inventory pi ON pi.item_id = ii.item_id
WHERE g.release_date > '2021-01-01'
GROUP BY g.title, g.platform
HAVING SUM(pi.quantity) > 500
ORDER BY total_item_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.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;

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

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

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

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

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

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

[User] How many users is each user following? Provide follower_user_id and the count of followings.

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

[User] Can you find all mutual follows in the system by joining the table with itself? For each mutual follow, show both user IDs and the date when the follow occurred.

[Assistant]
SELECT f1.follower_user_id AS user_a, f1.following_user_id AS user_b, f1.created_at
FROM social_media.follows f1
JOIN social_media.follows f2
  ON f1.follower_user_id = f2.following_user_id
  AND f1.following_user_id = f2.follower_user_id;

[User] Only include mutual follows that were established in 2024.

[Assistant]
SELECT f1.follower_user_id AS user_a, f1.following_user_id AS user_b, f1.created_at
FROM social_media.follows f1
JOIN social_media.follows f2
  ON f1.follower_user_id = f2.following_user_id
  AND f1.following_user_id = f2.follower_user_id
WHERE DATE_PART('year', f1.created_at) = 2024;

[User] Sort the results by creation date descending.

[Assistant]
SELECT f1.follower_user_id AS user_a, f1.following_user_id AS user_b, f1.created_at
FROM social_media.follows f1
JOIN social_media.follows f2
  ON f1.follower_user_id = f2.following_user_id
  AND f1.following_user_id = f2.follower_user_id
WHERE DATE_PART('year', f1.created_at) = 2024
ORDER BY f1.created_at DESC;

[User] Also include the follow IDs of both entries in the output.

[Assistant]
SELECT f1.follow_id AS follow_id_a, f2.follow_id AS follow_id_b, f1.follower_user_id AS user_a, f1.following_user_id AS user_b, f1.created_at
FROM social_media.follows f1
JOIN social_media.follows f2
  ON f1.follower_user_id = f2.following_user_id
  AND f1.following_user_id = f2.follower_user_id
WHERE DATE_PART('year', f1.created_at) = 2024
ORDER BY f1.created_at DESC;

[User] Count how many follow relationships were created in June 2024.

[Assistant] SELECT COUNT(follow_id) FROM social_media.follows WHERE created_at >= '2024-06-01' AND created_at < '2024-07-01';

[User] For each user, count how many different conversations they have participated in. Show user_id and conversation_count.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversation_count
FROM social_media.conversation_participants
GROUP BY user_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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;

[User] List all token transfers showing the transfer id, the symbol of the transferred token, and the contract address where the token was created.

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

[User] For each wallet, show the wallet address and the total value of tokens they have received across all token transfers.

[Assistant]
SELECT w.address, COALESCE(SUM(tt.value), 0) AS total_received_value
FROM web3.wallets w
LEFT JOIN web3.token_transfers tt ON w.address = tt.to_address
GROUP BY w.address;

[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and the count of transactions they've been involved in, sorted by transaction count in descending order.

[Assistant] SELECT c.address, c.deployer_address, COUNT(t.transaction_id) AS transaction_count FROM web3.contracts c LEFT JOIN web3.transactions t ON c.address = t.to_address WHERE c.network_id = 'ethereum' GROUP BY c.address, c.deployer_address ORDER BY transaction_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 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;

[User] Show me the average transaction amount per block, along with the block timestamp.

[Assistant] SELECT b.block_id, b.timestamp as block_timestamp, AVG(t.amount) as avg_transaction_amount FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id GROUP BY b.block_id, b.timestamp ORDER BY b.timestamp;

[User] Now filter this to only show blocks with more than 10 transactions.

[Assistant] SELECT b.block_id, b.timestamp as block_timestamp, AVG(t.amount) as avg_transaction_amount, COUNT(*) as transaction_count FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id GROUP BY b.block_id, b.timestamp HAVING COUNT(*) > 10 ORDER BY b.timestamp;

[User] Can you also include the difficulty level of these blocks?

[Assistant] SELECT b.block_id, b.timestamp as block_timestamp, b.difficulty, AVG(t.amount) as avg_transaction_amount, COUNT(*) as transaction_count FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id GROUP BY b.block_id, b.timestamp, b.difficulty HAVING COUNT(*) > 10 ORDER BY b.timestamp;

[User] Retrieve the username and email for every user, along with the wallet ID and associated address ID for any wallets they own.

[Assistant]
SELECT
    u.username,
    u.email,
    w.wallet_id,
    w.address_id
FROM
    blockchain.users AS u
LEFT JOIN
    blockchain.wallets AS w ON u.user_id = w.user_id;