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

[User] List the full names of citizens who have made payments for services that are currently inactive. Also show the service name and payment amount.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, s.service_name, p.amount
FROM government_services.payments p
JOIN government_services.citizens c ON p.citizen_id = c.citizen_id
JOIN government_services.services s ON p.service_id = s.service_id
WHERE s.is_active = FALSE;

[User] List the appointment IDs and statuses for all appointments scheduled at locations in the city of 'San Francisco'.

[Assistant]
SELECT a.appointment_id, a.status
FROM government_services.appointments a
JOIN government_services.service_locations l ON a.location_id = l.location_id
WHERE l.city = 'San Francisco';

[User] List the citizen ID, full name, and registration date for all unverified citizens who registered in the year 2022.

[Assistant] SELECT citizen_id, first_name, last_name, registration_date FROM government_services.citizens WHERE is_verified = FALSE AND EXTRACT(YEAR FROM registration_date) = 2022;

[User] Show me the names of all employees along with the names of the agencies they work for, and the number of appointments each employee has scheduled.

[Assistant]
SELECT e.first_name, e.last_name, a.agency_name, COUNT(appt.appointment_id) AS appointment_count
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
LEFT JOIN government_services.appointments appt ON e.employee_id = appt.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name, a.agency_name;

[User] Can you only show employees who have scheduled more than 5 appointments?

[Assistant]
SELECT e.first_name, e.last_name, a.agency_name, COUNT(appt.appointment_id) AS appointment_count
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
LEFT JOIN government_services.appointments appt ON e.employee_id = appt.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name, a.agency_name
HAVING COUNT(appt.appointment_id) > 5;

[User] Show the full name (first and last name) of employees who are assigned to applications with a status of 'Completed'.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.employees AS T1 INNER JOIN government_services.applications AS T2 ON T1.employee_id = T2.assigned_employee_id WHERE T2.status = 'Completed';

[User] List the agency names and the total amount received from payments with the status 'Pending'.

[Assistant]
SELECT ag.agency_name, SUM(p.amount) AS total_pending_payments
FROM government_services.payments p
JOIN government_services.services s ON p.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_id
WHERE p.status = 'Pending'
GROUP BY ag.agency_name;

[User] Show the full names and contact emails of all citizens who have made payments for applications assigned to employees with the job title 'Supervisor'.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
WHERE e.job_title = 'Supervisor';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Show the document ID, claim ID, and file name for all documents with a MIME type starting with 'image/'.

[Assistant] SELECT document_id, claim_id, file_name FROM insurance.claim_documents WHERE mime_type LIKE 'image/%';

[User] Can you also include the uploaded_by user and only show documents uploaded after January 1, 2023?

[Assistant] SELECT document_id, claim_id, file_name, uploaded_by FROM insurance.claim_documents WHERE mime_type LIKE 'image/%' AND uploaded_at >= '2023-01-01';

[User] List all claim IDs that have both an 'Accident Report' and a 'Damage Assessment' document type.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE document_type IN ('Accident Report', 'Damage Assessment')
GROUP BY claim_id
HAVING COUNT(DISTINCT document_type) = 2;

[User] This returns claim IDs even if they have only multiple 'Accident Report' entries and no 'Damage Assessment'. I want to ensure each claim_id has at least one of each type.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0;

[User] Also, only include documents uploaded after '2024-01-01'.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE uploaded_at > '2024-01-01'
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0;

[User] Finally, sort the result by claim_id in ascending order.

[Assistant]
SELECT claim_id
FROM insurance.claim_documents
WHERE uploaded_at > '2024-01-01'
GROUP BY claim_id
HAVING SUM(CASE WHEN document_type = 'Accident Report' THEN 1 ELSE 0 END) > 0
   AND SUM(CASE WHEN document_type = 'Damage Assessment' THEN 1 ELSE 0 END) > 0
ORDER BY claim_id ASC;

[User] How many documents exist for each document_type? Return document_type and the count.

[Assistant]
SELECT document_type,
       COUNT(*) AS document_count
FROM insurance.claim_documents
GROUP BY document_type;

[User] Show me all documents uploaded in 2024 that do not have a description.

[Assistant]
SELECT document_id, file_name, uploaded_at
FROM insurance.claim_documents
WHERE uploaded_at >= '2024-01-01'
  AND uploaded_at < '2025-01-01'
  AND (description IS NULL OR description = '');

[User] Find the claim ID and the total number of documents associated with each claim ID that has more than 10 documents.

[Assistant] SELECT claim_id, COUNT(*) FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(*) > 10;

[User] Which document types have been used for more than 100 documents, and what is the total file size across all documents of each such type?

[Assistant]
SELECT document_type, COUNT(*) AS document_count, SUM(file_size_bytes) AS total_file_size_bytes
FROM insurance.claim_documents
GROUP BY document_type
HAVING COUNT(*) > 100;

[User] For each claim, retrieve the earliest uploaded document and the latest uploaded document filenames. Return claim_id, earliest_file_name, latest_file_name.

[Assistant]
SELECT e.claim_id,
       e.file_name AS earliest_file_name,
       l.file_name AS latest_file_name
FROM insurance.claim_documents e
JOIN insurance.claim_documents l
  ON e.claim_id = l.claim_id
WHERE e.uploaded_at = (
        SELECT MIN(uploaded_at)
        FROM insurance.claim_documents
        WHERE claim_id = e.claim_id
      )
  AND l.uploaded_at = (
        SELECT MAX(uploaded_at)
        FROM insurance.claim_documents
        WHERE claim_id = l.claim_id
      );


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

[User] How many insurance policies does each subscriber have? Please display the subscriber name and policy count.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name;

[User] Please include only subscribers who have more than one policy.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name HAVING COUNT(*) > 1;

[User] List patient insurance details, including patient ID, policy number, and subscriber name, along with the corresponding plan name for each entry.

[Assistant] SELECT T1.patient_id, T1.policy_number, T1.subscriber_name, T2.plan_name FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id

[User] Modify the query to only include entries where the insurance plan type is 'PPO'.

[Assistant] SELECT T1.patient_id, T1.policy_number, T1.subscriber_name, T2.plan_name FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'PPO'

[User] Further filter the results to show only policies marked as primary (is_primary = true) and sort the output by subscriber name in ascending order.

[Assistant] SELECT T1.patient_id, T1.policy_number, T1.subscriber_name, T2.plan_name FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'PPO' AND T1.is_primary = true ORDER BY T1.subscriber_name ASC

[User] Show me a list of all insurance policies along with the subscriber's name and the effective and expiration dates for each policy, including the associated plan ID.

[Assistant] SELECT policy_number, subscriber_name, effective_date, expiration_date, plan_id FROM healthcare.patient_insurance;

