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.transactions ( transaction_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, related_account_id character varying(64), transaction_type character varying(50) NOT NULL, amount numeric(19, 4) NOT NULL, currency character varying(3) NOT NULL, transaction_date timestamp NOT NULL, effective_date date NOT NULL, description text, status character varying(32) NOT NULL, reference_number character varying(128), 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, ticker_symbol character varying(20) NOT NULL UNIQUE, isin_code character varying(12) UNIQUE, cusip_code character varying(9) UNIQUE, security_name text NOT NULL, security_type character varying(50) NOT NULL, exchange character varying(50), currency character varying(3) NOT NULL, issuer_name character varying(255), sector character varying(100), last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (security_id) )
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )

[User] List all customers and the total amount they have traded, showing their full name, email, and the total across all their trades. Join customers to their accounts, then to trades.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
GROUP BY c.customer_id, c.first_name, c.last_name, c.email;

[User] Please include only trades with a status of 'EXECUTED' in the calculation.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
WHERE t.status = 'EXECUTED'
GROUP BY c.customer_id, c.first_name, c.last_name, c.email;

[User] Only show customers whose total_trade_amount is greater than 5000.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
WHERE t.status = 'EXECUTED'
GROUP BY c.customer_id, c.first_name, c.last_name, c.email
HAVING SUM(t.total_amount) > 5000;

[User] Sort the result by total_trade_amount in descending order and limit to the first 10 results.

[Assistant]
SELECT c.customer_id, c.first_name, c.last_name, c.email, SUM(t.total_amount) AS total_trade_amount
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.trades t ON a.account_id = t.account_id
WHERE t.status = 'EXECUTED'
GROUP BY c.customer_id, c.first_name, c.last_name, c.email
HAVING SUM(t.total_amount) > 5000
ORDER BY total_trade_amount DESC
LIMIT 10;

[User] List each security and the total amount traded for it, with ticker symbol and security name. Only include trades from the last 90 days.

[Assistant]
SELECT s.ticker_symbol, s.security_name, SUM(t.total_amount) AS total_traded_amount
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
GROUP BY s.ticker_symbol, s.security_name;

[User] Also include the number of distinct accounts involved in trades for each security during this period.

[Assistant]
SELECT s.ticker_symbol, s.security_name, SUM(t.total_amount) AS total_traded_amount, COUNT(DISTINCT t.account_id) AS account_count
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
GROUP BY s.ticker_symbol, s.security_name;

[User] Only display securities where the account_count is greater than 5, and sort by total_traded_amount descending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, SUM(t.total_amount) AS total_traded_amount, COUNT(DISTINCT t.account_id) AS account_count
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
WHERE t.trade_timestamp >= NOW() - INTERVAL '90 days'
GROUP BY s.ticker_symbol, s.security_name
HAVING COUNT(DISTINCT t.account_id) > 5
ORDER BY total_traded_amount DESC;

[User] I need a summary of total traded volume and average price per unit by sector using the trades and securities tables for trades in the last 30 days.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
GROUP BY s.sector;

[User] Only include sectors where the summed quantity is at least 1000.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
GROUP BY s.sector
HAVING SUM(t.quantity) >= 1000;

[User] Sort the result by average price per unit ascending.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
GROUP BY s.sector
HAVING SUM(t.quantity) >= 1000
ORDER BY avg_price_per_unit ASC;

[User] Also ensure sectors are not null.

[Assistant]
SELECT
  s.sector,
  SUM(t.quantity) AS total_volume,
  AVG(t.price_per_unit) AS avg_price_per_unit
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE t.trade_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30 days'
  AND s.sector IS NOT NULL
GROUP BY s.sector
HAVING SUM(t.quantity) >= 1000
ORDER BY avg_price_per_unit ASC;

[User] Show me all loans with matching collateral, displaying loan_id, principal_amount, the collateral ticker, and its sector.

[Assistant]
SELECT
  l.loan_id,
  l.principal_amount,
  s.ticker_symbol,
  s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol;

[User] Filter this to loans with status 'Active' and securities of type 'Bond'.

[Assistant]
SELECT
  l.loan_id,
  l.principal_amount,
  s.ticker_symbol,
  s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol
WHERE l.status = 'Active'
  AND s.security_type = 'Bond';

[User] Finally, sort by maturity_date ascending and limit the result to the first 10 rows.

[Assistant]
SELECT
  l.loan_id,
  l.principal_amount,
  s.ticker_symbol,
  s.sector
FROM financial_services.loans l
JOIN financial_services.securities s
  ON l.collateral_description = s.ticker_symbol
WHERE l.status = 'Active'
  AND s.security_type = 'Bond'
ORDER BY l.maturity_date ASC
LIMIT 10;

[User] List each employee and their manager's full name, showing employee_id, employee full name, and manager full name.

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

[User] Only include active employees and exclude those without a manager.

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

[User] Now sort the output by department ascending and then by employee_name ascending.

[Assistant]
SELECT
  e.employee_id,
  e.first_name || ' ' || e.last_name AS employee_name,
  m.first_name || ' ' || m.last_name AS manager_name
FROM financial_services.employees e
JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.status = 'Active'
  AND e.manager_id IS NOT NULL
ORDER BY e.department ASC, employee_name ASC;

[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;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )

[User] Show me the total fuel cost for each vehicle, grouped by fuel type.

