[User] List all reviews for properties with a star rating of at least 4.5. Include the property_name, review_id, rating_overall, and review_date.

[Assistant]
SELECT p.property_name, r.review_id, r.rating_overall, r.review_date
FROM hospitality_technology.reviews r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE p.star_rating >= 4.5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Show me the count of notifications sent for each channel for applications submitted after January 1, 2024.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at > '2024-01-01'
GROUP BY n.channel;

[User] Now, only include channels that have sent more than 10 notifications.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at > '2024-01-01'
GROUP BY n.channel
HAVING COUNT(*) > 10;

[User] Exclude notifications with the status 'Failed'.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at > '2024-01-01' AND n.status != 'Failed'
GROUP BY n.channel
HAVING COUNT(*) > 10;

[User] Show for 2023 instead of 2024.

[Assistant]
SELECT n.channel, COUNT(*) AS notification_count
FROM government_services.notifications n
JOIN government_services.applications a ON n.application_id = a.application_id
WHERE a.submitted_at >= '2023-01-01' AND a.submitted_at < '2024-01-01' AND n.status != 'Failed'
GROUP BY n.channel
HAVING COUNT(*) > 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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.notifications ( notification_id text, 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 all invoices that were paid within 7 days of their issue date. Show invoice number, issue date, payment date, and total amount.

[Assistant] SELECT invoice_number, issue_date, payment_date, total_amount FROM legal_services.invoices WHERE status = 'Paid' AND payment_date IS NOT NULL AND (payment_date::DATE - issue_date) <= 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )


[User] I want to identify pairs of bookings that share the same payment_transaction_id, showing both booking IDs and the payment_transaction_id.

[Assistant]
SELECT b1.booking_id AS booking1, b2.booking_id AS booking2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
  AND b1.booking_id < b2.booking_id;

[User] Now limit the results to only include pairs where both bookings have a status of 'Completed'.

[Assistant]
SELECT b1.booking_id AS booking1, b2.booking_id AS booking2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
  AND b1.booking_id < b2.booking_id
WHERE b1.status = 'Completed'
  AND b2.status = 'Completed';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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] List all time entries for lawyers specializing in 'Criminal Law'. Show the entry ID, the date worked, hours spent, and the first and last name of the lawyer who performed the work.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries te JOIN legal_services.lawyers l ON te.lawyer_id = l.lawyer_id WHERE l.specialization = 'Criminal Law';

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


[User] List the claim_id and the total number of documents uploaded for each claim, but only include claims with between 3 and 7 documents.

[Assistant] SELECT claim_id, COUNT(*) AS document_count FROM insurance.claim_documents GROUP BY claim_id HAVING COUNT(*) BETWEEN 3 AND 7;

[User] Can you also show the upload time of the most recent document for each claim in this list?

[Assistant] SELECT cd.claim_id, COUNT(*) AS document_count, MAX(cd.uploaded_at) AS latest_uploaded_at FROM insurance.claim_documents cd GROUP BY cd.claim_id HAVING COUNT(*) BETWEEN 3 AND 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] What is the average number of days by which paid invoices were paid late? Calculate the average of (payment_date - due_date) for invoices with status 'Paid'.

[Assistant]
SELECT AVG((payment_date::date - due_date)) AS average_late_days
FROM legal_services.invoices
WHERE status = 'Paid';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )


[User] List all reservations where the number of adults is greater than 2, showing reservation_id, guest_id, and the total_amount.

[Assistant]
SELECT reservation_id, guest_id, total_amount
FROM hospitality_technology.reservations
WHERE num_adults > 2;

[User] Can you also include the room_type_id and the status for each reservation?

[Assistant]
SELECT reservation_id, guest_id, room_type_id, status, total_amount
FROM hospitality_technology.reservations
WHERE num_adults > 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] For each claim, show the corresponding product_type of the insurance product for the related policy.