[User] Now, I only want to see policies that are primary and do not have a group number assigned. Please also include the patient_id.

[Assistant] SELECT policy_number, subscriber_name, effective_date, expiration_date, plan_id, patient_id FROM healthcare.patient_insurance WHERE is_primary = TRUE AND group_number IS NULL;

[User] Actually, please filter further to only show policies that expire after 2024-12-31.

[Assistant] SELECT policy_number, subscriber_name, effective_date, expiration_date, plan_id, patient_id FROM healthcare.patient_insurance WHERE is_primary = TRUE AND group_number IS NULL AND expiration_date > '2024-12-31';

[User] I need a list showing each patient along with their current primary insurance policy number and their immediately previous primary policy number.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.effective_date < ci.effective_date
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE)
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.effective_date < ci.effective_date
  );

[User] Actually, I only want to include previous policies that have an expiration_date set.

[Assistant]
SELECT ci.patient_id,
       ci.policy_number AS current_policy,
       pi.policy_number AS previous_policy
FROM healthcare.patient_insurance ci
LEFT JOIN healthcare.patient_insurance pi
  ON ci.patient_id = pi.patient_id
  AND pi.is_primary = TRUE
  AND pi.expiration_date IS NOT NULL
  AND pi.effective_date = (
      SELECT MAX(pii.effective_date)
      FROM healthcare.patient_insurance pii
      WHERE pii.patient_id = ci.patient_id
        AND pii.is_primary = TRUE
        AND pii.expiration_date IS NOT NULL
        AND pii.effective_date < ci.effective_date
  )
WHERE ci.is_primary = TRUE
  AND (ci.expiration_date IS NULL OR ci.expiration_date > CURRENT_DATE);

[User] For each subscriber, count the number of insurance plans they have where the plan type is 'HMO'. Show the subscriber name and their count.

[Assistant] SELECT T1.subscriber_name, COUNT(T2.plan_id) FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'HMO' GROUP BY T1.subscriber_name

[User] Filter the list from the previous query to include only subscribers who are associated with more than 3 'HMO' plans.

[Assistant] SELECT T1.subscriber_name, COUNT(T2.plan_id) FROM healthcare.patient_insurance AS T1 JOIN healthcare.insurance_plan AS T2 ON T1.plan_id = T2.plan_id WHERE T2.plan_type = 'HMO' GROUP BY T1.subscriber_name HAVING COUNT(T2.plan_id) > 3

[User] How many active insurance policies are there for each plan_id? Show plan_id and active_count.

[Assistant]
SELECT plan_id,
       COUNT(*) AS active_count
FROM healthcare.patient_insurance
WHERE expiration_date IS NULL OR expiration_date > CURRENT_DATE
GROUP BY plan_id;

[User] List the patient_id and policy_number for all policies belonging to patients who have more than one insurance policy record in the system.

[Assistant] SELECT DISTINCT T1.patient_id, T1.policy_number FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id WHERE T1.patient_insurance_id <> T2.patient_insurance_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

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

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

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

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

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

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

[User] Count the total number of hashtags.

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

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

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

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

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

[User] List all hashtags created in March 2024 along with their creation timestamps.

[Assistant]
SELECT hashtag_id, tag_name, created_at
FROM social_media.hashtags
WHERE created_at BETWEEN '2024-03-01 00:00:00' AND '2024-03-31 23:59:59';

[User] List all hashtag names and their creation dates.

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

[User] Please only include hashtags created in the year 2023.

[Assistant] SELECT tag_name, created_at FROM social_media.hashtags WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01';

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

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

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

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

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

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


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.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )

[User] List all trades for asset 'BTC' where the trade quantity is greater than 5.

[Assistant] SELECT trade_id, order_id, buyer_id, seller_id, quantity, price, traded_at FROM trading_platform.trades WHERE asset_id = 'BTC' AND quantity > 5;

[User] Calculate the total quantity traded for each day in the dataset.

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Could you also include the total trade value (quantity * price) for each day in that report?

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity, SUM(quantity * price) AS total_daily_value FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Now, for each day, show how the total quantity compares to the overall average daily quantity across all days in the dataset.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity, total_daily_quantity - AVG(total_daily_quantity) OVER () AS quantity_difference_from_average FROM DailySummary ORDER BY trade_day;

[User] Finally, only show the days where the total quantity was higher than the overall average daily quantity.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity FROM DailySummary WHERE total_daily_quantity > (SELECT AVG(total_daily_quantity) FROM DailySummary) ORDER BY trade_day;

[User] List all trades that occurred on July 10, 2024, showing the trade ID, asset symbol, quantity, and trade price.

[Assistant]
SELECT t.trade_id, a.symbol AS asset_symbol, t.quantity, t.price
FROM trading_platform.trades t
JOIN trading_platform.assets a ON t.asset_id = a.asset_id
WHERE DATE(t.traded_at) = '2024-07-10';

[User] For each asset, show the asset name, symbol, and the latest trade price.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, (
    SELECT t1.price FROM trading_platform.trades t1
    WHERE t1.asset_id = a.asset_id
    ORDER BY t1.traded_at DESC
    LIMIT 1
) AS latest_trade_price
FROM trading_platform.assets a;

[User] Actually, add the traded_at timestamp of the latest trade as well.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, latest_trade.price AS latest_trade_price, latest_trade.traded_at AS latest_traded_at
FROM trading_platform.assets a
LEFT JOIN LATERAL (
    SELECT t.price, t.traded_at
    FROM trading_platform.trades t
    WHERE t.asset_id = a.asset_id
    ORDER BY t.traded_at DESC
    LIMIT 1
) latest_trade ON true;

[User] Can you filter to only show assets with at least one trade after July 1, 2024?

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, latest_trade.price AS latest_trade_price, latest_trade.traded_at AS latest_traded_at
FROM trading_platform.assets a
JOIN LATERAL (
    SELECT t.price, t.traded_at
    FROM trading_platform.trades t
    WHERE t.asset_id = a.asset_id AND t.traded_at > '2024-07-01'
    ORDER BY t.traded_at DESC
    LIMIT 1
) latest_trade ON true;

[User] The query returns no rows for some assets because they have no trades after July 1. Please include all assets, showing NULL for the trade details if there are none since that date.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, latest_trade.price AS latest_trade_price, latest_trade.traded_at AS latest_traded_at
FROM trading_platform.assets a
LEFT JOIN LATERAL (
    SELECT t.price, t.traded_at
    FROM trading_platform.trades t
    WHERE t.asset_id = a.asset_id AND t.traded_at > '2024-07-01'
    ORDER BY t.traded_at DESC
    LIMIT 1
) latest_trade ON true;