[Assistant] SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_fuel_cost FROM transportation.fuel_logs GROUP BY vehicle_id, fuel_type;

[User] Can you include the average quantity per fuel type for each vehicle as well?

[Assistant] SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_fuel_cost, AVG(quantity) AS average_quantity FROM transportation.fuel_logs GROUP BY vehicle_id, fuel_type;

[User] Now filter this to only show results where the total fuel cost exceeds $1000.

[Assistant] SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_fuel_cost, AVG(quantity) AS average_quantity FROM transportation.fuel_logs GROUP BY vehicle_id, fuel_type HAVING SUM(total_cost) > 1000;

[User] Calculate the monthly total quantity of fuel consumed and the average cost_per_unit for each fuel_type in 2023.

[Assistant]
SELECT date_trunc('month', log_timestamp) AS month,
       fuel_type,
       SUM(quantity)      AS total_quantity,
       AVG(cost_per_unit) AS avg_cost_per_unit
FROM transportation.fuel_logs
WHERE log_timestamp >= '2023-01-01'
  AND log_timestamp <  '2024-01-01'
GROUP BY 1, fuel_type
ORDER BY 1, fuel_type;

[User] Now limit the results to fuel types where the total_quantity exceeds 1000 units in that month.

[Assistant]
SELECT month,
       fuel_type,
       total_quantity,
       avg_cost_per_unit
FROM (
  SELECT date_trunc('month', log_timestamp) AS month,
         fuel_type,
         SUM(quantity)      AS total_quantity,
         AVG(cost_per_unit) AS avg_cost_per_unit
  FROM transportation.fuel_logs
  WHERE log_timestamp >= '2023-01-01'
    AND log_timestamp <  '2024-01-01'
  GROUP BY 1, fuel_type
) sub
WHERE total_quantity > 1000
ORDER BY month, fuel_type;

[User] Calculate the total quantity and average cost_per_unit for each fuel_type in the fuel_logs table.

[Assistant]
SELECT fuel_type,
       SUM(quantity)         AS total_quantity,
       AVG(cost_per_unit)    AS avg_cost_per_unit
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Actually, only include fuel types where the total quantity exceeds 1000 and order the results by avg_cost_per_unit descending.

[Assistant]
SELECT fuel_type,
       SUM(quantity)         AS total_quantity,
       AVG(cost_per_unit)    AS avg_cost_per_unit
FROM transportation.fuel_logs
GROUP BY fuel_type
HAVING SUM(quantity) > 1000
ORDER BY avg_cost_per_unit DESC;

[User] List all pairs of fuel log entries for the same vehicle that occurred more than 7 days apart, showing vehicle_id, first_log_id, second_log_id, and the time difference in days.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days';

[User] Now filter to only include pairs where the quantity increased by at least 50 units.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days'
WHERE (f2.quantity - f1.quantity) >= 50;

[User] Also display the difference in total_cost between the two logs.

[Assistant]
SELECT f1.vehicle_id,
       f1.fuel_log_id AS first_log_id,
       f2.fuel_log_id AS second_log_id,
       EXTRACT(EPOCH FROM (f2.log_timestamp - f1.log_timestamp))/86400 AS days_difference,
       (f2.quantity - f1.quantity)      AS quantity_difference,
       (f2.total_cost - f1.total_cost)  AS cost_difference
FROM transportation.fuel_logs f1
JOIN transportation.fuel_logs f2
  ON f1.vehicle_id = f2.vehicle_id
 AND f2.log_timestamp > f1.log_timestamp + INTERVAL '7 days'
WHERE (f2.quantity - f1.quantity) >= 50;

[User] For each vehicle and unit combination, show the total quantity of fuel refueled and the total cost.

[Assistant]
SELECT vehicle_id, unit, SUM(quantity) AS total_quantity, SUM(total_cost) AS total_cost
FROM transportation.fuel_logs
GROUP BY vehicle_id, unit;

[User] Identify all instances where a vehicle's odometer_reading increased by more than 500 miles between two consecutive fuel log entries.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       a.log_timestamp                       AS previous_time,
       b.log_timestamp                       AS next_time,
       b.odometer_reading - a.odometer_reading AS mile_increase
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500;

[User] Now restrict these increases to those where the time difference between entries is less than 7 days.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       a.log_timestamp                       AS previous_time,
       b.log_timestamp                       AS next_time,
       b.odometer_reading - a.odometer_reading AS mile_increase,
       EXTRACT(epoch FROM (b.log_timestamp - a.log_timestamp))/3600 AS hours_diff
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500
  AND b.log_timestamp - a.log_timestamp < INTERVAL '7 days';

[User] Also include both the mile increase and the time difference in hours in the final output columns.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       b.odometer_reading - a.odometer_reading AS mile_increase,
       EXTRACT(epoch FROM (b.log_timestamp - a.log_timestamp))/3600 AS hours_difference
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500
  AND b.log_timestamp - a.log_timestamp < INTERVAL '7 days';


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

[User] Show me the names and URLs of all DApps, and for each DApp, list the KYC status and last review date for all users who have an audit entry.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
ORDER BY d.name, k.user_id;

[User] I only want DApps whose name includes the word 'market', and for KYC audits, show only those with status 'approved'.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.name ILIKE '%market%' AND k.status = 'approved'
ORDER BY d.name, k.user_id;

[User] List the names of all DApps whose description contains the word 'auction' along with the user IDs of anyone who has had a KYC audit.