[Assistant]
SELECT cl.claim_id, ip.product_type
FROM insurance.claims cl
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id;

[User] Sorry, there is no policies table, I got an error. Can you try joining claims to insurance_products another way?

[Assistant]
-- Unable to join directly since there is no 'policies' table connecting claims to insurance_products. If policy_id equals product_id, you may try:
SELECT claim_id, policy_id, product_type
FROM insurance.claims
JOIN insurance.insurance_products ON claims.policy_id = insurance_products.product_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] List all guests who have placed service orders for services in the 'Transportation' department, along with their full names and the service names.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, s.service_name
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so ON g.guest_id = so.guest_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE s.department = 'Transportation';

[User] Actually, only include guests who have placed at least two such service orders. Also, order the results by the guest's last name.

[Assistant]
SELECT g.guest_id, g.first_name, g.last_name, COUNT(so.order_id) AS order_count
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so ON g.guest_id = so.guest_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE s.department = 'Transportation'
GROUP BY g.guest_id, g.first_name, g.last_name
HAVING COUNT(so.order_id) >= 2
ORDER BY g.last_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )


[User] List all managers (employees who have other employees reporting to them) along with the count of their direct reports, showing only those with more than 5 reports.

[Assistant] SELECT e.employee_id, e.first_name, e.last_name, COUNT(r.employee_id) as direct_reports_count FROM financial_services.employees e JOIN financial_services.employees r ON e.employee_id = r.manager_id WHERE e.status = 'Active' GROUP BY e.employee_id, e.first_name, e.last_name HAVING COUNT(r.employee_id) > 5 ORDER BY direct_reports_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )


[User] Could you list each game title along with its developer's name and the total number of servers hosting it?

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
LEFT JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
LEFT JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title, d.name;

[User] Actually, please include only servers with status = 'online' and exclude games with zero online servers.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.status = 'online'
GROUP BY g.title, d.name;

[User] I want to see only developers based in 'USA'.

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id AND s.status = 'online'
WHERE d.country = 'USA'
GROUP BY g.title, d.name;

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

[Assistant]
SELECT g.title, d.name AS developer_name, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id AND s.status = 'online'
WHERE d.country = 'USA'
GROUP BY g.title, d.name
ORDER BY server_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )


[User] Show me a list of all properties along with their average overall review rating.

[Assistant]
SELECT p.property_id, p.property_name, AVG(r.rating_overall) AS avg_rating
FROM hospitality_technology.properties p
JOIN hospitality_technology.reviews r ON p.property_id = r.property_id
GROUP BY p.property_id, p.property_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] For each chain, which centralized exchange holds the largest total USD value in their token balance as of the most recent snapshot?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
GROUP BY c.chain, c.exchange
QUALIFY ROW_NUMBER() OVER(PARTITION BY c.chain ORDER BY SUM(c.usd_value) DESC) = 1;

[User] Could you also include the number of distinct tokens each exchange holds in those chains?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  GROUP BY c.chain, c.exchange
),
ranked_exchanges AS (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY chain ORDER BY total_usd_value DESC) AS rn
  FROM exchange_totals
)
SELECT chain, exchange, total_usd_value, token_count
FROM ranked_exchanges
WHERE rn = 1;

[User] I got an error with the QUALIFY clause. Can you rewrite the query using a derived table or CTE instead?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  GROUP BY c.chain, c.exchange
),
max_values AS (
  SELECT chain, MAX(total_usd_value) AS max_usd_value
  FROM exchange_totals
  GROUP BY chain
)
SELECT e.chain, e.exchange, e.total_usd_value, e.token_count
FROM exchange_totals e
JOIN max_values m ON e.chain = m.chain AND e.total_usd_value = m.max_usd_value;