[User] List all orders that are currently pending and were created more than 24 hours ago.

[Assistant] SELECT * FROM trading_platform.orders WHERE status = 'pending' AND created_at < CURRENT_TIMESTAMP - INTERVAL '24 hours';

[User] Now show me the count of such orders grouped by order_type.

[Assistant] SELECT order_type, COUNT(order_id) AS order_count FROM trading_platform.orders WHERE status = 'pending' AND created_at < CURRENT_TIMESTAMP - INTERVAL '24 hours' GROUP BY order_type;

[User] Can you modify the query to also include the total quantity for each order type?

[Assistant] SELECT order_type, COUNT(order_id) AS order_count, SUM(quantity) AS total_quantity FROM trading_platform.orders WHERE status = 'pending' AND created_at < CURRENT_TIMESTAMP - INTERVAL '24 hours' GROUP BY order_type;

[User] I want a summary for each user showing their total buy value and total sell value across all trades.

[Assistant]
SELECT
  COALESCE(b.user_id, s.user_id) AS user_id,
  COALESCE(b.total_buy, 0) AS total_buy_value,
  COALESCE(s.total_sell, 0) AS total_sell_value
FROM
  (
    SELECT buyer_id AS user_id, SUM(quantity * price) AS total_buy
    FROM trading_platform.trades
    GROUP BY buyer_id
  ) b
FULL OUTER JOIN
  (
    SELECT seller_id AS user_id, SUM(quantity * price) AS total_sell
    FROM trading_platform.trades
    GROUP BY seller_id
  ) s
ON b.user_id = s.user_id;

[User] Actually, I only care about users who have both bought and sold assets.

[Assistant]
SELECT
  b.user_id,
  b.total_buy AS total_buy_value,
  s.total_sell AS total_sell_value
FROM
  (
    SELECT buyer_id AS user_id, SUM(quantity * price) AS total_buy
    FROM trading_platform.trades
    GROUP BY buyer_id
  ) b
INNER JOIN
  (
    SELECT seller_id AS user_id, SUM(quantity * price) AS total_sell
    FROM trading_platform.trades
    GROUP BY seller_id
  ) s
ON b.user_id = s.user_id;

[User] What is the average trade price for each asset for trades executed between '2024-05-01' and '2024-05-31'?

[Assistant]
SELECT
  asset_id,
  AVG(price) AS avg_price
FROM trading_platform.trades
WHERE traded_at >= '2024-05-01' AND traded_at < '2024-06-01'
GROUP BY asset_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] Could you provide the booking ID, route number, and fare for all bookings?

[Assistant] SELECT T1.booking_id, T2.route_number, T1.fare FROM transportation.bookings AS T1 JOIN transportation.routes AS T2 ON T1.trip_id = T2.route_id;

[User] Now, filter the results to only include bookings with a fare greater than 100 and sort them by fare in descending order.

[Assistant] SELECT T1.booking_id, T2.route_number, T1.fare FROM transportation.bookings AS T1 JOIN transportation.routes AS T2 ON T1.trip_id = T2.route_id WHERE T1.fare > 100 ORDER BY T1.fare DESC;

[User] Show the route number and description for routes that have bookings associated with them.

[Assistant] SELECT DISTINCT T1.route_number, T1.description FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id;

[User] For these routes, what is the average fare of the associated bookings?

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number;

[User] Also, only include routes where the average fare is greater than 75.

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number HAVING AVG(T2.fare) > 75;

[User] What is the average fare for bookings with status 'Completed'?

[Assistant] SELECT AVG(fare) FROM transportation.bookings WHERE status = 'Completed';

[User] What about the average fare for 'Cancelled' bookings?

[Assistant] SELECT AVG(fare) FROM transportation.bookings WHERE status = 'Cancelled';

[User] Show the booking ID and seat number for all bookings that have a fare equal to 50.

[Assistant]
SELECT booking_id, seat_number
FROM transportation.bookings
WHERE fare = 50;

[User] Also include the booking status and order the results by booking time ascending.

[Assistant]
SELECT booking_id, seat_number, status
FROM transportation.bookings
WHERE fare = 50
ORDER BY booking_time ASC;

[User] Find all bookings for which the special_requests field is not null. Show the booking ID, passenger ID, and the special request.

[Assistant]
SELECT booking_id, passenger_id, special_requests
FROM transportation.bookings
WHERE special_requests IS NOT NULL;

[User] Could you also show the associated route number and the city of the origin location for these bookings?

[Assistant]
SELECT b.booking_id, b.passenger_id, b.special_requests, r.route_number, l.city AS origin_city
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id
JOIN transportation.locations l ON r.origin_location_id = l.location_id
WHERE b.special_requests IS NOT NULL;

[User] Only show bookings where the special_requests field contains the word 'wheelchair'.

[Assistant]
SELECT b.booking_id, b.passenger_id, b.special_requests, r.route_number, l.city AS origin_city
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id
JOIN transportation.locations l ON r.origin_location_id = l.location_id
WHERE b.special_requests ILIKE '%wheelchair%';

[User] List the route number, origin city, and destination city for all routes that have bookings associated with them.

[Assistant]
SELECT DISTINCT r.route_number, l_origin.city AS origin_city, l_dest.city AS destination_city
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id
JOIN transportation.locations l_origin ON r.origin_location_id = l_origin.location_id
JOIN transportation.locations l_dest ON r.destination_location_id = l_dest.location_id;

[User] Now, only show routes where the origin and destination cities are different.

[Assistant]
SELECT DISTINCT r.route_number, l_origin.city AS origin_city, l_dest.city AS destination_city
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id
JOIN transportation.locations l_origin ON r.origin_location_id = l_origin.location_id
JOIN transportation.locations l_dest ON r.destination_location_id = l_dest.location_id
WHERE l_origin.city <> l_dest.city;

[User] List the booking ID, trip ID, and the booking status for all bookings.

[Assistant] SELECT booking_id, trip_id, status FROM transportation.bookings;

[User] For these bookings, please also include the scheduled departure time of the corresponding trip.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id;

[User] Only show bookings for trips with more than 50 passengers.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id WHERE T.passenger_count > 50;

[User] Order the results by scheduled departure time in descending order.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id WHERE T.passenger_count > 50 ORDER BY T.scheduled_departure 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 web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)

[User] Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values.

[Assistant]
SELECT recv.transfer_id AS receive_transfer_id,
       send.transfer_id AS send_transfer_id,
       recv.to_address AS address,
       recv.value       AS received_value,
       send.value       AS sent_value
FROM web3.token_transfers recv
JOIN web3.token_transfers send
  ON recv.to_address = send.from_address;