[Assistant]
SELECT d.name AS dapp_name, k.user_id
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
ORDER BY d.name, k.user_id;

[User] Just show KYC audits with a status that is not 'approved'.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id;

[User] Actually, I want to include the reviewed_at time for each audit result too.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] Filter further to only show audits reviewed after January 1, 2024.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
  AND k.reviewed_at > '2024-01-01'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] How many unique users have a KYC audit record with status 'pending'?

[Assistant]
SELECT COUNT(DISTINCT user_id) AS pending_kyc_users
FROM trading_platform.kyc_audit
WHERE status = 'pending';

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )

[User] Show all prescriptions with prescription_id, patient_id, medication_id, quantity_dispensed, and refills_allowed.

[Assistant] SELECT prescription_id, patient_id, medication_id, quantity_dispensed, refills_allowed FROM healthcare.prescriptions;

[User] Filter this list to include only prescriptions where the quantity dispensed is greater than 20 and refills allowed is 0.

[Assistant] SELECT prescription_id, patient_id, medication_id, quantity_dispensed, refills_allowed FROM healthcare.prescriptions WHERE quantity_dispensed > 20 AND refills_allowed = 0;

[User] List appointments including ID, patient ID, doctor ID, time, and duration, where the reason is 'follow-up'.

[Assistant] SELECT appointment_id, patient_id, doctor_id, appointment_time, duration_minutes FROM healthcare.appointments WHERE reason = 'follow-up';

[User] Only show those appointments where the duration is greater than 30 minutes.

[Assistant] SELECT appointment_id, patient_id, doctor_id, appointment_time, duration_minutes FROM healthcare.appointments WHERE reason = 'follow-up' AND duration_minutes > 30;

[User] Also include the doctor's first and last name in the result and sort by appointment time.

[Assistant] SELECT T1.appointment_id, T1.patient_id, T1.doctor_id, T2.first_name, T2.last_name, T1.appointment_time, T1.duration_minutes FROM healthcare.appointments AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id WHERE T1.reason = 'follow-up' AND T1.duration_minutes > 30 ORDER BY T1.appointment_time;

[User] Show me all doctors who have prescribed medications along with the count of prescriptions they've made, ordered by the count in descending order.

[Assistant] SELECT d.doctor_id, d.first_name, d.last_name, COUNT(p.prescription_id) AS prescription_count FROM healthcare.doctors d JOIN healthcare.prescriptions p ON d.doctor_id = p.doctor_id GROUP BY d.doctor_id, d.first_name, d.last_name ORDER BY prescription_count DESC;

[User] Show all doctors whose license number starts with 'MD', including their ID, first name, and last name.

[Assistant] SELECT doctor_id, first_name, last_name FROM healthcare.doctors WHERE license_number LIKE 'MD%';

[User] Now, also include their specialty and phone number in the result.

[Assistant] SELECT doctor_id, first_name, last_name, specialty, phone_number FROM healthcare.doctors WHERE license_number LIKE 'MD%';

[User] Show all diagnoses, including the diagnosis ID, description, diagnosis date, and the full name of the doctor who made the diagnosis.

[Assistant] SELECT T1.diagnosis_id, T1.description, T1.diagnosis_date, T2.first_name, T2.last_name FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id;

[User] Refine this list to only include diagnoses where the diagnosis_date is in the year 2023 and the doctor's specialty is 'Cardiology'.

[Assistant] SELECT T1.diagnosis_id, T1.description, T1.diagnosis_date, T2.first_name, T2.last_name FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id WHERE T2.specialty = 'Cardiology' AND EXTRACT(YEAR FROM T1.diagnosis_date) = 2023;

[User] List the medical record ID and record date for all medical records that are linked to an appointment whose duration was longer than the average duration of all appointments.

[Assistant] SELECT T1.record_id, T1.record_date FROM healthcare.medical_records AS T1 JOIN healthcare.appointments AS T2 ON T1.appointment_id = T2.appointment_id WHERE T2.duration_minutes > (SELECT AVG(duration_minutes) FROM healthcare.appointments);


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.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 )

[User] Can you show me the total amount paid by each citizen for each service? Please display the citizen_id, service_id, and the total amount.

[Assistant]
SELECT citizen_id, service_id, SUM(amount) AS total_amount
FROM government_services.payments
GROUP BY citizen_id, service_id;

[User] Actually, I only want to see results for payments with status 'Succeeded'.

[Assistant]
SELECT citizen_id, service_id, SUM(amount) AS total_amount
FROM government_services.payments
WHERE status = 'Succeeded'
GROUP BY citizen_id, service_id;

[User] Show me all failed payments along with the application ID, citizen ID, and payment timestamp.

[Assistant]
SELECT payment_id, application_id, citizen_id, payment_timestamp
FROM government_services.payments
WHERE status = 'Failed';

[User] Show me the total payment amount and number of payments for each service.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id;

[User] Only include services where more than 3 payments have been made.

[Assistant] SELECT service_id, SUM(amount) AS total_amount, COUNT(*) AS payment_count FROM government_services.payments GROUP BY service_id HAVING COUNT(*) > 3;

[User] Can you show the total amount paid and number of payments per citizen in 2024?

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' GROUP BY citizen_id;

[User] Add a filter to only include payments with the status 'Succeeded'.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id;

[User] Now, only show those citizens who have paid more than 1000 in total.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id HAVING SUM(amount) > 1000;