[User] Now, only show exchanges where their usd_value is above $5,000,000.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  GROUP BY c.chain, c.exchange
),
max_values AS (
  SELECT chain, MAX(total_usd_value) AS max_usd_value
  FROM exchange_totals
  GROUP BY chain
)
SELECT e.chain, e.exchange, e.total_usd_value, e.token_count
FROM exchange_totals e
JOIN max_values m ON e.chain = m.chain AND e.total_usd_value = m.max_usd_value
WHERE e.total_usd_value > 5000000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp chain character varying(128) NOT NULL, -- the chain that the token resides address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX exchange character varying(512) NOT NULL, -- a centralized exchange name token_address character varying(128) NOT NULL, -- token contract address token_symbol character varying(512), --token symbol balance numeric(38,10), -- token balance usd_value numeric(38,14), -- value of the token held in USD price double precision, --price of the token in USD ,PRIMARY KEY (snapshot_time, exchange, address, chain, token_address) )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )


[User] List all premium payments for policy 'POL123'. Show payment ID, payment date, amount paid, and status.

[Assistant] SELECT payment_id, payment_date, amount_paid, status FROM insurance.premium_payments WHERE policy_id = 'POL123';

[User] Only show payments made on or after January 1, 2024.

[Assistant] SELECT payment_id, payment_date, amount_paid, status FROM insurance.premium_payments WHERE policy_id = 'POL123' AND payment_date >= '2024-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)


[User] Show me all reservations with their reservation_id, room_number, room status, and check_in_date.

[Assistant]
SELECT r.reservation_id,
       rm.room_number,
       rm.status AS room_status,
       r.check_in_date
FROM hospitality_technology.reservations r
LEFT JOIN hospitality_technology.rooms rm
  ON r.room_id = rm.room_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )


[User] Find pairs of insurance policies where the plan_id is the same, but they belong to different patients. Show the plan_id, and the patient_id and policy_number for both policies in the pair.

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id;

[User] Refine this to only include policies that are currently active (expiration_date IS NULL or > CURRENT_DATE) for both policies in the pair.

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id AND (T1.expiration_date IS NULL OR T1.expiration_date > CURRENT_DATE) AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE);

[User] Also, only show pairs where one policy is primary and the other is not primary (is_primary = TRUE for one, is_primary = FALSE for the other).

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id AND (T1.expiration_date IS NULL OR T1.expiration_date > CURRENT_DATE) AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND ((T1.is_primary = TRUE AND T2.is_primary = FALSE) OR (T1.is_primary = FALSE AND T2.is_primary = TRUE));

[User] Filter further to only show pairs where the shared plan_id starts with 'HMO'.

[Assistant] SELECT T1.plan_id, T1.patient_id AS patient_id_1, T1.policy_number AS policy_number_1, T2.patient_id AS patient_id_2, T2.policy_number AS policy_number_2 FROM healthcare.patient_insurance AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.plan_id = T2.plan_id WHERE T1.patient_id <> T2.patient_id AND T1.patient_insurance_id < T2.patient_insurance_id AND (T1.expiration_date IS NULL OR T1.expiration_date > CURRENT_DATE) AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND ((T1.is_primary = TRUE AND T2.is_primary = FALSE) OR (T1.is_primary = FALSE AND T2.is_primary = TRUE)) AND T1.plan_id LIKE 'HMO%';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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] Retrieve all pairs of distinct contract IDs that were created by the same creator within an hour of each other. Include the creator address and the timestamps of both contracts.

[Assistant] SELECT sc1.creator_address, sc1.contract_id AS contract_id_1, sc1.timestamp AS timestamp_1, sc2.contract_id AS contract_id_2, sc2.timestamp AS timestamp_2 FROM blockchain.smart_contracts sc1 JOIN blockchain.smart_contracts sc2 ON sc1.creator_address = sc2.creator_address AND sc1.contract_id <> sc2.contract_id WHERE ABS(UNIX_TIMESTAMP(sc1.timestamp) - UNIX_TIMESTAMP(sc2.timestamp)) <= 3600 AND sc1.timestamp < sc2.timestamp;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )


[User] List all guests who have not provided their date of birth, along with their email if available.