[User] Find pairs of distinct token transfers that occurred in the same transaction and were initiated by the same sender address. List the transaction ID, the common sender address, and both transfer IDs.

[Assistant]
SELECT
  t1.transaction_id,
  t1.from_address,
  t1.transfer_id AS transfer_id_1,
  t2.transfer_id AS transfer_id_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.from_address = t2.from_address
WHERE
  t1.transfer_id < t2.transfer_id;

[User] For each sender address, count how many distinct tokens they have transferred. Show from_address and token_count.

[Assistant]
SELECT from_address, COUNT(DISTINCT token_id) AS token_count
FROM web3.token_transfers
GROUP BY from_address;

[User] Now filter to only include senders who have transferred more than 5 distinct tokens.

[Assistant]
SELECT from_address, COUNT(DISTINCT token_id) AS token_count
FROM web3.token_transfers
GROUP BY from_address
HAVING COUNT(DISTINCT token_id) > 5;

[User] For each token, show the token_id and the total number of unique addresses that have ever received it.

[Assistant]
SELECT token_id, COUNT(DISTINCT to_address) AS unique_recipients
FROM web3.token_transfers
GROUP BY token_id;

[User] List all token transfers between two distinct addresses, showing transfer_id, from_address, to_address, value, and transaction_id.

[Assistant]
SELECT transfer_id, from_address, to_address, value, transaction_id
FROM web3.token_transfers
WHERE from_address <> to_address;

[User] Actually, I only want to see transfers where the value transferred is greater than 1000 tokens.

[Assistant]
SELECT transfer_id, from_address, to_address, value, transaction_id
FROM web3.token_transfers
WHERE from_address <> to_address AND value > 1000;

[User] List all token transfers with a value greater than 1000000. Show transfer ID, token ID, from address, to address, and value.

[Assistant]
SELECT
  transfer_id,
  token_id,
  from_address,
  to_address,
  value
FROM web3.token_transfers
WHERE
  value > 1000000;

[User] Now, only show transfers for token ID '0xabc...xyz'.

[Assistant]
SELECT
  transfer_id,
  token_id,
  from_address,
  to_address,
  value
FROM web3.token_transfers
WHERE
  value > 1000000
  AND token_id = '0xabc...xyz';

[User] Find pairs of token transfers within the same transaction and for the same token, where the value of one transfer is exactly twice the value of the other. Show the transaction ID, token ID, and both transfer IDs and their values.

[Assistant]
SELECT
  t1.transaction_id,
  t1.token_id,
  t1.transfer_id AS transfer_id_1,
  t1.value AS value_1,
  t2.transfer_id AS transfer_id_2,
  t2.value AS value_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.token_id = t2.token_id
  AND t1.transfer_id < t2.transfer_id
WHERE
  t1.value = 2 * t2.value
  OR t2.value = 2 * t1.value;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )

[User] Show me the number of guests registered in each city. Order the results by city name.

[Assistant] SELECT city, COUNT(guest_id) AS guest_count FROM guests GROUP BY city ORDER BY city;

[User] Find all guests who live in the same city and list each guest's name along with the name of another guest in that city.

[Assistant]
SELECT g1.first_name || ' ' || g1.last_name AS guest_name,
       g2.first_name || ' ' || g2.last_name AS other_guest_name,
       g1.city
FROM guests g1
JOIN guests g2
  ON g1.city = g2.city
 AND g1.guest_id <> g2.guest_id;

[User] Now restrict to only cities with more than two guests and order by city ascending.

[Assistant]
SELECT pairs.city,
       pairs.guest_name,
       pairs.other_guest_name
FROM (
  SELECT g1.first_name || ' ' || g1.last_name AS guest_name,
         g2.first_name || ' ' || g2.last_name AS other_guest_name,
         g1.city
  FROM guests g1
  JOIN guests g2
    ON g1.city = g2.city
   AND g1.guest_id <> g2.guest_id
) AS pairs
JOIN (
  SELECT city
  FROM guests
  GROUP BY city
  HAVING COUNT(*) > 2
) AS multi
  ON pairs.city = multi.city
ORDER BY pairs.city ASC;

[User] Find pairs of guests living in the same city, returning each pair’s full names and the city.

[Assistant]
SELECT g1.first_name || ' ' || g1.last_name AS guest1,
       g2.first_name || ' ' || g2.last_name AS guest2,
       g1.city
FROM hospitality_technology.guests g1
JOIN hospitality_technology.guests g2
  ON g1.city = g2.city
 AND g1.guest_id < g2.guest_id;

[User] List all guests who have communication consent enabled along with their email addresses.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email
FROM guests
WHERE communication_consent = TRUE;

[User] Now only include those guests who also have a loyalty_member_id.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email,
       loyalty_member_id
FROM guests
WHERE communication_consent = TRUE
  AND loyalty_member_id IS NOT NULL;

[User] Show me all guests from 'CA' along with their full name and email address.

[Assistant] SELECT guest_id, CONCAT(first_name, ' ', last_name) AS full_name, email FROM hospitality_technology.guests WHERE country_code = 'CA';

[User] List all guests who have provided a phone number, showing their guest ID and phone number.

[Assistant] SELECT guest_id, phone_number FROM hospitality_technology.guests WHERE phone_number IS NOT NULL AND phone_number <> '';

[User] Can you also include their email addresses in the result?

[Assistant] SELECT guest_id, phone_number, email FROM hospitality_technology.guests WHERE phone_number IS NOT NULL AND phone_number <> '';

[User] Show me the list of guests who were created in 2024, along with their first and last names and registration date.

[Assistant] SELECT guest_id, first_name, last_name, created_at FROM hospitality_technology.guests WHERE EXTRACT(YEAR FROM created_at) = 2024;

[User] Please filter this list to include only those who have a loyalty member ID.

[Assistant] SELECT guest_id, first_name, last_name, created_at FROM hospitality_technology.guests WHERE EXTRACT(YEAR FROM created_at) = 2024 AND loyalty_member_id IS NOT NULL AND loyalty_member_id <> '';

[User] Also show their email and date of birth.

[Assistant] SELECT guest_id, first_name, last_name, email, date_of_birth, created_at FROM hospitality_technology.guests WHERE EXTRACT(YEAR FROM created_at) = 2024 AND loyalty_member_id IS NOT NULL AND loyalty_member_id <> '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool 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_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )

[User] Show me all tokens which have a 6-hour price change percentage above 2% and the current price, on the Arbitrum chain.

[Assistant]
SELECT token_symbol, price, price_change_percentage_6h
FROM token_dexpool_info
WHERE chain = 'Arbitrum'
  AND price_change_percentage_6h > 2;