[User] Show the result ordered by total_paid descending and limit to top 10 citizens.

[Assistant] SELECT citizen_id, SUM(amount) AS total_paid, COUNT(*) AS payment_count FROM government_services.payments WHERE payment_timestamp >= '2024-01-01' AND payment_timestamp < '2025-01-01' AND status = 'Succeeded' GROUP BY citizen_id HAVING SUM(amount) > 1000 ORDER BY total_paid DESC LIMIT 10;

[User] For each payment method, show the total number of completed payments and the total amount paid.

[Assistant] SELECT payment_method, COUNT(*) AS completed_count, SUM(amount) AS total_paid FROM government_services.payments WHERE status = 'Completed' GROUP BY payment_method;

[User] How many payments have been made using each payment_method, and what is the total amount for each method?

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
GROUP BY payment_method;

[User] Can you filter to only include methods where the total_amount exceeds 1000?

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
GROUP BY payment_method
HAVING SUM(amount) > 1000;

[User] Also exclude any payments with status other than 'Completed'.

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
WHERE status = 'Completed'
GROUP BY payment_method
HAVING SUM(amount) > 1000;

[User] Order the results by total_amount descending and limit to the top 5 payment methods.

[Assistant]
SELECT payment_method, COUNT(*) AS payment_count, SUM(amount) AS total_amount
FROM government_services.payments
WHERE status = 'Completed'
GROUP BY payment_method
HAVING SUM(amount) > 1000
ORDER BY total_amount DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)

[User] List each patient's first and last medical record entries, showing patient_id, earliest_record_id, earliest_record_date, latest_record_id, and latest_record_date.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date
        FROM healthcare.medical_records
        GROUP BY patient_id
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] Filter to include only patients who have at least three medical record entries.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date,
            COUNT(*) AS total_records
        FROM healthcare.medical_records
        GROUP BY patient_id
        HAVING COUNT(*) >= 3
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] Also include for each patient the count of distinct days on which records were made, labeled active_days.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date,
    fl.active_days
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date,
            COUNT(*) AS total_records,
            COUNT(DISTINCT date_trunc('day', record_date)) AS active_days
        FROM healthcare.medical_records
        GROUP BY patient_id
        HAVING COUNT(*) >= 3
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] What is the total count of medical records created in the year 2023 where the assessment field is not empty?

[Assistant] SELECT COUNT(*) FROM healthcare.medical_records mr WHERE (mr.assessment IS NOT NULL AND mr.assessment != '') AND EXTRACT(YEAR FROM mr.record_date) = 2023;

[User] Now, break down this count by the doctor who created the record. Show the doctor_id and the count.

[Assistant] SELECT mr.doctor_id, COUNT(*) FROM healthcare.medical_records mr WHERE (mr.assessment IS NOT NULL AND mr.assessment != '') AND EXTRACT(YEAR FROM mr.record_date) = 2023 GROUP BY mr.doctor_id;

[User] List the record ID, record date, patient ID, and chief complaint for medical records belonging to patients whose last name is 'Smith'. Also include the patient's last name in the results.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith';

[User] Refine this list to only show records where the record date is in 2024 and the chief complaint is not null. Sort by record_date in ascending order.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith' AND EXTRACT(YEAR FROM mr.record_date) = 2024 AND (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') ORDER BY mr.record_date ASC;

[User] List all pairs of record_id for the same patient that were created on the same day. Show the two record_ids, patient_id, and the date.

[Assistant]
SELECT
    mr1.patient_id,
    date_trunc('day', mr1.record_date) AS record_day,
    mr1.record_id AS record_id_1,
    mr2.record_id AS record_id_2
FROM healthcare.medical_records mr1
JOIN healthcare.medical_records mr2
  ON mr1.patient_id = mr2.patient_id
 AND date_trunc('day', mr1.record_date) = date_trunc('day', mr2.record_date)
 AND mr1.record_id < mr2.record_id;

[User] Only include pairs where both records have a heart rate over 100 in their vitals.

[Assistant]
SELECT
    mr1.patient_id,
    date_trunc('day', mr1.record_date) AS record_day,
    mr1.record_id AS record_id_1,
    mr2.record_id AS record_id_2
FROM healthcare.medical_records mr1
JOIN healthcare.medical_records mr2
  ON mr1.patient_id = mr2.patient_id
 AND date_trunc('day', mr1.record_date) = date_trunc('day', mr2.record_date)
 AND mr1.record_id < mr2.record_id
WHERE (mr1.vitals->>'HR')::int > 100
  AND (mr2.vitals->>'HR')::int > 100;

[User] I would like to see a list of all medical records where the chief complaint contains the word 'cough' along with the doctor's ID and the date of the record.

[Assistant] SELECT record_id, doctor_id, record_date, chief_complaint FROM healthcare.medical_records WHERE chief_complaint ILIKE '%cough%';

[User] Could you expand this to show only records where the temperature in the vitals field is above 37.5°C?

[Assistant] SELECT record_id, doctor_id, record_date, chief_complaint, vitals->>'temperature' AS temperature FROM healthcare.medical_records WHERE chief_complaint ILIKE '%cough%' AND (vitals->>'temperature')::float > 37.5;

[User] Now, restrict it further to only show records documented after January 1st, 2024.