[Assistant] SELECT guest_id, first_name, last_name, email FROM hospitality_technology.guests WHERE date_of_birth IS NULL;

[User] Now, filter these results to only include guests from the USA.

[Assistant] SELECT guest_id, first_name, last_name, email FROM hospitality_technology.guests WHERE date_of_birth IS NULL AND country_code = 'USA';

[User] The query is missing their city information. Can you include that as well?

[Assistant] SELECT guest_id, first_name, last_name, email, city FROM hospitality_technology.guests WHERE date_of_birth IS NULL AND country_code = 'USA';

[User] Actually, I need to see the results ordered by created_at in descending order.

[Assistant] SELECT guest_id, first_name, last_name, email, city, created_at FROM hospitality_technology.guests WHERE date_of_birth IS NULL AND country_code = 'USA' ORDER BY created_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )


[User] Show me document_id, application_id, and verification_status for all documents submitted by citizen 'cit123'.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM documents
WHERE citizen_id = 'cit123';

[User] I got an error: relation 'documents' does not exist.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM government_services.documents
WHERE citizen_id = 'cit123';

[User] Now, only include documents where verification_status = 'Pending'.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM government_services.documents
WHERE citizen_id = 'cit123'
  AND verification_status = 'Pending';

[User] Also, limit the results to files uploaded in 2024.

[Assistant]
SELECT document_id,
       application_id,
       verification_status
FROM government_services.documents
WHERE citizen_id = 'cit123'
  AND verification_status = 'Pending'
  AND upload_timestamp >= '2024-01-01'
  AND upload_timestamp < '2025-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, 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.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.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] List all pairs of properties located in the same city, showing each pair's property IDs and names along with the city.

[Assistant]
SELECT p1.property_id AS property_id_1,
       p1.property_name AS property_name_1,
       p2.property_id AS property_id_2,
       p2.property_name AS property_name_2,
       p1.city
FROM hospitality_technology.properties p1
JOIN hospitality_technology.properties p2
  ON p1.city = p2.city
 AND p1.property_id < p2.property_id;

[User] Only include pairs in cities that have more than two properties.

[Assistant]
SELECT p1.property_id AS property_id_1,
       p1.property_name AS property_name_1,
       p2.property_id AS property_id_2,
       p2.property_name AS property_name_2,
       p1.city
FROM hospitality_technology.properties p1
JOIN hospitality_technology.properties p2
  ON p1.city = p2.city
 AND p1.property_id < p2.property_id
WHERE p1.city IN (
  SELECT city
  FROM hospitality_technology.properties
  GROUP BY city
  HAVING COUNT(*) > 2
);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )


[User] Show me a summary of all clients with the total number of invoices they've received and the sum of total_amount for those invoices.

[Assistant]
SELECT cl.client_id,
       CONCAT(cl.first_name, ' ', cl.last_name) AS client_name,
       COUNT(inv.invoice_id) AS invoice_count,
       SUM(inv.total_amount) AS total_amount_sum
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv ON cl.client_id = inv.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name;

[User] I'd like to consider only invoices issued in the year 2023.

[Assistant]
SELECT cl.client_id,
       CONCAT(cl.first_name, ' ', cl.last_name) AS client_name,
       COUNT(inv.invoice_id) AS invoice_count,
       SUM(inv.total_amount) AS total_amount_sum
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv ON cl.client_id = inv.client_id
WHERE inv.issue_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY cl.client_id, cl.first_name, cl.last_name;

[User] And exclude clients who have not paid any amount on any of their invoices.

[Assistant]
SELECT cl.client_id,
       CONCAT(cl.first_name, ' ', cl.last_name) AS client_name,
       COUNT(inv.invoice_id) AS invoice_count,
       SUM(inv.total_amount) AS total_amount_sum,
       SUM(inv.amount_paid) AS amount_paid_sum
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv ON cl.client_id = inv.client_id
WHERE inv.issue_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING SUM(inv.amount_paid) > 0;