[User] Show tokens held by CEX addresses that have a positive ROI from smart money. Display the token symbol, chain, the exchange holding it, the CEX USD value of the holding, and the smart money ROI. Limit the results to the top 10 tokens ranked by smart money ROI in descending order.

[Assistant] SELECT c.token_symbol, c.chain, c.exchange, c.usd_value, s.roi FROM cex_token_balance c JOIN smart_money_token_performance s ON c.token_address = s.token_address AND c.chain = s.chain WHERE s.roi > 0 ORDER BY s.roi DESC LIMIT 10;

[User] Modify the query to also include the token's narrative and its current price from the basic info table.

[Assistant] SELECT c.token_symbol, c.chain, c.exchange, c.usd_value, s.roi, b.narrative, b.price FROM cex_token_balance c JOIN smart_money_token_performance s ON c.token_address = s.token_address AND c.chain = s.chain JOIN token_basic_info b ON c.token_address = b.token_address AND c.chain = b.chain WHERE s.roi > 0 ORDER BY s.roi DESC LIMIT 10;

[User] For each chain, which token has the lowest average cost as reported by smart money, and what is its current price and ROI?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Now, I only want to see tokens where the ROI is above 0.5.

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Can you also return the token narrative from the token_basic_info table for each result?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi, tbi.narrative
FROM smart_money_token_performance smtp
JOIN token_basic_info tbi ON smtp.token_symbol = tbi.token_symbol AND smtp.chain = tbi.chain
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi, tbi.narrative;

[User] What is the total USD value of tokens held by 'Binance' on the 'BSC' chain according to the latest snapshot?

[Assistant] SELECT SUM(usd_value) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] Also, show the number of distinct token symbols held by Binance on BSC in that same snapshot.

[Assistant] SELECT SUM(usd_value), COUNT(DISTINCT token_symbol) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] List tokens on the 'Arbitrum' chain with a 24-hour price change percentage greater than 10% and a market cap above 1,000,000 USD. Show their symbol, name, price, 24-hour change percentage, and market cap. Order the results by the 24-hour change percentage in descending order.

[Assistant] SELECT token_symbol, token_name, price, price_change_percentage_24h, market_cap FROM token_basic_info WHERE chain = 'Arbitrum' AND price_change_percentage_24h > 10 AND market_cap > 1000000 ORDER BY price_change_percentage_24h DESC;

[User] Show me the top 3 narratives by trend rank, along with their top 3 tokens and 7-day price change percentage.

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d FROM narrative_info n ORDER BY n.trend_rank ASC LIMIT 3;

[User] Can you also include the 24-hour trading volume for these narratives?

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n ORDER BY n.trend_rank ASC LIMIT 3;

[User] Actually, I only want narratives with a 7-day price change percentage above 10%.

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n WHERE n.price_change_percentage_7d > 10 ORDER BY n.trend_rank ASC LIMIT 3;

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

[Assistant] SELECT n.narrative, n.top_3_coins, n.price_change_percentage_7d, n.volume_24h FROM narrative_info n WHERE n.price_change_percentage_7d > 10 ORDER BY n.volume_24h DESC LIMIT 3;

[User] Find tokens that are currently trending (trend rank 10 or lower) and have a positive net flow from smart money addresses. Show their token symbol, chain, trend rank, and smart money net flow. Order the results by trend rank ascending.

[Assistant] SELECT b.token_symbol, b.chain, b.trend_rank, s.net_flow FROM token_basic_info b JOIN smart_money_token_performance s ON b.token_address = s.token_address AND b.chain = s.chain WHERE b.trend_rank IS NOT NULL AND b.trend_rank <= 10 AND s.net_flow > 0 ORDER BY b.trend_rank ASC;

[User] Filter these results to only include tokens where the smart money realized ratio is greater than 0.5. Also, include the token's narrative in the output.

[Assistant] SELECT b.token_symbol, b.chain, b.trend_rank, s.net_flow, s.realized_ratio, b.narrative FROM token_basic_info b JOIN smart_money_token_performance s ON b.token_address = s.token_address AND b.chain = s.chain WHERE b.trend_rank IS NOT NULL AND b.trend_rank <= 10 AND s.net_flow > 0 AND s.realized_ratio > 0.5 ORDER BY b.trend_rank ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )

[User] Show a count of drivers per status.

[Assistant]
SELECT status, COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

[User] Can you also list the earliest hire date for each status?

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status;

[User] I only want to see statuses with more than 5 drivers.

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 5;

[User] Please sort the output by driver_count in descending order.

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 5
ORDER BY driver_count DESC;

[User] Calculate the total number of drivers for each status.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

[User] Now only include statuses with more than 10 drivers.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 10;

[User] List all drivers whose licenses are set to expire within the next 60 days, along with their full name, license number, and contact number.

[Assistant]
SELECT driver_id, first_name, last_name, license_number, contact_number
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] For each driver, show their driver_id, first_name, last_name, along with any other driver whose license_expiry_date is earlier than theirs.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date;

[User] Exclude pairs where the two expiry dates are not in the same calendar year.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date);

[User] Also only include pairs where the difference between their expiry dates is more than 30 days.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date,
       DATE_PART('day', d1.license_expiry_date - d2.license_expiry_date) AS days_difference
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
WHERE d1.license_expiry_date - d2.license_expiry_date > INTERVAL '30 days';

[User] List pairs of drivers whose license expiry dates fall within 30 days of each other. Show both driver_ids, names, and the two expiry dates.

[Assistant] SELECT d1.driver_id AS driver1_id, d1.first_name AS driver1_first, d1.last_name AS driver1_last, d1.license_expiry_date AS expiry1, d2.driver_id AS driver2_id, d2.first_name AS driver2_first, d2.last_name AS driver2_last, d2.license_expiry_date AS expiry2 FROM transportation.drivers d1 JOIN transportation.drivers d2 ON d1.driver_id < d2.driver_id AND ABS((d1.license_expiry_date - d2.license_expiry_date)) <= INTERVAL '30 days';

[User] Which drivers have licenses expiring before 2025-01-01, and what are their first and last names along with the license expiry date?

[Assistant] SELECT driver_id, first_name, last_name, license_expiry_date FROM transportation.drivers WHERE license_expiry_date < '2025-01-01';

[User] From this list, only include drivers whose status is 'Active'.

[Assistant] SELECT driver_id, first_name, last_name, license_expiry_date FROM transportation.drivers WHERE license_expiry_date < '2025-01-01' AND status = 'Active';

[User] List pairs of drivers who share the same hire_date, showing both driver IDs and the hire_date.

[Assistant]
SELECT d1.driver_id AS driver1_id,
       d2.driver_id AS driver2_id,
       d1.hire_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d1.hire_date = d2.hire_date
  AND d1.driver_id < d2.driver_id;