[Assistant] SELECT record_id, doctor_id, record_date, chief_complaint, vitals->>'temperature' AS temperature FROM healthcare.medical_records WHERE chief_complaint ILIKE '%cough%' AND (vitals->>'temperature')::float > 37.5 AND record_date >= '2024-01-01';

[User] Find all medical records associated with an appointment, and show the record_id, appointment_id, and the record_date.

[Assistant]
SELECT record_id, appointment_id, record_date
FROM healthcare.medical_records
WHERE appointment_id IS NOT NULL;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)

[User] I want a list of DApp names and the asset symbols mentioned in their descriptions.

[Assistant]
SELECT d.name AS dapp_name,
       a.symbol AS asset_symbol
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%';

[User] Now, only include DApps where the description mentions more than one distinct asset symbol.

[Assistant]
SELECT d.name AS dapp_name,
       COUNT(DISTINCT a.symbol) AS symbol_count
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Also show the comma-separated list of these symbols.

[Assistant]
SELECT d.name AS dapp_name,
       COUNT(DISTINCT a.symbol) AS symbol_count,
       STRING_AGG(DISTINCT a.symbol, ',') AS symbols_list
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Finally, order the result by number of mentioned assets descending and limit to top 3.

[Assistant]
SELECT d.name AS dapp_name,
       COUNT(DISTINCT a.symbol) AS symbol_count,
       STRING_AGG(DISTINCT a.symbol, ',') AS symbols_list
FROM trading_platform.dapps d
JOIN trading_platform.assets a
  ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name
HAVING COUNT(DISTINCT a.symbol) > 1
ORDER BY symbol_count DESC
LIMIT 3;

[User] List all assets mentioned in DApp descriptions along with the DApp name and URL.

[Assistant]
SELECT a.name AS asset_name,
       a.symbol AS asset_symbol,
       d.name AS dapp_name,
       d.url
FROM trading_platform.assets a
JOIN trading_platform.dapps d
  ON d.description ILIKE '%' || a.symbol || '%';

[User] Actually, only include assets of type 'cryptocurrency'.

[Assistant]
SELECT a.name AS asset_name,
       a.symbol AS asset_symbol,
       d.name AS dapp_name,
       d.url
FROM trading_platform.assets a
JOIN trading_platform.dapps d
  ON d.description ILIKE '%' || a.symbol || '%'
WHERE a.type = 'cryptocurrency';

[User] How many UTXOs have the 'spent' flag set to false?

[Assistant]
SELECT COUNT(*) AS unspent_utxo_count
FROM trading_platform.utxos
WHERE spent = false;

[User] Show all DApps that have metadata linked to an asset with a key of 'category', including the DApp name, URL, and the associated asset_id.

[Assistant]
SELECT d.name, d.url, m.asset_id
FROM trading_platform.dapps d
JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id
WHERE m.key = 'category';

[User] Instead, list the DApp name, URL, and also include the metadata value as 'category' in the result.

[Assistant]
SELECT d.name, d.url, m.value AS category
FROM trading_platform.dapps d
JOIN trading_platform.metadata m ON d.dapp_id = m.asset_id
WHERE m.key = 'category';


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.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )

[User] Could you list each player's username and the total number of sessions they have played?

[Assistant]
SELECT p.username, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
GROUP BY p.username;

[User] Now I only want players registered after '2022-01-01'.

[Assistant]
SELECT p.username, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
WHERE p.registration_date > '2022-01-01'
GROUP BY p.username;

[User] Actually, also include their country_code and order the results by total_sessions descending.

[Assistant]
SELECT p.username,
       p.country_code,
       COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
WHERE p.registration_date > '2022-01-01'
GROUP BY p.username, p.country_code
ORDER BY total_sessions DESC;

[User] Finally, only include players who have played more than 10 sessions.

[Assistant]
SELECT p.username,
       p.country_code,
       COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.players p
LEFT JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
WHERE p.registration_date > '2022-01-01'
GROUP BY p.username, p.country_code
HAVING COUNT(gs.session_id) > 10
ORDER BY total_sessions DESC;

[User] Show me each achievement name and the number of players who have unlocked it.

[Assistant]
SELECT a.name,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name;

[User] Now only include achievements with at least 20 unlocks, and display their points as well.

[Assistant]
SELECT a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name, a.points
HAVING COUNT(pa.player_id) >= 20;

[User] Finally, include the game_id for each achievement and sort by unlock_count descending.

[Assistant]
SELECT a.game_id,
       a.name,
       a.points,
       COUNT(pa.player_id) AS unlock_count
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.game_id, a.name, a.points
HAVING COUNT(pa.player_id) >= 20
ORDER BY unlock_count DESC;

[User] List each server's name and region along with the total number of sessions hosted on that server.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region;

[User] Filter out servers with fewer than 50 sessions.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50;

[User] Also include the average duration_seconds of those sessions per server.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50;

[User] And only for servers currently online, sorted by avg_duration descending.

[Assistant]
SELECT s.server_name,
       s.region,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.servers s
LEFT JOIN gaming_technology.game_sessions gs ON s.server_id = gs.server_id
WHERE s.status = 'online'
GROUP BY s.server_name, s.region
HAVING COUNT(gs.session_id) >= 50
ORDER BY avg_duration DESC;

[User] Which achievements have the highest unlock counts? List the top 5 achievement names along with the number of distinct players who unlocked each.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Only exclude hidden achievements from the ranking.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Now include only achievements unlocked by at least 50 players and order by player_count descending.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
HAVING COUNT(DISTINCT pa.player_id) >= 50
ORDER BY player_count DESC;