[User] Finally, order the results by the sum of total_amount in descending order.

[Assistant]
SELECT cl.client_id,
       CONCAT(cl.first_name, ' ', cl.last_name) AS client_name,
       COUNT(inv.invoice_id) AS invoice_count,
       SUM(inv.total_amount) AS total_amount_sum,
       SUM(inv.amount_paid) AS amount_paid_sum
FROM legal_services.clients cl
LEFT JOIN legal_services.invoices inv ON cl.client_id = inv.client_id
WHERE inv.issue_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING SUM(inv.amount_paid) > 0
ORDER BY total_amount_sum DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )


[User] List each achievement with the very next achievement unlocked by the same player using a self-join. Show player_id, current_ach, current_unlocked_at, next_ach, and next_unlocked_at.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 );

[User] Now restrict to pairs where the time difference between current_unlocked_at and next_unlocked_at is less than 48 hours.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours';

[User] Order the results by player_id and current_unlocked_at ascending.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours'
ORDER BY pa1.player_id ASC, pa1.unlocked_at ASC;

[User] Finally, limit to 20 rows.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS current_ach,
       pa1.unlocked_at AS current_unlocked_at,
       pa2.achievement_id AS next_ach,
       pa2.unlocked_at AS next_unlocked_at
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa2.unlocked_at = (
     SELECT MIN(pa3.unlocked_at)
     FROM gaming_technology.player_achievements pa3
     WHERE pa3.player_id = pa1.player_id
       AND pa3.unlocked_at > pa1.unlocked_at
 )
WHERE pa2.unlocked_at - pa1.unlocked_at < INTERVAL '48 hours'
ORDER BY pa1.player_id ASC, pa1.unlocked_at ASC
LIMIT 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )


[User] List each transaction along with its status and the names of any events that were emitted during that transaction.

[Assistant]
SELECT tr.transaction_id, tr.status, e.event_name
FROM web3.transactions tr
LEFT JOIN web3.events e ON tr.transaction_id = e.transaction_id;

[User] Only show transactions that had more than one event emitted, and list the number of events for each such transaction.

[Assistant]
SELECT tr.transaction_id, tr.status, COUNT(e.event_id) AS event_count
FROM web3.transactions tr
JOIN web3.events e ON tr.transaction_id = e.transaction_id
GROUP BY tr.transaction_id, tr.status
HAVING COUNT(e.event_id) > 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] List the transaction IDs and gas used for transactions where gas used is greater than 500000.

[Assistant] SELECT transaction_id, gas_used FROM web3.transactions WHERE gas_used > 500000;

[User] Order the results by gas used in descending order.

[Assistant] SELECT transaction_id, gas_used FROM web3.transactions WHERE gas_used > 500000 ORDER BY gas_used DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] Show me each loyalty program ID along with the full names of all passengers enrolled in that program.

[Assistant] SELECT loyalty_program_id, first_name, last_name FROM transportation.passengers WHERE loyalty_program_id IS NOT NULL ORDER BY loyalty_program_id, last_name, first_name;

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


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

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

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id text, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )


[User] Show me all properties in California with their star ratings and the total number of rooms they have, ordered by the room count in descending order.

[Assistant] SELECT p.property_id, p.property_name, p.star_rating, COUNT(r.room_id) AS room_count FROM hospitality_technology.properties p LEFT JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.state_province = 'California' GROUP BY p.property_id, p.property_name, p.star_rating ORDER BY room_count DESC;

[User] Now, include only properties with a star rating of 4.0 or higher and show the average base rate of their room types.