[User] Now limit to only those hire_dates in the year 2023 and order the results by hire_date ascending.

[Assistant]
SELECT d1.driver_id AS driver1_id,
       d2.driver_id AS driver2_id,
       d1.hire_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d1.hire_date = d2.hire_date
  AND d1.driver_id < d2.driver_id
WHERE d1.hire_date BETWEEN '2023-01-01' AND '2023-12-31'
ORDER BY d1.hire_date ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Show me all notifications sent in the last 7 days, including the user ID and message.

[Assistant] SELECT user_id, message, sent_at FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days';

[User] From that list, only show the notifications that have not been read yet.

[Assistant] SELECT user_id, message, sent_at FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL;

[User] Instead of listing them, can you just give me the total count of unread notifications sent in the last 7 days?

[Assistant] SELECT COUNT(*) FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL;

[User] Now, show the count of unread notifications sent in the last 7 days for each user ID.

[Assistant] SELECT user_id, COUNT(*) FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL GROUP BY user_id;

[User] Get a list of users who have both read and unread notifications. For each user, show their user_id, the count of unread notifications as unread_count, and the count of read notifications as read_count.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;

[User] Actually, I want to filter to only include those users whose unread_count is at least 3.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
  HAVING COUNT(*) >= 3
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;

[User] For each user, list their user_id along with their first and last notification messages and the sent_at timestamps.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id;

[User] Limit to users who have more than 5 notifications.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id
JOIN (
  SELECT user_id
  FROM trading_platform.notifications
  GROUP BY user_id
  HAVING COUNT(*) > 5
) AS filtered ON f.user_id = filtered.user_id;

[User] Also include total_notification_count in the result.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), counts AS (
  SELECT user_id, COUNT(*) AS total_notification_count
  FROM trading_platform.notifications
  GROUP BY user_id
  HAVING COUNT(*) > 5
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at, c.total_notification_count
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id
JOIN counts c ON f.user_id = c.user_id;

[User] Order by total_notification_count descending and limit to top 10.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), counts AS (
  SELECT user_id, COUNT(*) AS total_notification_count
  FROM trading_platform.notifications
  GROUP BY user_id
  HAVING COUNT(*) > 5
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at, c.total_notification_count
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id
JOIN counts c ON f.user_id = c.user_id
ORDER BY c.total_notification_count DESC
LIMIT 10;

[User] Find all notifications that were sent more than 24 hours ago and are still unread. Show the notification ID, user ID, and sent_at timestamp.

[Assistant] SELECT notification_id, user_id, sent_at FROM notifications WHERE read_at IS NULL AND sent_at < NOW() - INTERVAL '24 hour';

[User] Could you provide the total number of notifications sent on each day?

[Assistant] SELECT DATE(sent_at), COUNT(*) FROM notifications GROUP BY DATE(sent_at) ORDER BY DATE(sent_at);

[User] Now, show only the days where more than 50 notifications were sent. Also, for those days, calculate the average time it took for notifications sent on that day to be read (only consider notifications that have been read).

[Assistant] SELECT DATE(sent_at), COUNT(*), AVG(EXTRACT(EPOCH FROM (read_at - sent_at))) FROM notifications WHERE read_at IS NOT NULL GROUP BY DATE(sent_at) HAVING COUNT(*) > 50 ORDER BY DATE(sent_at);

[User] I want to find the average time it takes for a notification to be marked as read, calculated for each user. Please show the user ID and the average read time in seconds, considering only notifications that have been read.

[Assistant] SELECT user_id, AVG(EXTRACT(EPOCH FROM (read_at - sent_at))) AS average_read_time_seconds FROM notifications WHERE read_at IS NOT NULL GROUP BY user_id ORDER BY average_read_time_seconds;

[User] The previous query only included users who have read at least one notification. Please modify it to include all users who have received at least one notification, showing NULL for the average read time if they haven't read any.

[Assistant] SELECT user_id, AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) AS average_read_time_seconds FROM notifications GROUP BY user_id ORDER BY average_read_time_seconds;

[User] Now, filter this list to only include users whose average read time is greater than 600 seconds (10 minutes).

[Assistant] SELECT user_id, AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) AS average_read_time_seconds FROM notifications GROUP BY user_id HAVING AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) > 600 ORDER BY average_read_time_seconds;

[User] Also, include the total number of notifications sent to each of these users in the result, and order the list by average read time in descending order.

[Assistant] SELECT user_id, AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) AS average_read_time_seconds, COUNT(*) AS total_notifications FROM notifications GROUP BY user_id HAVING AVG(CASE WHEN read_at IS NOT NULL THEN EXTRACT(EPOCH FROM (read_at - sent_at)) END) > 600 ORDER BY average_read_time_seconds DESC;

[User] For each user, show their username and the timestamp of their most recent notification. Include users who have never received notifications.

[Assistant] SELECT T1.username, max(T2.sent_at) FROM users AS T1 LEFT JOIN trading_platform.notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.username

[User] Could you also include the total number of notifications for each user?

[Assistant] SELECT T1.username, count(T2.notification_id), max(T2.sent_at) FROM users AS T1 LEFT JOIN trading_platform.notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.username

[User] Actually, only show users whose latest notification is unread.

[Assistant] WITH LatestNotification AS ( SELECT user_id, sent_at, read_at, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY sent_at DESC) AS rn FROM trading_platform.notifications ) SELECT T1.username, T2.sent_at FROM users AS T1 JOIN LatestNotification AS T2 ON T1.user_id = T2.user_id WHERE T2.rn = 1 AND T2.read_at IS NULL

[User] Also, include the count of unread notifications for these users.

[Assistant] WITH LatestNotification AS ( SELECT user_id, sent_at, read_at, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY sent_at DESC) AS rn FROM trading_platform.notifications ) SELECT T1.username, count(CASE WHEN T3.read_at IS NULL THEN T3.notification_id ELSE NULL END), T2.sent_at FROM users AS T1 JOIN LatestNotification AS T2 ON T1.user_id = T2.user_id AND T2.rn = 1 AND T2.read_at IS NULL JOIN trading_platform.notifications AS T3 ON T1.user_id = T3.user_id GROUP BY T1.username, T2.sent_at


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

[User] List token symbols on any chain that have both a realized ratio above 0.8 and an ROI greater than 5. Show their symbol, chain, realized ratio, and ROI.

[Assistant] SELECT token_symbol, chain, realized_ratio, roi FROM smart_money_token_performance WHERE realized_ratio > 0.8 AND roi > 5

[User] Can you also include their PNL and Net Flow in the result?

[Assistant] SELECT token_symbol, chain, realized_ratio, roi, pnl, net_flow FROM smart_money_token_performance WHERE realized_ratio > 0.8 AND roi > 5