[User] For each in-game item type, display the item type, total quantity held by players, and the average cost amount of those items.

[Assistant]
SELECT i.item_type,
       COALESCE(SUM(pi.quantity), 0) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
GROUP BY i.item_type;

[User] Now restrict to items with rarity 'Epic'.

[Assistant]
SELECT i.item_type,
       COALESCE(SUM(pi.quantity), 0) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type;

[User] Also exclude any groups where the average cost_amount is less than 100.

[Assistant]
SELECT i.item_type,
       SUM(pi.quantity) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type
HAVING AVG(i.cost_amount) >= 100;

[User] Please order the results by total_quantity descending.

[Assistant]
SELECT i.item_type,
       SUM(pi.quantity) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type
HAVING AVG(i.cost_amount) >= 100
ORDER BY total_quantity DESC;

[User] For each game, show the game title, the total duration of all sessions in seconds, and the average score.

[Assistant] SELECT g.title, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Could you also show the total number of sessions for each game?

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Filter the results to only include games with more than 100 sessions.

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title HAVING COUNT(gs.session_id) > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )

[User] Which projects that raised funds in 2023 have an associated token, and what are their fundraising amounts, token symbols, and token market caps?

[Assistant] SELECT T1.project_name, T1.investment_value, T2.token_symbol, T2.market_cap FROM project_fundraising_record AS T1 LEFT JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE T1.investment_date LIKE '%2023%' AND T2.token_symbol IS NOT NULL

[User] Instead of just 2023, show projects that raised funds in 2022 or 2023.

[Assistant] SELECT T1.project_name, T1.investment_value, T2.token_symbol, T2.market_cap FROM project_fundraising_record AS T1 LEFT JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE (T1.investment_date LIKE '%2022%' OR T1.investment_date LIKE '%2023%') AND T2.token_symbol IS NOT NULL

[User] Also include the fundraising round name and the token's 24-hour volume.

[Assistant] SELECT T1.project_name, T1.rounds_name, T1.investment_value, T2.token_symbol, T2.market_cap, T2.total_volume FROM project_fundraising_record AS T1 LEFT JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE (T1.investment_date LIKE '%2022%' OR T1.investment_date LIKE '%2023%') AND T2.token_symbol IS NOT NULL

[User] Filter the results to only show projects where the token's market cap is above $50,000,000.

[Assistant] SELECT T1.project_name, T1.rounds_name, T1.investment_value, T2.token_symbol, T2.market_cap, T2.total_volume FROM project_fundraising_record AS T1 INNER JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE (T1.investment_date LIKE '%2022%' OR T1.investment_date LIKE '%2023%') AND T2.market_cap > 50000000

[User] Which tokens have a current price above $20 and belong to the 'DeFi' narrative?

[Assistant]
SELECT token_symbol, token_name, chain, price
FROM token_basic_info
WHERE price > 20 AND narrative = 'DeFi';

[User] Add only those with a market cap above $500 million and order by market cap descending.

[Assistant]
SELECT token_symbol, token_name, chain, price, market_cap
FROM token_basic_info
WHERE price > 20
  AND narrative = 'DeFi'
  AND market_cap > 500000000
ORDER BY market_cap DESC;

[User] Show me the average smart money ROI and the total PNL for each narrative category, based on the `smart_money_token_performance` and `token_basic_info` tables.

[Assistant] SELECT tbi.narrative, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol GROUP BY tbi.narrative ORDER BY average_roi DESC;

[User] Filter the results to only include narratives with an average ROI greater than 1 (100%) and a total PNL greater than 0. Order by total PNL descending.

[Assistant] SELECT tbi.narrative, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol GROUP BY tbi.narrative HAVING AVG(smp.roi) > 1 AND SUM(smp.pnl) > 0 ORDER BY total_pnl DESC;

[User] Break down these results by chain as well. Show narrative, chain, average ROI, and total PNL for narratives with average ROI > 1 and total PNL > 0 on each chain.

[Assistant] SELECT tbi.narrative, smp.chain, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol AND smp.chain = tbi.chain GROUP BY tbi.narrative, smp.chain HAVING AVG(smp.roi) > 1 AND SUM(smp.pnl) > 0 ORDER BY total_pnl DESC;

[User] Now, only show results where the total PNL is greater than $50,000 AND the number of unique tokens contributing to this PNL for that narrative and chain is at least 3. Include the count of unique tokens. Order by total PNL descending and limit to the top 10.

[Assistant] SELECT tbi.narrative, smp.chain, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl, COUNT(DISTINCT smp.token_symbol) AS unique_token_count FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol AND smp.chain = tbi.chain GROUP BY tbi.narrative, smp.chain HAVING AVG(smp.roi) > 1 AND SUM(smp.pnl) > 50000 AND COUNT(DISTINCT smp.token_symbol) >= 3 ORDER BY total_pnl DESC LIMIT 10;

[User] List tokens in DEX pools with a 24-hour trading volume greater than $500,000 and a price less than $1. Show their symbol, chain, volume, and price.

[Assistant] SELECT token_symbol, chain, volume_24h, price FROM token_dexpool_info WHERE volume_24h > 500000 AND price < 1

[User] Could you list projects that have completed more than one fundraising round, showing the project name and the number of rounds?