[Assistant] SELECT p.property_id, p.property_name, p.star_rating, COUNT(r.room_id) AS room_count, AVG(rt.base_rate) AS avg_base_rate FROM hospitality_technology.properties p LEFT JOIN hospitality_technology.rooms r ON p.property_id = r.property_id LEFT JOIN hospitality_technology.room_types rt ON p.property_id = rt.property_id WHERE p.state_province = 'California' AND p.star_rating >= 4.0 GROUP BY p.property_id, p.property_name, p.star_rating ORDER BY room_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] I want to find the total number of ERC1155 "approval-for-all" events per contract. Show contract_address and the approval_count.

[Assistant]
SELECT contract_address, COUNT(*) AS approval_count
FROM erc1155_approval_for_all
GROUP BY contract_address;

[User] Also show the number of unique wallet holders currently holding any token from those contracts by joining to nft_holders.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       COALESCE(b.holder_count, 0) AS holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
LEFT JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
) b
  ON a.contract_address = b.contract_address;

[User] Filter to only include contracts where holder_count is greater than 50.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       b.holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
  HAVING COUNT(DISTINCT wallet_address) > 50
) b
  ON a.contract_address = b.contract_address;

[User] Sort results by approval_count descending and limit to the top 10.

[Assistant]
SELECT a.contract_address,
       a.approval_count,
       b.holder_count
FROM (
  SELECT contract_address, COUNT(*) AS approval_count
  FROM erc1155_approval_for_all
  GROUP BY contract_address
) a
JOIN (
  SELECT contract_address, COUNT(DISTINCT wallet_address) AS holder_count
  FROM nft_holders
  GROUP BY contract_address
  HAVING COUNT(DISTINCT wallet_address) > 50
) b
  ON a.contract_address = b.contract_address
ORDER BY a.approval_count DESC
LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )


[User] List the employee's first and last name along with the appointment ID and scheduled start time for all appointments associated with the citizen who has the national ID number 'A123456789'.

[Assistant]
SELECT e.first_name, e.last_name, a.appointment_id, a.scheduled_start_time
FROM government_services.appointments a
JOIN government_services.employees e ON a.employee_id = e.employee_id
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
WHERE c.national_id_number = 'A123456789';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] Can you provide a breakdown of total and average account balance by account_type and currency for each account status?

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance
FROM financial_services.accounts
GROUP BY account_type, currency, status;

[User] Could you include the minimum and maximum interest rate for each group as well?

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance, MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type, currency, status;

[User] Only show groups where the total_accounts is greater than 20.

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance, MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type, currency, status
HAVING COUNT(*) > 20;

[User] Please sort the results by average_balance in descending order.

[Assistant]
SELECT account_type, currency, status, COUNT(*) AS total_accounts, SUM(balance) AS total_balance, AVG(balance) AS average_balance, MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type, currency, status
HAVING COUNT(*) > 20
ORDER BY average_balance DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)


[User] Show me the deployer address and the count of contracts they have deployed on the 'mainnet' network, but only for deployers who have deployed more than 5 contracts on mainnet. Sort the results by the count in descending order.

[Assistant] SELECT deployer_address, COUNT(*) FROM web3.contracts WHERE network_id = 'mainnet' GROUP BY deployer_address HAVING COUNT(*) > 5 ORDER BY COUNT(*) DESC;

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id text PRIMARY KEY, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )


[User] Show the agent_id, first name, and last name for all agents who were hired before January 1, 2020.

[Assistant] SELECT agent_id, first_name, last_name FROM insurance.agents WHERE hire_date < '2020-01-01';

[User] Additionally, only include agents who have a commission rate greater than 0.05.

[Assistant] SELECT agent_id, first_name, last_name FROM insurance.agents WHERE hire_date < '2020-01-01' AND commission_rate > 0.05;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )


[User] List all group conversations that were created after January 1st, 2023, and for each, show the names of hashtags that were created within the same month as the conversation.

[Assistant]
SELECT c.conversation_id, c.group_name, c.created_at AS conversation_created_at, h.tag_name, h.created_at AS hashtag_created_at
FROM social_media.conversations c
JOIN social_media.hashtags h
  ON DATE_TRUNC('month', c.created_at) = DATE_TRUNC('month', h.created_at)