[User] For each chain, what is the average price of tokens recorded in the smart_money_token_performance table?

[Assistant] SELECT chain, AVG(price) AS average_token_price FROM smart_money_token_performance GROUP BY chain;

[User] List all token symbols on the 'Ethereum' chain with a Realized Ratio greater than 0.9. Show the symbol and realized ratio.

[Assistant] SELECT token_symbol, realized_ratio FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9;

[User] Can you also include their current Price and Net Flow?

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9;

[User] Now, filter these results to only include tokens where the Net Flow is positive.

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9 AND net_flow > 0;

[User] Order the results by Net Flow descending and show the top 10.

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9 AND net_flow > 0 ORDER BY net_flow DESC LIMIT 10;

[User] How many distinct token symbols are recorded for each chain in the smart money performance data?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) FROM smart_money_token_performance GROUP BY chain

[User] List all smart money addresses that have a negative PNL but a positive Realized Ratio. Show the address, chain, PNL, and Realized Ratio.

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < 0 AND realized_ratio > 0

[User] Can you refine the results to only include addresses where the absolute value of PNL is greater than 1000?

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < -1000 AND realized_ratio > 0

[User] For each chain, which token symbol has the highest pnl and what are its roi and avg_cost?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl;

[User] Could you please also include the realized_ratio for those tokens in the result?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost, t.realized_ratio
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl;

[User] Actually, could you show only results where roi is greater than 3 and realized_ratio is above 0.4?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost, t.realized_ratio
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl
WHERE t.roi > 3 AND t.realized_ratio > 0.4;

[User] And can you order the results by roi descending?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost, t.realized_ratio
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl
WHERE t.roi > 3 AND t.realized_ratio > 0.4
ORDER BY t.roi DESC;

[User] Which 3 tokens across all chains have the highest realized_ratio and what are their avg_cost and roi?

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi
FROM smart_money_token_performance
ORDER BY realized_ratio DESC
LIMIT 3;

[User] I get an error, could you also display their pnl in the result?

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi, pnl
FROM smart_money_token_performance
ORDER BY realized_ratio DESC
LIMIT 3;

[User] Actually, I want tokens where realized_ratio is above 0.7 and net_flow is positive only.

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi, pnl
FROM smart_money_token_performance
WHERE realized_ratio > 0.7 AND net_flow > 0
ORDER BY realized_ratio DESC
LIMIT 3;

[User] And can you order the result by pnl descending instead?

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi, pnl
FROM smart_money_token_performance
WHERE realized_ratio > 0.7 AND net_flow > 0
ORDER BY pnl DESC
LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002

[User] 特定の予約ID 'book_zyx' に関連するすべてのチケットの詳細を取得するのを手伝っていただけますか？また、関連する車両情報も含めてください。

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGETALL ticket:<ticket_id>
HGETALL car:<car_id>

[User] チェックイン済みのチケットだけを表示するようにフィルタリングしていただけますか？

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGET ticket:<ticket_id> is_checked_in
HGETALL ticket:<ticket_id> (only if is_checked_in = 1)
HGETALL car:<car_id>

[User] 座席番号も結果に含めて、座席番号順に並べ替えることは可能ですか？

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGET ticket:<ticket_id> is_checked_in
HGETALL ticket:<ticket_id> (only if is_checked_in = 1)
HGETALL car:<car_id>
(Sort results by seat_number in ascending order)

[User] 車両IDごとにチケットの総数を追加していただけますか？

[Assistant]
SMEMBERS booking:book_zyx:tickets
HGET ticket:<ticket_id> is_checked_in
HGETALL ticket:<ticket_id> (only if is_checked_in = 1)
HGETALL car:<car_id>
(Group by car_id and count total tickets per car_id)
(Sort results by seat_number in ascending order)

[User] 特定の列車ID 'train_789' に関連するすべてのメンテナンス記録の詳細を取得するのを手伝っていただけますか？

[Assistant]
SMEMBERS train:train_789:maintenance
HGETALL maintenance_record:<record_id>

[User] 特定のプラットフォームID 'plat_123' に関連するメンテナンス記録を取得するのを手伝っていただけますか？また、記録のステータスも含めてください。

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGETALL maintenance_record:<record_id>

[User] ステータスが 'Completed' の記録だけを表示するようにフィルタリングしていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')

[User] 関連する資産タイプも結果に含めていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')


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 character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    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, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
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)
)
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_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 patients who have had at least one appointment with a doctor specializing in 'Cardiology'. Include the patient's full name, appointment time, and doctor's full name.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology';

[User] Can you only include appointments that are marked as 'Completed'?

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed';

[User] Only show appointments that lasted at least 45 minutes.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed' AND a.duration_minutes >= 45;

[User] Could you also include the doctor's specialty in the result?

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, d.specialty
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed' AND a.duration_minutes >= 45;

[User] List each patient's first and last name along with their total number of appointments in 2024.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY p.first_name, p.last_name;

[User] Now exclude all 'Cancelled' appointments from the count.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
  AND a.status <> 'Cancelled'
GROUP BY p.first_name, p.last_name;

[User] Also, only show patients who have more than 2 appointments and sort the result by appointment_count in descending order.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
  AND a.status <> 'Cancelled'
GROUP BY p.first_name, p.last_name
HAVING COUNT(a.appointment_id) > 2
ORDER BY appointment_count DESC;

[User] List the medication name and manufacturer of all medications where the description contains the word 'extended'.

[Assistant]
SELECT medication_name, manufacturer
FROM healthcare.medications
WHERE description ILIKE '%extended%';

[User] Only include medications where the ndc_code is not null and has more than 8 characters.

[Assistant]
SELECT medication_name, manufacturer
FROM healthcare.medications
WHERE description ILIKE '%extended%'
  AND ndc_code IS NOT NULL
  AND length(ndc_code) > 8;

[User] Provide each patient's most recent medical-record doctor's full name along with their primary insurance plan name. Return patient_id, first_name, last_name, primary_plan_name, doctor_first_name, doctor_last_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name      AS primary_plan_name,
       d.first_name      AS doctor_first_name,
       d.last_name       AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id
 AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans AS ip
  ON pi.plan_id = ip.plan_id
JOIN (
  SELECT DISTINCT ON (patient_id)
         patient_id,
         doctor_id,
         record_date
  FROM healthcare.medical_records
  ORDER BY patient_id, record_date DESC
) AS mr
  ON p.patient_id = mr.patient_id
JOIN healthcare.doctors AS d
  ON mr.doctor_id = d.doctor_id;