[Assistant] SELECT project_name, COUNT(*) AS round_count FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 ORDER BY round_count DESC;

[User] For these projects with multiple rounds, can you show the earliest and latest investment date and the corresponding investment value for each project?

[Assistant] WITH ProjectRounds AS ( SELECT project_id, project_name, investment_value, investment_date, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date ASC) as rn_earliest, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date DESC) as rn_latest FROM project_fundraising_record ) SELECT pr_earliest.project_name, pr_earliest.investment_date AS earliest_date, pr_earliest.investment_value AS earliest_investment, pr_latest.investment_date AS latest_date, pr_latest.investment_value AS latest_investment FROM ProjectRounds pr_earliest JOIN ProjectRounds pr_latest ON pr_earliest.project_id = pr_latest.project_id WHERE pr_earliest.rn_earliest = 1 AND pr_latest.rn_latest = 1 AND pr_earliest.project_id IN ( SELECT project_id FROM project_fundraising_record GROUP BY project_id HAVING COUNT(*) > 1 ) ORDER BY pr_latest.investment_date DESC;

[User] Now, for those projects that also have a matching token, link the latest investment value to the token's current price and its smart money ROI. Match project name to token symbol or name case-insensitively.

[Assistant] WITH ProjectLatestRound AS ( SELECT project_id, project_name, investment_value, investment_date, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date DESC) as rn FROM project_fundraising_record WHERE project_id IN ( SELECT project_id FROM project_fundraising_record GROUP BY project_id HAVING COUNT(*) > 1 ) ) SELECT plr.project_name, plr.investment_value AS latest_investment, tbi.token_symbol, tbi.price AS current_token_price, smp.roi AS smart_money_roi FROM ProjectLatestRound plr JOIN token_basic_info tbi ON LOWER(tbi.token_symbol) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_symbol) || '%' OR LOWER(tbi.token_name) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_name) || '%' LEFT JOIN smart_money_token_performance smp ON tbi.token_symbol = smp.token_symbol WHERE plr.rn = 1;

[User] Filter the results to only include projects where the latest investment value is greater than $1,000,000 AND the token's smart money ROI is positive (greater than 0). Order the results by smart money ROI descending and show the top 10.

[Assistant] WITH ProjectLatestRound AS ( SELECT project_id, project_name, investment_value, investment_date, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date DESC) as rn FROM project_fundraising_record WHERE project_id IN ( SELECT project_id FROM project_fundraising_record GROUP BY project_id HAVING COUNT(*) > 1 ) ) SELECT plr.project_name, plr.investment_value AS latest_investment, tbi.token_symbol, tbi.price AS current_token_price, smp.roi AS smart_money_roi FROM ProjectLatestRound plr JOIN token_basic_info tbi ON LOWER(tbi.token_symbol) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_symbol) || '%' OR LOWER(tbi.token_name) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_name) || '%' JOIN smart_money_token_performance smp ON tbi.token_symbol = smp.token_symbol WHERE plr.rn = 1 AND plr.investment_value > 1000000 AND smp.roi > 0 ORDER BY smp.roi DESC LIMIT 10;

[User] Which fundraising projects in 2023 have an associated token, and what are their investment amounts, chain, and token narratives?

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023%';

[User] Could you also include the token's symbol and current price in the results?

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative, t.token_symbol, t.price
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023%';

[User] Some matches may be missed. Can you use a more flexible join, such as where the token name contains the project name or vice versa (case-insensitive)?

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative, t.token_symbol, t.price
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
     OR LOWER(p.project_name) LIKE CONCAT('%', LOWER(t.token_name), '%')
     OR LOWER(t.token_name) LIKE CONCAT('%', LOWER(p.project_name), '%')
WHERE p.investment_date LIKE '2023%';

[User] Add a filter to only include projects where the investment amount is greater than $2,000,000, and order by investment_value descending.

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative, t.token_symbol, t.price
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
     OR LOWER(p.project_name) LIKE CONCAT('%', LOWER(t.token_name), '%')
     OR LOWER(t.token_name) LIKE CONCAT('%', LOWER(p.project_name), '%')
WHERE p.investment_date LIKE '2023%'
  AND p.investment_value > 2000000
ORDER BY p.investment_value 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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] Show me all male patients who have received more than one prescription, including their full name, date of birth, and the total number of prescriptions.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Could you also include the names of the medications they've been prescribed?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Actually, I only want to see patients who also have at least one active diagnosis.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(DISTINCT pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] One of the medication_ids columns seems off, could you instead also show the medication_id and dosage for each prescription individually, as well as the diagnosis_code for their active diagnosis?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, pr.prescription_id, pr.medication_id, pr.dosage, d.diagnosis_code
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active';

[User] Show all prescriptions made in 2024 for medications prescribed during appointments scheduled at location 'LOC001', including prescription_id, patient_id, medication_id, and appointment_time.

[Assistant]
SELECT pr.prescription_id, pr.patient_id, pr.medication_id, ap.appointment_time
FROM healthcare.prescriptions pr
JOIN healthcare.medical_records mr ON pr.record_id = mr.record_id
JOIN healthcare.appointments ap ON mr.appointment_id = ap.appointment_id
WHERE ap.location_id = 'LOC001'
  AND EXTRACT(YEAR FROM pr.prescription_date) = 2024;

[User] List the contact phone and website for all insurance plans provided by 'Continental Health'.