WHERE c.is_group_chat = TRUE
  AND c.created_at > '2023-01-01';

[User] Instead of hashtag names, can you show their hashtag IDs?

[Assistant]
SELECT c.conversation_id, c.group_name, c.created_at AS conversation_created_at, h.hashtag_id, h.created_at AS hashtag_created_at
FROM social_media.conversations c
JOIN social_media.hashtags h
  ON DATE_TRUNC('month', c.created_at) = DATE_TRUNC('month', h.created_at)
WHERE c.is_group_chat = TRUE
  AND c.created_at > '2023-01-01';

[User] Also, filter only group chats where the group name contains the word 'Project'.

[Assistant]
SELECT c.conversation_id, c.group_name, c.created_at AS conversation_created_at, h.hashtag_id, h.created_at AS hashtag_created_at
FROM social_media.conversations c
JOIN social_media.hashtags h
  ON DATE_TRUNC('month', c.created_at) = DATE_TRUNC('month', h.created_at)
WHERE c.is_group_chat = TRUE
  AND c.created_at > '2023-01-01'
  AND c.group_name ILIKE '%Project%';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )


[User] Show the total number of bookings grouped by payment_transaction_id.

[Assistant] SELECT payment_transaction_id, COUNT(*) AS booking_count FROM transportation.bookings GROUP BY payment_transaction_id;

[User] Exclude entries with null payment_transaction_id and order the results by the booking count descending.

[Assistant] SELECT payment_transaction_id, COUNT(*) AS booking_count FROM transportation.bookings WHERE payment_transaction_id IS NOT NULL GROUP BY payment_transaction_id ORDER BY booking_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
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 PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] Can you show me the number of servers in each region, as well as the total max_players for each region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players FROM gaming_technology.servers GROUP BY region;

[User] Actually, can you also include the average number of current players per region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players, AVG(current_players) AS avg_current_players FROM gaming_technology.servers GROUP BY region;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )


[User] For each player, calculate the total quantity of items they have acquired. Return player_id and total_quantity.

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

[User] Exclude players whose total_quantity is less than 50.

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

[User] Also include the number of distinct items each player has acquired as distinct_item_count.

[Assistant]
SELECT player_id,
       SUM(quantity) AS total_quantity,
       COUNT(DISTINCT item_id) AS distinct_item_count
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) >= 50;

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

[Assistant]
SELECT player_id,
       SUM(quantity) AS total_quantity,
       COUNT(DISTINCT item_id) AS distinct_item_count
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) >= 50
ORDER BY total_quantity DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )


[User] Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens where the price is greater than $0.1.

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] I think there's an error in your query - it should be 'tpl.symbol' not 'tm.symbol'. Also, can you add the decimals to the results?

[Assistant] SELECT tm.name, tm.contract_address, tm.decimals, tm.total_supply, tpl.symbol, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.1 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] Now filter these results to only show tokens with decimals equal to 18.

[Assistant] SELECT tm.name, tm.contract_address, tm.decimals, tm.total_supply, tpl.symbol, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tpl.price > 0.1 AND tm.decimals = 18 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


[User] Count the total number of employees who have a direct manager assigned.

[Assistant] SELECT COUNT(employee_id) FROM government_services.employees WHERE manager_employee_id IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id.text, 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.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.notifications ( notification_id.text, 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] Which route numbers connect locations with a distance less than 80 km and more than 5 words in their description? Include the route type in the results.

[Assistant] SELECT route_number, type FROM transportation.routes WHERE distance_km < 80 AND array_length(regexp_split_to_array(description, '\s+'), 1) > 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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 )


[User] List the full name and bar number of all lawyers who were hired before 2015.

[Assistant]
SELECT first_name || ' ' || last_name AS lawyer_full_name, bar_number
FROM legal_services.lawyers
WHERE hire_date < '2015-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_id) )