[User] Actually, restrict to only those whose primary plan_type is 'PPO'.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name      AS primary_plan_name,
       d.first_name      AS doctor_first_name,
       d.last_name       AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id
 AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans AS ip
  ON pi.plan_id = ip.plan_id
JOIN (
  SELECT DISTINCT ON (patient_id)
         patient_id,
         doctor_id,
         record_date
  FROM healthcare.medical_records
  ORDER BY patient_id, record_date DESC
) AS mr
  ON p.patient_id = mr.patient_id
JOIN healthcare.doctors AS d
  ON mr.doctor_id = d.doctor_id
WHERE ip.plan_type = 'PPO';

[User] Find patients who currently have both a primary and a secondary insurance policy. For each, show patient_id, full name, primary policy_number, and secondary policy_number.

[Assistant]
SELECT p.patient_id,
       p.first_name || ' ' || p.last_name AS patient_name,
       pri.policy_number AS primary_policy,
       sec.policy_number AS secondary_policy
FROM healthcare.patients p
JOIN healthcare.patient_insurance pri ON p.patient_id = pri.patient_id AND pri.is_primary = TRUE
JOIN healthcare.patient_insurance sec ON p.patient_id = sec.patient_id AND sec.is_primary = FALSE;

[User] List all patients along with their primary insurance plan name and the first and last name of their prescribing doctor for any prescription they have received.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, ip.plan_name AS primary_insurance_plan, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
LEFT JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true
LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
LEFT JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
LEFT JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id;

[User] Only include patients whose insurance plan type is 'EPO' and prescriptions issued after January 1st, 2023.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, ip.plan_name AS primary_insurance_plan, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
LEFT JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true
LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
LEFT JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id AND pr.prescription_date >= '2023-01-01'
LEFT JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
WHERE ip.plan_type = 'EPO';

[User] Add the prescription's medication_id and dosage to the results, and sort by prescription_date descending.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, ip.plan_name AS primary_insurance_plan, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, pr.medication_id, pr.dosage, pr.prescription_date
FROM healthcare.patients p
LEFT JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id AND pi.is_primary = true
LEFT JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
LEFT JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id AND pr.prescription_date >= '2023-01-01'
LEFT JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id
WHERE ip.plan_type = 'EPO'
ORDER BY pr.prescription_date DESC;

[User] Show all patients along with the names of all insurance plans they are enrolled in, plus the insurance provider for each plan.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, ip.plan_name, ip.insurance_provider
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id;

[User] Only include patients whose insurance plan type is 'POS'.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, ip.plan_name, ip.insurance_provider
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.plan_type = 'POS';

[User] Also, sort the results by patient's last name in ascending order and insurance plan name descending.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, ip.plan_name, ip.insurance_provider
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.plan_type = 'POS'
ORDER BY p.last_name ASC, ip.plan_name DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.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.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )

[User] Show me all users who have commented on a post and have also liked any comment on that same post. I want their user IDs and the corresponding post IDs.

[Assistant]
SELECT DISTINCT c.user_id, c.post_id
FROM social_media.comments c
JOIN social_media.likes l ON l.comment_id IS NOT NULL AND l.post_id = c.post_id AND l.user_id = c.user_id

[User] Can you also include the comment content that was liked and the time the like was created?

[Assistant]
SELECT DISTINCT c.user_id, c.post_id, c2.content AS liked_comment_content, l.created_at AS like_created_at
FROM social_media.comments c
JOIN social_media.likes l ON l.comment_id IS NOT NULL AND l.post_id = c.post_id AND l.user_id = c.user_id
JOIN social_media.comments c2 ON c2.comment_id = l.comment_id

[User] Show me the content of all comments that have received at least one like.

[Assistant] SELECT DISTINCT T1.content FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id;

[User] Also include the creation time of these comments and the user_id of the commenter?

[Assistant] SELECT DISTINCT T1.comment_id, T1.content, T1.created_at, T1.user_id FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id;

[User] Only show comments created before '2024-05-01'.

[Assistant] SELECT DISTINCT T1.comment_id, T1.content, T1.created_at, T1.user_id FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T1.created_at < '2024-05-01';

[User] Show me all users who have liked both a comment and a post, including their user IDs.

[Assistant]
SELECT DISTINCT l1.user_id
FROM social_media.likes l1
JOIN social_media.likes l2 ON l1.user_id = l2.user_id
WHERE l1.post_id IS NOT NULL AND l2.comment_id IS NOT NULL;

[User] Please also include the post ID and the comment ID for each user.

[Assistant]
SELECT DISTINCT l1.user_id, l1.post_id, l2.comment_id
FROM social_media.likes l1
JOIN social_media.likes l2 ON l1.user_id = l2.user_id
WHERE l1.post_id IS NOT NULL AND l2.comment_id IS NOT NULL;

[User] Now only show users who liked at least two different posts and two different comments, and include the count of distinct posts and comments they liked.

[Assistant]
SELECT user_id, COUNT(DISTINCT post_id) AS distinct_post_count, COUNT(DISTINCT comment_id) AS distinct_comment_count
FROM social_media.likes
WHERE post_id IS NOT NULL OR comment_id IS NOT NULL
GROUP BY user_id
HAVING COUNT(DISTINCT post_id) >= 2 AND COUNT(DISTINCT comment_id) >= 2;

[User] List all comment IDs that have not received any likes.

[Assistant] SELECT T1.comment_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;

[User] Can you also include the content of these comments and the post_id they belong to?

[Assistant] SELECT T1.comment_id, T1.content, T1.post_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;

[User] List all conversation IDs with the total number of messages sent in each conversation.

[Assistant]
SELECT conversation_id, COUNT(*) AS message_count
FROM social_media.messages
GROUP BY conversation_id;

[User] Show me the usernames of users who have commented on posts that were created in group chat conversations, along with the names of those group chats.

[Assistant]
SELECT u.username, c.group_name
FROM social_media.comments cm
JOIN social_media.posts p ON cm.post_id = p.post_id
JOIN social_media.conversations c ON p.post_id = c.conversation_id AND c.is_group_chat = true
JOIN social_media.users u ON cm.user_id = u.user_id
;

[User] Can you also include the time each user commented?

[Assistant]
SELECT u.username, c.group_name, cm.created_at AS comment_time
FROM social_media.comments cm
JOIN social_media.posts p ON cm.post_id = p.post_id
JOIN social_media.conversations c ON p.post_id = c.conversation_id AND c.is_group_chat = true
JOIN social_media.users u ON cm.user_id = u.user_id
;

[User] How many likes were given to comments in June 2024?

[Assistant]
SELECT COUNT(*) AS comment_likes_count
FROM social_media.likes
WHERE comment_id IS NOT NULL
  AND DATE_TRUNC('month', created_at) = '2024-06-01';