[Assistant]
SELECT plan_name, contact_phone, website
FROM healthcare.insurance_plans
WHERE insurance_provider = 'Continental Health';

[User] List all medical record IDs and the record date for records created by doctors specializing in 'Gastroenterology'.

[Assistant] SELECT mr.record_id, mr.record_date FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id WHERE d.specialty = 'Gastroenterology';

[User] Could you also include the patient's first and last name for these records?

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology';

[User] Now, only show records for male patients.

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male';

[User] Additionally, restrict the results to medical records that have at least one associated diagnosis with status 'Resolved'.

[Assistant] SELECT DISTINCT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id JOIN healthcare.diagnoses diag ON mr.record_id = diag.record_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male' AND diag.status = 'Resolved';

[User] What is the average number of refills allowed across all prescriptions?

[Assistant] SELECT AVG(refills_allowed) FROM healthcare.prescriptions;

[User] List each chronic active diagnosis along with the prescribed medication details, showing diagnosis_id, diagnosis_code, medication_id, dosage, and diagnosis_date.

[Assistant] SELECT d.diagnosis_id, d.diagnosis_code, p.medication_id, p.dosage, d.diagnosis_date FROM healthcare.diagnoses d JOIN healthcare.prescriptions p ON d.record_id = p.record_id AND d.patient_id = p.patient_id WHERE d.is_chronic = TRUE AND d.status = 'Active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)

[User] How many users have verified profiles and private profiles enabled?

[Assistant]
SELECT COUNT(*)
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE u.is_verified = true AND s.private_profile = true;

[User] Can you show me the usernames instead of just the count?

[Assistant]
SELECT u.username
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE u.is_verified = true AND s.private_profile = true;

[User] Only show those users who have push notifications enabled as well.

[Assistant]
SELECT u.username
FROM social_media.users u
JOIN social_media.user_settings s ON u.user_id = s.user_id
WHERE u.is_verified = true AND s.private_profile = true AND s.push_notifications_enabled = true;

[User] List the usernames and user IDs of all users whose bio contains the word 'developer'.

[Assistant]
SELECT user_id, username
FROM social_media.users
WHERE bio ILIKE '%developer%';

[User] List all usernames and their respective group chat names where they are participants.

[Assistant]
SELECT u.username, c.group_name
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = true;

[User] I also want to see the group chat creation time. Can you include that?

[Assistant]
SELECT u.username, c.group_name, c.created_at
FROM social_media.conversation_participants cp
JOIN social_media.users u ON cp.user_id = u.user_id
JOIN social_media.conversations c ON cp.conversation_id = c.conversation_id
WHERE c.is_group_chat = true;

[User] Show all users who have liked comments made by users with a specified location, say 'Paris'. For each, show their username, the comment_id, and the location of the comment's author.

[Assistant]
SELECT l.user_id AS liker_user_id, u_liker.username, l.comment_id, u_author.location AS comment_author_location
FROM social_media.likes l
JOIN social_media.comments c ON l.comment_id = c.comment_id
JOIN social_media.users u_author ON c.user_id = u_author.user_id
JOIN social_media.users u_liker ON l.user_id = u_liker.user_id
WHERE u_author.location = 'Paris';

[User] Actually, please also include the full name of the user who made the comment, and restrict to likes created after April 1, 2024.

[Assistant]
SELECT l.user_id AS liker_user_id, u_liker.username, l.comment_id, u_author.location AS comment_author_location, u_author.full_name AS comment_author_full_name
FROM social_media.likes l
JOIN social_media.comments c ON l.comment_id = c.comment_id
JOIN social_media.users u_author ON c.user_id = u_author.user_id
JOIN social_media.users u_liker ON l.user_id = u_liker.user_id
WHERE u_author.location = 'Paris' AND l.created_at >= '2024-04-01';

[User] I see duplicate users for the same comment. Show only unique username-comment_id pairs, and order the results by liker username ascending.

[Assistant]
SELECT DISTINCT u_liker.username, l.comment_id, u_author.location AS comment_author_location, u_author.full_name AS comment_author_full_name
FROM social_media.likes l
JOIN social_media.comments c ON l.comment_id = c.comment_id
JOIN social_media.users u_author ON c.user_id = u_author.user_id
JOIN social_media.users u_liker ON l.user_id = u_liker.user_id
WHERE u_author.location = 'Paris' AND l.created_at >= '2024-04-01'
ORDER BY u_liker.username ASC;

[User] For each hashtag, show its tag name and the number of unique users who have ever commented on posts associated with that hashtag.

[Assistant]
SELECT h.tag_name, COUNT(DISTINCT c.user_id) AS unique_commenters
FROM social_media.hashtags h
JOIN social_media.post_hashtags ph ON h.hashtag_id = ph.hashtag_id
JOIN social_media.comments c ON ph.post_id = c.post_id
GROUP BY h.hashtag_id, h.tag_name;

[User] Only show hashtags that have more than 10 unique commenters, and order them by the number of unique commenters descending.

[Assistant]
SELECT h.tag_name, COUNT(DISTINCT c.user_id) AS unique_commenters
FROM social_media.hashtags h
JOIN social_media.post_hashtags ph ON h.hashtag_id = ph.hashtag_id
JOIN social_media.comments c ON ph.post_id = c.post_id
GROUP BY h.hashtag_id, h.tag_name
HAVING COUNT(DISTINCT c.user_id) > 10
ORDER BY unique_commenters DESC;