System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] I need a report showing each passenger's total number of bookings and the date of their most recent booking.

[Assistant]
SELECT b.passenger_id,
       COUNT(*) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
GROUP BY b.passenger_id;

[User] Only include passengers who have made at least 3 bookings.

[Assistant]
SELECT b.passenger_id,
       COUNT(*) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
GROUP BY b.passenger_id
HAVING COUNT(*) >= 3;

[User] Also include the passenger's full name and email in the result.

[Assistant]
SELECT p.passenger_id,
       p.first_name || ' ' || p.last_name AS full_name,
       p.email,
       COUNT(b.booking_id) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING COUNT(b.booking_id) >= 3;

[User] Finally, order the output by total bookings descending and limit to the top 5.

[Assistant]
SELECT p.passenger_id,
       p.first_name || ' ' || p.last_name AS full_name,
       p.email,
       COUNT(b.booking_id) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING COUNT(b.booking_id) >= 3
ORDER BY total_bookings DESC
LIMIT 5;

[User] Please provide a list of all trips along with their route details, including the route_number, origin city, and destination city, ordered by scheduled_departure.

[Assistant]
SELECT t.trip_id,
       t.vehicle_id,
       t.driver_id,
       r.route_number,
       ol.city AS origin_city,
       dl.city AS destination_city,
       t.scheduled_departure
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.locations ol ON t.origin_location_id = ol.location_id
JOIN transportation.locations dl ON t.destination_location_id = dl.location_id
ORDER BY t.scheduled_departure;

[User] Give me the vehicle ID, make, model, year, and the total number of trips made by each vehicle.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, v.year, COUNT(t.trip_id) AS total_trips
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model, v.year;

[User] List all routes along with the number of unique vehicles assigned to trips on each route.

[Assistant]
SELECT r.route_id, r.route_number, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number;

[User] Can you add the average passenger count per trip for each route as well?

[Assistant]
SELECT r.route_id, r.route_number, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles, AVG(t.passenger_count) AS avg_passenger_count
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number;

[User] Only show routes where there have been more than 5 trips.

[Assistant]
SELECT r.route_id, r.route_number, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles, AVG(t.passenger_count) AS avg_passenger_count, COUNT(t.trip_id) AS total_trips
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number
HAVING COUNT(t.trip_id) > 5;

[User] Please also include the route type and order the results by the average passenger count in descending order.

[Assistant]
SELECT r.route_id, r.route_number, r.type AS route_type, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles, AVG(t.passenger_count) AS avg_passenger_count, COUNT(t.trip_id) AS total_trips
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number, r.type
HAVING COUNT(t.trip_id) > 5
ORDER BY avg_passenger_count DESC;

[User] Show all trips with the trip ID, route number, and the full description of each route.

[Assistant]
SELECT t.trip_id, r.route_number, r.description
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id;

[User] What is the average maintenance cost per vehicle?

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id;

[User] Only include vehicles with average maintenance cost greater than 300.

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id
HAVING AVG(cost) > 300;

[User] Also display the most recent service_date for each vehicle.

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost, MAX(service_date) AS last_service_date
FROM transportation.maintenance_logs
GROUP BY vehicle_id
HAVING AVG(cost) > 300;

[User] Finally, restrict to vehicles that have at least 5 maintenance records.

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost, MAX(service_date) AS last_service_date, COUNT(*) AS service_count
FROM transportation.maintenance_logs
GROUP BY vehicle_id
HAVING AVG(cost) > 300 AND COUNT(*) >= 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)

[User] List all users whose usernames start with the letter 'B'.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username LIKE 'B%';

[User] Can you make it case-insensitive, so usernames starting with either upper or lower case 'b' are included?

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE username ILIKE 'b%';

[User] Instead of showing all details, just display the usernames in alphabetical order.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC;

[User] Limit the result to only the first 3 usernames.

[Assistant] SELECT username FROM trading_platform.users WHERE username ILIKE 'b%' ORDER BY username ASC LIMIT 3;

[User] How many users registered in 2024?

[Assistant] SELECT COUNT(*) FROM trading_platform.users WHERE DATE_PART('year', created_at) = 2024;

[User] Show me all users whose email address contains the word 'test', along with their user IDs and the date they registered.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%';

[User] Actually, only include users who registered after January 1, 2024, and sort them by newest registration date first.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%' AND created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Show the number of users registered each month for 2024.

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

[User] List the user IDs and usernames for all users who registered in the year 2024.

[Assistant] SELECT user_id, username FROM trading_platform.users WHERE created_at >= '2024-01-01 00:00:00' AND created_at < '2025-01-01 00:00:00';

[User] From that list, also filter to only include users whose username starts with 'alpha'.

[Assistant] SELECT user_id, username FROM trading_platform.users WHERE created_at >= '2024-01-01 00:00:00' AND created_at < '2025-01-01 00:00:00' AND username LIKE 'alpha%';

[User] Show the email address and the creation date for every user, ordered by their username alphabetically.

[Assistant] SELECT email, created_at FROM trading_platform.users ORDER BY username ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )

[User] Find pairs of players from the same country who have different last login dates. Show their usernames, country code, and last login dates. Exclude pairs where either last login date is null.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login;

[User] Filter the results to only include pairs where the last login date difference is more than 30 days.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400;

[User] Exclude pairs where the country code is NULL.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400 AND p1.country_code IS NOT NULL;

[User] Order the results by the country code and then by the larger of the two last login dates in descending order. Limit to the top 10 results.

[Assistant] SELECT p1.username AS player1_username, p2.username AS player2_username, p1.country_code, p1.last_login AS player1_last_login, p2.last_login AS player2_last_login FROM gaming_technology.players p1 JOIN gaming_technology.players p2 ON p1.country_code = p2.country_code AND p1.player_id < p2.player_id WHERE p1.last_login IS NOT NULL AND p2.last_login IS NOT NULL AND p1.last_login != p2.last_login AND ABS(EXTRACT(EPOCH FROM (p1.last_login - p2.last_login))) > 30 * 86400 AND p1.country_code IS NOT NULL ORDER BY p1.country_code, GREATEST(p1.last_login, p2.last_login) DESC LIMIT 10;

[User] How many players are registered for each country? Return the country_code and the player count.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY country_code;

[User] I only want to see countries where there are at least 3 players. Please also order the result by player_count descending.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] Remove countries where the country_code is NULL.

[Assistant] SELECT country_code, COUNT(*) AS player_count FROM gaming_technology.players WHERE country_code IS NOT NULL GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] Please also include the earliest registration_date for each country.

[Assistant] SELECT country_code, COUNT(*) AS player_count, MIN(registration_date) AS earliest_registration FROM gaming_technology.players WHERE country_code IS NOT NULL GROUP BY country_code HAVING COUNT(*) >= 3 ORDER BY player_count DESC;

[User] Show me all players who do not have a last_login recorded. List their player_id, username, and registration_date.

[Assistant] SELECT player_id, username, registration_date FROM gaming_technology.players WHERE last_login IS NULL;

[User] Additionally, include their email and country_code.

[Assistant] SELECT player_id, username, registration_date, email, country_code FROM gaming_technology.players WHERE last_login IS NULL;

[User] I only want players from the United States. Can you filter the list for country_code = 'US'?

[Assistant] SELECT player_id, username, registration_date, email, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'US';

[User] Please sort the list by registration_date in ascending order.

[Assistant] SELECT player_id, username, registration_date, email, country_code FROM gaming_technology.players WHERE last_login IS NULL AND country_code = 'US' ORDER BY registration_date ASC;

[User] List all players from 'Germany' whose status is currently 'online', and show their username and registration date.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE country_code = 'DE' AND status = 'online';

[User] Could you also add their email to the result and order the list by registration_date descending?

[Assistant] SELECT username, email, registration_date FROM gaming_technology.players WHERE country_code = 'DE' AND status = 'online' ORDER BY registration_date DESC;

[User] Show me the number of players who registered each year. List the registration year and the count.

[Assistant] SELECT EXTRACT(YEAR FROM registration_date) AS registration_year, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY registration_year ORDER BY registration_year;

[User] Now, filter that list to only show years where more than 50 players registered.

[Assistant] SELECT EXTRACT(YEAR FROM registration_date) AS registration_year, COUNT(*) AS player_count FROM gaming_technology.players GROUP BY EXTRACT(YEAR FROM registration_date) HAVING COUNT(*) > 50 ORDER BY registration_year;

[User] Also include the earliest and latest registration date for each of those years.

[Assistant] SELECT EXTRACT(YEAR FROM registration_date) AS registration_year, COUNT(*) AS player_count, MIN(registration_date) AS earliest_registration_date, MAX(registration_date) AS latest_registration_date FROM gaming_technology.players GROUP BY EXTRACT(YEAR FROM registration_date) HAVING COUNT(*) > 50 ORDER BY registration_year;

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

[Assistant] SELECT EXTRACT(YEAR FROM registration_date) AS registration_year, COUNT(*) AS player_count, MIN(registration_date) AS earliest_registration_date, MAX(registration_date) AS latest_registration_date FROM gaming_technology.players GROUP BY EXTRACT(YEAR FROM registration_date) HAVING COUNT(*) > 50 ORDER BY player_count DESC;

[User] Show the usernames and registration dates of all players whose last_login is NULL.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE last_login IS NULL;

[User] Please also show their country_code, and only include players who registered on or after 2023-01-01.

[Assistant] SELECT username, country_code, registration_date FROM gaming_technology.players WHERE last_login IS NULL AND registration_date >= '2023-01-01';

[User] Also, sort the players by username alphabetically.

[Assistant] SELECT username, country_code, registration_date FROM gaming_technology.players WHERE last_login IS NULL AND registration_date >= '2023-01-01' ORDER BY username ASC;

[User] Add the email field too, and exclude any players whose status is 'banned'.

[Assistant] SELECT username, email, country_code, registration_date FROM gaming_technology.players WHERE last_login IS NULL AND registration_date >= '2023-01-01' AND status <> 'banned' ORDER BY username ASC;


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

[User] For projects that have completed more than one fundraising round, calculate the average investment value across all their recorded rounds. Display the project name and this average value.

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1;

[User] Can you modify this to only show projects where the average investment value is greater than 10 million USD and order the results by average investment value descending?

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 AND AVG(investment_value) > 10000000 ORDER BY average_investment DESC;

[User] Which month in 2022 saw the highest total fundraising amount, and which project contributed the most to that month's total?

[Assistant]
WITH monthly_totals AS (
    SELECT
        to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM') AS month,
        SUM(investment_value) AS total_fundraising
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022-%'
    GROUP BY to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM')
),
highest_month AS (
    SELECT month
    FROM monthly_totals
    ORDER BY total_fundraising DESC
    LIMIT 1
),
project_contributions AS (
    SELECT
        to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM') AS month,
        project_name,
        investment_value
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022-%'
)
SELECT m.month, p.project_name, p.investment_value
FROM highest_month m
JOIN project_contributions p ON m.month = p.month
ORDER BY p.investment_value DESC
LIMIT 1;

[User] Can you show both the total fundraising for that month and the top project's contribution side by side?

[Assistant]
WITH monthly_totals AS (
    SELECT
        to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM') AS month,
        SUM(investment_value) AS total_fundraising
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022-%'
    GROUP BY to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM')
),
highest_month AS (
    SELECT month, total_fundraising
    FROM monthly_totals
    ORDER BY total_fundraising DESC
    LIMIT 1
),
project_contributions AS (
    SELECT
        to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM') AS month,
        project_name,
        investment_value
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022-%'
)
SELECT h.month, h.total_fundraising, p.project_name, p.investment_value AS top_project_contribution
FROM highest_month h
JOIN project_contributions p ON h.month = p.month
ORDER BY p.investment_value DESC
LIMIT 1;

[User] I got an error about the date conversion. Can you revise the query in case investment_date might already be in 'YYYY-MM' format sometimes?

[Assistant]
WITH monthly_totals AS (
    SELECT
        CASE
            WHEN length(investment_date) = 7 THEN investment_date
            ELSE to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM')
        END AS month,
        SUM(investment_value) AS total_fundraising
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022%'
    GROUP BY CASE
        WHEN length(investment_date) = 7 THEN investment_date
        ELSE to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM')
    END
),
highest_month AS (
    SELECT month, total_fundraising
    FROM monthly_totals
    ORDER BY total_fundraising DESC
    LIMIT 1
),
project_contributions AS (
    SELECT
        CASE
            WHEN length(investment_date) = 7 THEN investment_date
            ELSE to_char(to_date(investment_date, 'YYYY-MM-DD'), 'YYYY-MM')
        END AS month,
        project_name,
        investment_value
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022%'
)
SELECT h.month, h.total_fundraising, p.project_name, p.investment_value AS top_project_contribution
FROM highest_month h
JOIN project_contributions p ON h.month = p.month
ORDER BY p.investment_value DESC
LIMIT 1;

[User] Which fundraising round type had the highest total valuation across all projects, and which projects are in that round?

[Assistant]
WITH round_valuations AS (
    SELECT
        rounds_name,
        SUM(valuation) AS total_valuation
    FROM project_fundraising_record
    WHERE valuation IS NOT NULL
    GROUP BY rounds_name
),
max_round AS (
    SELECT rounds_name
    FROM round_valuations
    ORDER BY total_valuation DESC
    LIMIT 1
)
SELECT r.rounds_name, p.project_name, p.valuation
FROM max_round r
JOIN project_fundraising_record p ON r.rounds_name = p.rounds_name
WHERE p.valuation IS NOT NULL;

[User] Show the number of projects included in that round type as well.

[Assistant]
WITH round_valuations AS (
    SELECT
        rounds_name,
        SUM(valuation) AS total_valuation
    FROM project_fundraising_record
    WHERE valuation IS NOT NULL
    GROUP BY rounds_name
),
max_round AS (
    SELECT rounds_name
    FROM round_valuations
    ORDER BY total_valuation DESC
    LIMIT 1
)
SELECT r.rounds_name, COUNT(DISTINCT p.project_id) AS num_projects
FROM max_round r
JOIN project_fundraising_record p ON r.rounds_name = p.rounds_name
WHERE p.valuation IS NOT NULL;

[User] Now filter only to rounds where each project's valuation was at least $100 million.

[Assistant]
WITH round_valuations AS (
    SELECT
        rounds_name,
        SUM(valuation) AS total_valuation
    FROM project_fundraising_record
    WHERE valuation >= 100000000
    GROUP BY rounds_name
),
max_round AS (
    SELECT rounds_name
    FROM round_valuations
    ORDER BY total_valuation DESC
    LIMIT 1
)
SELECT r.rounds_name, COUNT(DISTINCT p.project_id) AS num_projects
FROM max_round r
JOIN project_fundraising_record p ON r.rounds_name = p.rounds_name
WHERE p.valuation >= 100000000;

[User] Can you also show the names and valuations of these projects in the output?

[Assistant]
WITH round_valuations AS (
    SELECT
        rounds_name,
        SUM(valuation) AS total_valuation
    FROM project_fundraising_record
    WHERE valuation >= 100000000
    GROUP BY rounds_name
),
max_round AS (
    SELECT rounds_name
    FROM round_valuations
    ORDER BY total_valuation DESC
    LIMIT 1
)
SELECT p.project_name, p.valuation, p.rounds_name
FROM max_round r
JOIN project_fundraising_record p ON r.rounds_name = p.rounds_name
WHERE p.valuation >= 100000000;

[User] List the total amount invested in each month of 2023.

[Assistant] SELECT SUBSTRING(investment_date, 1, 7) AS month, SUM(investment_value) AS total_invested FROM project_fundraising_record WHERE investment_date LIKE '2023%' GROUP BY SUBSTRING(investment_date, 1, 7) ORDER BY month;

[User] Now only show the months where total invested exceeded $20 million.

[Assistant] SELECT SUBSTRING(investment_date, 1, 7) AS month, SUM(investment_value) AS total_invested FROM project_fundraising_record WHERE investment_date LIKE '2023%' GROUP BY SUBSTRING(investment_date, 1, 7) HAVING SUM(investment_value) > 20000000 ORDER BY month;

[User] How many distinct fundraising round names are recorded in the table?

[Assistant] SELECT COUNT(DISTINCT rounds_name) FROM project_fundraising_record;

[User] Which projects had fundraising rounds in the first quarter of 2022, and what were their investment values and round names?

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-04-01';

[User] Add each project's valuation and introduction to the output as well.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, valuation, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-04-01';

[User] Now, show only those projects where the valuation was at least $200 million.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, valuation, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-04-01' AND valuation >= 200000000;

[User] Order the results by investment_value descending and limit to the top 5 records.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, valuation, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-04-01' AND valuation >= 200000000 ORDER BY investment_value DESC LIMIT 5;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.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] What is the average overall rating for each property?

[Assistant]
SELECT property_id, AVG(rating_overall) AS avg_rating
FROM hospitality_technology.reviews
GROUP BY property_id;

[User] Filter to properties with an average overall rating above 4.5 and sort by that average descending.

[Assistant]
SELECT property_id, AVG(rating_overall) AS avg_rating
FROM hospitality_technology.reviews
GROUP BY property_id
HAVING AVG(rating_overall) > 4.5
ORDER BY avg_rating DESC;

[User] Show me the property_id and property_name along with the average overall rating for public reviews.

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

[User] Also include the number of public reviews for each property.

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

[User] Only display properties with an average rating of 4.5 or higher and at least 100 public reviews, sorted by average rating descending.

[Assistant]
SELECT p.property_id, p.property_name, AVG(r.rating_overall) AS avg_rating, COUNT(*) AS public_review_count
FROM hospitality_technology.reviews r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.is_public = true
GROUP BY p.property_id, p.property_name
HAVING AVG(r.rating_overall) >= 4.5 AND COUNT(*) >= 100
ORDER BY avg_rating DESC;

[User] Show me the review_id, review_date, and comment for all non-public reviews along with the guest's first and last name.

[Assistant]
SELECT r.review_id, r.review_date, r.comment, g.first_name, g.last_name
FROM hospitality_technology.reviews r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
WHERE r.is_public = false;

[User] Actually, only include those reviews where the staff has responded and include the staff member's full name and response_date.

[Assistant]
SELECT r.review_id, r.review_date, r.comment, g.first_name, g.last_name, s.first_name AS resp_first_name, s.last_name AS resp_last_name, r.response_date
FROM hospitality_technology.reviews r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.staff s ON r.response_staff_id = s.staff_id
WHERE r.is_public = false
  AND r.staff_response IS NOT NULL;

[User] Identify all pairs of reviews where the same guest reviewed the same property twice, listing both review IDs.

[Assistant]
SELECT
  r1.guest_id,
  r1.property_id,
  r1.review_id AS review_a,
  r2.review_id AS review_b
FROM hospitality_technology.reviews r1
JOIN hospitality_technology.reviews r2
  ON r1.guest_id = r2.guest_id
  AND r1.property_id = r2.property_id
  AND r1.review_id < r2.review_id;

[User] Only include pairs where the two reviews were submitted within 30 days of each other.

[Assistant]
SELECT
  r1.guest_id,
  r1.property_id,
  r1.review_id AS review_a,
  r2.review_id AS review_b
FROM hospitality_technology.reviews r1
JOIN hospitality_technology.reviews r2
  ON r1.guest_id = r2.guest_id
  AND r1.property_id = r2.property_id
  AND r1.review_id < r2.review_id
  AND ABS(EXTRACT(EPOCH FROM (r2.review_date - r1.review_date)) / 86400) <= 30;

[User] Also include a column called review_gap_days that shows the number of days between the two review dates (rounded to two decimals).

[Assistant]
SELECT
  r1.guest_id,
  r1.property_id,
  r1.review_id AS review_a,
  r2.review_id AS review_b,
  ROUND(ABS(EXTRACT(EPOCH FROM (r2.review_date - r1.review_date))) / 86400, 2) AS review_gap_days
FROM hospitality_technology.reviews r1
JOIN hospitality_technology.reviews r2
  ON r1.guest_id = r2.guest_id
  AND r1.property_id = r2.property_id
  AND r1.review_id < r2.review_id
  AND ABS(EXTRACT(EPOCH FROM (r2.review_date - r1.review_date)) / 86400) <= 30;

[User] For each review, show me the comment, the review date, and the full name of the staff member who responded to the review, if there is a response.

[Assistant]
SELECT r.review_id, r.comment, r.review_date, s.first_name || ' ' || s.last_name AS staff_full_name
FROM hospitality_technology.reviews r
LEFT JOIN hospitality_technology.staff s ON r.response_staff_id = s.staff_id;

[User] Only show reviews that have a staff response and also include the response date.

[Assistant]
SELECT r.review_id, r.comment, r.review_date, s.first_name || ' ' || s.last_name AS staff_full_name, r.response_date
FROM hospitality_technology.reviews r
JOIN hospitality_technology.staff s ON r.response_staff_id = s.staff_id
WHERE r.staff_response IS NOT NULL;

[User] How many reviews were posted by each guest? Show the guest ID and the count of reviews.

[Assistant]
SELECT guest_id, COUNT(*) AS review_count
FROM hospitality_technology.reviews
GROUP BY guest_id;

[User] Filter to only include guests who have posted at least 3 reviews.

[Assistant]
SELECT guest_id, COUNT(*) AS review_count
FROM hospitality_technology.reviews
GROUP BY guest_id
HAVING COUNT(*) >= 3;

[User] Also, for these guests, list their most recent review date.

[Assistant]
SELECT guest_id, COUNT(*) AS review_count, MAX(review_date) AS latest_review_date
FROM hospitality_technology.reviews
GROUP BY guest_id
HAVING COUNT(*) >= 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] Show the latest time each player acquired any item.

[Assistant] SELECT player_id, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id;

[User] Actually, can you also show the total number of items that each player acquired?

[Assistant] SELECT player_id, MAX(acquired_at) AS last_acquired_at, SUM(quantity) AS total_items_acquired FROM gaming_technology.player_inventory GROUP BY player_id;

[User] I would also like this ordered by total_items_acquired descending.

[Assistant] SELECT player_id, MAX(acquired_at) AS last_acquired_at, SUM(quantity) AS total_items_acquired FROM gaming_technology.player_inventory GROUP BY player_id ORDER BY total_items_acquired DESC;

[User] For each item, can you show the total quantity held by all players and the most recent acquisition date for that item?

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

[User] Please only show items where total_quantity is at least 50.

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

[User] Can you also sort the result by total_quantity in descending order?

[Assistant]
SELECT item_id, SUM(quantity) AS total_quantity, MAX(acquired_at) AS last_acquired_at
FROM gaming_technology.player_inventory
GROUP BY item_id
HAVING SUM(quantity) >= 50
ORDER BY total_quantity DESC;

[User] Can you show the total quantity of all in-game items held by each player?

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

[User] I'd like to see only players whose total quantity is over 20.

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

[User] Also, can you include the number of different unique items each player owns?

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

[User] Order the final result by unique_items descending, then by total_quantity descending.

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

[User] Can you show me the total number of each item acquired by every player, along with their player_id and item_id?

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

[User] I think I also need the most recent acquisition timestamp for each player and item combination.

[Assistant] SELECT player_id, item_id, SUM(quantity) AS total_acquired, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id, item_id;

[User] Can you only include combinations where total_acquired is greater than 3?

[Assistant] SELECT player_id, item_id, SUM(quantity) AS total_acquired, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id, item_id HAVING SUM(quantity) > 3;

[User] Also, please order the results by last_acquired_at descending.

[Assistant] SELECT player_id, item_id, SUM(quantity) AS total_acquired, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id, item_id HAVING SUM(quantity) > 3 ORDER BY last_acquired_at DESC;

[User] What is the count of unique items acquired on each day?

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at);

[User] Only show days where more than 10 unique items were acquired.

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at) HAVING COUNT(DISTINCT item_id) > 10;

[User] Also include the total quantity of items acquired on those days.

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count, SUM(quantity) AS total_quantity FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at) HAVING COUNT(DISTINCT item_id) > 10;

[User] Order the results by the total quantity in descending order.

[Assistant] SELECT DATE(acquired_at) AS acquisition_date, COUNT(DISTINCT item_id) AS unique_item_count, SUM(quantity) AS total_quantity FROM gaming_technology.player_inventory GROUP BY DATE(acquired_at) HAVING COUNT(DISTINCT item_id) > 10 ORDER BY total_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )

[User] Show me the earliest created smart contract for each creator address.

[Assistant] SELECT DISTINCT ON (creator_address) contract_id, creator_address, code, timestamp FROM blockchain.smart_contracts ORDER BY creator_address, timestamp ASC;

[User] Now include the total number of contracts each creator has made alongside this information.

[Assistant] WITH earliest_contracts AS (SELECT DISTINCT ON (creator_address) contract_id, creator_address, code, timestamp FROM blockchain.smart_contracts ORDER BY creator_address, timestamp ASC) SELECT ec.*, (SELECT COUNT(*) FROM blockchain.smart_contracts sc WHERE sc.creator_address = ec.creator_address) AS total_contracts FROM earliest_contracts ec;

[User] Filter this to only show creators who have made at least 10 contracts.

[Assistant] WITH earliest_contracts AS (SELECT DISTINCT ON (creator_address) contract_id, creator_address, code, timestamp FROM blockchain.smart_contracts ORDER BY creator_address, timestamp ASC) SELECT ec.*, (SELECT COUNT(*) FROM blockchain.smart_contracts sc WHERE sc.creator_address = ec.creator_address) AS total_contracts FROM earliest_contracts ec WHERE (SELECT COUNT(*) FROM blockchain.smart_contracts sc WHERE sc.creator_address = ec.creator_address) >= 10;

[User] Find all smart contracts where the contract code contains the keyword 'proxy'.

[Assistant] SELECT contract_id, creator_address, timestamp FROM blockchain.smart_contracts WHERE code LIKE '%proxy%';

[User] For these 'proxy' contracts, can you also include the total number of contracts deployed by each creator?

[Assistant] SELECT sc.contract_id, sc.creator_address, sc.timestamp, creator_counts.total_contracts FROM blockchain.smart_contracts sc JOIN ( SELECT creator_address, COUNT(*) as total_contracts FROM blockchain.smart_contracts GROUP BY creator_address ) creator_counts ON sc.creator_address = creator_counts.creator_address WHERE sc.code LIKE '%proxy%';

[User] I want to know how many times each smart contract has been invoked by transactions; also include the contract creator.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address;

[User] I'd like to see only contracts with more than 100 invocations.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address
HAVING COUNT(t.transaction_id) > 100;

[User] Actually, I want to order them by invocation_count descending and limit to the top 5.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address
HAVING COUNT(t.transaction_id) > 100
ORDER BY invocation_count DESC
LIMIT 5;

[User] Also, show the timestamp when each of those top 5 contracts was created.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp AS creation_time, COUNT(t.transaction_id) AS invocation_count
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
GROUP BY sc.contract_id, sc.creator_address, sc.timestamp
HAVING COUNT(t.transaction_id) > 100
ORDER BY invocation_count DESC
LIMIT 5;

[User] Find all smart contracts deployed in 2022 that have never received any transactions.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp AS deployment_time
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
WHERE sc.timestamp >= '2022-01-01' AND sc.timestamp < '2023-01-01'
  AND t.transaction_id IS NULL;

[User] Show me all smart contracts created by addresses that have created more than 3 contracts, along with the total number of contracts each creator has made.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(*) OVER (PARTITION BY sc.creator_address) AS total_contracts
FROM blockchain.smart_contracts sc
WHERE sc.creator_address IN (
    SELECT creator_address
    FROM blockchain.smart_contracts
    GROUP BY creator_address
    HAVING COUNT(*) > 3
)
ORDER BY total_contracts DESC;

[User] Now filter these results to only show contracts created in the last 6 months.

[Assistant]
SELECT sc.contract_id, sc.creator_address, COUNT(*) OVER (PARTITION BY sc.creator_address) AS total_contracts
FROM blockchain.smart_contracts sc
WHERE sc.creator_address IN (
    SELECT creator_address
    FROM blockchain.smart_contracts
    GROUP BY creator_address
    HAVING COUNT(*) > 3
)
AND sc.timestamp >= NOW() - INTERVAL '6 months'
ORDER BY total_contracts DESC;

[User] Show me all smart contracts created by addresses with a balance greater than 1000, along with the contract creation timestamp and the creator's public key.

[Assistant] SELECT sc.contract_id, sc.timestamp, a.public_key FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id WHERE a.balance > 1000;

[User] Now filter these results to only show contracts created in the last 6 months and order them by timestamp in descending order.

[Assistant] SELECT sc.contract_id, sc.timestamp, a.public_key FROM blockchain.smart_contracts sc JOIN blockchain.addresses a ON sc.creator_address = a.address_id WHERE a.balance > 1000 AND sc.timestamp > NOW() - INTERVAL '6 months' ORDER BY sc.timestamp 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 legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )

[User] Please list the full name and status of clients who have not provided a company name.

[Assistant]
SELECT first_name, last_name, status
FROM legal_services.clients
WHERE company_name IS NULL;

[User] Can you show me the company name, email, and phone of all clients who share the same status?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id;

[User] What if I only want to see those clients who registered before January 1st, 2023?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01';

[User] Please add each client's first and last name, and sort the results by company_name.

[Assistant]
SELECT a.first_name, a.last_name, a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01'
ORDER BY a.company_name;

[User] I need a list of unique company names and the number of clients in each company.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name;

[User] Only include companies where there are at least 2 clients.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name
HAVING COUNT(*) >= 2;

[User] Also, show the email addresses of the clients in those companies.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] Only show companies whose name contains the word 'Group'.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL AND company_name ILIKE '%Group%'
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] List all pairs of clients who registered in the same year. Show each client's first_name, last_name, and the registration year.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id;

[User] Actually, only include clients with status = 'active'.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active';

[User] Also, sort the results by registration_year descending and then by the first client's last_name ascending.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active' ORDER BY registration_year DESC, last_name_1 ASC;

[User] List the first_name, last_name, and email of all clients whose email domain is 'gmail.com'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE SUBSTRING(email FROM POSITION('@' IN email) + 1) = 'gmail.com';

[User] List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Show me the incident date, estimated loss, and the associated product name for all claims with an estimated loss greater than 20000.

[Assistant]
SELECT c.incident_date, c.estimated_loss, p.product_name
FROM insurance.claims c
JOIN insurance.policies pol ON c.policy_id = pol.policy_id
JOIN insurance.insurance_products p ON pol.product_id = p.product_id
WHERE c.estimated_loss > 20000;

[User] List all insurance products along with their product type and creation date.

[Assistant]
SELECT product_name, product_type, created_at
FROM insurance.insurance_products;

[User] Show me claim IDs and the file names of any documents associated with claims filed before January 1, 2024.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01';

[User] Only include documents where the file size is less than 1 MB.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576;

[User] Add the document type to the results and sort by file size ascending.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

[User] Sorry, I got an error about NULL file sizes. Please exclude records where the file size is NULL.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes IS NOT NULL
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

[User] How many claims were reported in the last 90 days?

[Assistant] SELECT COUNT(*) FROM claims WHERE reported_date >= CURRENT_DATE - INTERVAL '90 days'

[User] List all policies that have at least one beneficiary with a 'Child' relationship, showing policy number, policy status, and the number of child beneficiaries for that policy.

[Assistant] SELECT T1.policy_number, T1.status, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status HAVING COUNT(T2.beneficiary_id) >= 1

[User] Can you also include the total premium amount for these policies?

[Assistant] SELECT T1.policy_number, T1.status, T1.premium_amount, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status, T1.premium_amount HAVING COUNT(T2.beneficiary_id) >= 1

[User] Show all policies that started before January 1, 2022, including policy_id, policy_number, start_date, and status.

[Assistant]
SELECT policy_id, policy_number, start_date, status
FROM insurance.policies
WHERE start_date < '2022-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)

[User] For each sector, retrieve the ticker symbol and last_updated timestamp of the earliest and latest updated securities, labeling them as earliest_ticker, earliest_updated, latest_ticker, and latest_updated.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated;

[User] Actually, only include sectors where the time span between latest_updated and earliest_updated exceeds 30 days.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
  HAVING MAX(last_updated) - MIN(last_updated) > INTERVAL '30 days'
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated;

[User] Now order the results by the time span descending.

[Assistant]
WITH sector_stats AS (
  SELECT
    sector,
    MIN(last_updated) AS earliest_updated,
    MAX(last_updated) AS latest_updated
  FROM financial_services.securities
  GROUP BY sector
  HAVING MAX(last_updated) - MIN(last_updated) > INTERVAL '30 days'
)
SELECT
  ss.sector,
  s_min.ticker_symbol AS earliest_ticker,
  ss.earliest_updated,
  s_max.ticker_symbol AS latest_ticker,
  ss.latest_updated,
  ss.latest_updated - ss.earliest_updated AS time_span
FROM sector_stats ss
LEFT JOIN financial_services.securities s_min
  ON s_min.sector = ss.sector
  AND s_min.last_updated = ss.earliest_updated
LEFT JOIN financial_services.securities s_max
  ON s_max.sector = ss.sector
  AND s_max.last_updated = ss.latest_updated
ORDER BY time_span DESC;

[User] List pairs of securities that trade on different exchanges but belong to the same sector, showing ticker_symbol of both as symbol_a and symbol_b, their exchanges, and the sector.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.ticker_symbol < b.ticker_symbol;

[User] Actually, exclude any pairs where the sector is NULL and ensure uniqueness by requiring symbol_a < symbol_b.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.ticker_symbol < b.ticker_symbol;

[User] Now also order the results by sector ascending and symbol_a ascending.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.ticker_symbol < b.ticker_symbol
ORDER BY a.sector ASC, a.ticker_symbol ASC;

[User] Finally, only include pairs where both securities are denominated in USD.

[Assistant]
SELECT a.ticker_symbol AS symbol_a, a.exchange AS exchange_a, b.ticker_symbol AS symbol_b, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b
  ON a.sector = b.sector
  AND a.exchange <> b.exchange
WHERE a.sector IS NOT NULL
  AND a.currency = 'USD'
  AND b.currency = 'USD'
  AND a.ticker_symbol < b.ticker_symbol
ORDER BY a.sector ASC, a.ticker_symbol ASC;

[User] Show the number of securities per exchange and the average length of their ticker symbols, including only exchanges that have more than 5 securities.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
GROUP BY exchange
HAVING COUNT(*) > 5;

[User] Actually, exclude any entries where exchange is NULL.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
WHERE exchange IS NOT NULL
GROUP BY exchange
HAVING COUNT(*) > 5;

[User] Also, sort the output by the securities_count in descending order.

[Assistant]
SELECT exchange, COUNT(*) AS securities_count, AVG(LENGTH(ticker_symbol)) AS avg_ticker_length
FROM financial_services.securities
WHERE exchange IS NOT NULL
GROUP BY exchange
HAVING COUNT(*) > 5
ORDER BY securities_count DESC;

[User] List the ticker_symbol and average close price for all securities of type 'ETF'.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol;

[User] Sort the result by average close price descending.

[Assistant]
SELECT s.ticker_symbol, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.security_type = 'ETF'
GROUP BY s.ticker_symbol
ORDER BY avg_close_price DESC;

[User] Show me all securities listed on the 'NYSE' exchange with their ticker symbol and most recent close price.

[Assistant]
SELECT s.security_name, s.ticker_symbol, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE' AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
);

[User] Only include securities where the close price is below 30.

[Assistant]
SELECT s.security_name, s.ticker_symbol, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE'
  AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
  )
  AND md.close_price < 30;

[User] Please add the sector information to the result as well.

[Assistant]
SELECT s.security_name, s.ticker_symbol, s.sector, md.close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
WHERE s.exchange = 'NYSE'
  AND md.data_timestamp = (
    SELECT MAX(md2.data_timestamp)
    FROM financial_services.market_data md2
    WHERE md2.security_id = s.security_id
  )
  AND md.close_price < 30;

[User] Show me all securities (security_id, ticker_symbol, security_name) that are traded on the NASDAQ exchange and belong to the 'Technology' sector, along with the employees (employee_id, first_name, last_name) who work in the 'Investment' department and were hired in the last 3 years.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, e.employee_id, e.first_name, e.last_name FROM financial_services.securities s CROSS JOIN financial_services.employees e WHERE s.exchange = 'NASDAQ' AND s.sector = 'Technology' AND e.department = 'Investment' AND e.hire_date >= CURRENT_DATE - INTERVAL '3 years' AND e.status = 'Active';

[User] Now modify the query to only include securities with a ticker_symbol starting with 'A' and sort the results by security_name in ascending order.

[Assistant] SELECT s.security_id, s.ticker_symbol, s.security_name, e.employee_id, e.first_name, e.last_name FROM financial_services.securities s CROSS JOIN financial_services.employees e WHERE s.exchange = 'NASDAQ' AND s.sector = 'Technology' AND s.ticker_symbol LIKE 'A%' AND e.department = 'Investment' AND e.hire_date >= CURRENT_DATE - INTERVAL '3 years' AND e.status = 'Active' ORDER BY s.security_name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] List the names of services that have been scheduled at accessible service locations.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN government_services.appointments AS T2 ON T1.service_id = T2.service_id JOIN government_services.service_locations AS T3 ON T2.location_id = T3.location_id WHERE T3.is_accessible = TRUE

[User] Now, only include services from agencies with 'State' jurisdiction level.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN government_services.appointments AS T2 ON T1.service_id = T2.service_id JOIN government_services.service_locations AS T3 ON T2.location_id = T3.location_id JOIN government_services.agencies AS T4 ON T1.agency_id = T4.agency_id WHERE T3.is_accessible = TRUE AND T4.jurisdiction_level = 'State'


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
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)

[User] Can you retrieve the total number of train cars for each train in the database?

[Assistant]
MATCH (t:Train)<-[:PART_OF_TRAIN]-(tc:TrainCar)
RETURN t.train_id, t.train_number, COUNT(tc) AS total_cars
ORDER BY t.train_id

[User] Can you help me find all bookings made by passengers from a specific city, say 'Boston', including the passenger details and the scheduled trip information?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, st.schedule_id

[User] Can you modify the query to include only bookings with a status of 'Confirmed'?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, st.schedule_id

[User] Can you also add the total price of each booking to the result?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, b.total_price, st.schedule_id

[User] Can you sort the results by booking datetime in ascending order?

[Assistant]
MATCH (p:Passenger)-[:MADE_BOOKING]->(b:Booking)-[:FOR_TRIP]->(st:ScheduledTrip)
MATCH (p)-[:BASED_AT]->(s:Station)
WHERE s.city = 'Boston' AND b.status = 'Confirmed'
RETURN p.passenger_id, p.first_name, p.last_name, b.booking_id, b.booking_datetime, b.status, b.total_price, st.schedule_id
ORDER BY b.booking_datetime ASC

[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff

[User] Can you help me find all staff members based at a specific station with station_id 'station_xyz', including the station details and platform information they are associated with?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you filter the results to include only staff with the role of 'Manager' and platforms with status 'Operational'?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you sort the results by staff last name and platform number?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status
ORDER BY stf.last_name, p.platform_number

[User] Can you provide the total number of maintenance records for a specific train with train_id 'train_789'?

[Assistant]
MATCH (t:Train {train_id: 'train_789'})<-[:PERFORMED_ON]-(mr:MaintenanceRecord)
RETURN COUNT(mr) AS total_maintenance_records


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
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 )

[User] Show me the total number of players who have unlocked at least one achievement on each server, along with the server name and game title.

[Assistant]
SELECT s.server_id, s.server_name, s.game_id, COUNT(DISTINCT pa.player_id) AS total_players
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id AND pa.achievement_id IS NOT NULL AND gs.server_id IS NOT NULL
JOIN gaming_technology.servers s ON gs.server_id = s.server_id
GROUP BY s.server_id, s.server_name, s.game_id;

[User] Can you also include each server's current_players and status in the result?

[Assistant]
SELECT s.server_id, s.server_name, s.game_id, s.current_players, s.status, COUNT(DISTINCT pa.player_id) AS total_players
FROM gaming_technology.player_achievements pa
JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id AND pa.achievement_id IS NOT NULL AND gs.server_id IS NOT NULL
JOIN gaming_technology.servers s ON gs.server_id = s.server_id
GROUP BY s.server_id, s.server_name, s.game_id, s.current_players, s.status;

[User] Give me a list of developers and how many unique games they have created. Show developer name and total_games.

[Assistant]
SELECT d.name AS developer_name, COUNT(DISTINCT g.game_id) AS total_games
FROM gaming_technology.developers d
LEFT JOIN gaming_technology.games g ON d.developer_id = g.developer_id
GROUP BY d.developer_id, d.name;

[User] Oops, it says table 'gaming_technology.games' does not exist. Please adjust the SQL to just show information about the developers.

[Assistant]
SELECT name AS developer_name, country, founded_year
FROM gaming_technology.developers;

[User] I only want to see developers founded after 2015.

[Assistant]
SELECT name AS developer_name, country, founded_year
FROM gaming_technology.developers
WHERE founded_year > 2015;

[User] Also include the website column, and order by founded_year descending.

[Assistant]
SELECT name AS developer_name, country, founded_year, website
FROM gaming_technology.developers
WHERE founded_year > 2015
ORDER BY founded_year DESC;

[User] List all items of type 'Armor' in the database, showing the item name, rarity, and their corresponding game_id.

[Assistant]
SELECT item_id, item_name, rarity, game_id
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor';

[User] Please also show their cost_amount and cost_currency.

[Assistant]
SELECT item_id, item_name, rarity, game_id, cost_amount, cost_currency
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor';

[User] Now only include results where the cost_amount is at least 500.

[Assistant]
SELECT item_id, item_name, rarity, game_id, cost_amount, cost_currency
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor' AND cost_amount >= 500;

[User] Order the items by cost_amount in descending order.

[Assistant]
SELECT item_id, item_name, rarity, game_id, cost_amount, cost_currency
FROM gaming_technology.in_game_items
WHERE item_type = 'Armor' AND cost_amount >= 500
ORDER BY cost_amount DESC;

[User] Show the usernames of players and a count of how many different item types they have in their inventory.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username;

[User] Only include players who have 3 or more different item types.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3;

[User] Order the results by the count of unique item types in descending order.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3 ORDER BY count(DISTINCT T3.item_type) DESC;

[User] For these players, could you also show the total quantity of all items they possess?

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type), sum(T2.quantity) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3 ORDER BY count(DISTINCT T3.item_type) DESC;

[User] List the names and types of all in-game items that have a rarity of 'Epic'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic';

[User] Further restrict the list to only include items of item_type 'Weapon'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon';

[User] Order these results by their cost_amount in descending order.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Please also include the cost_currency and cost_amount in the output.

[Assistant] SELECT item_name, item_type, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Show for each player the total score achieved in sessions on each server, and the number of sessions per server.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] Now also include the maximum duration of any session that player has had on that server.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] For each player-server pair, include the average session duration as well.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration, AVG(duration_seconds) AS avg_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id;

[User] Finally, only include player-server pairs where the session_count is at least 5.

[Assistant]
SELECT player_id, server_id, SUM(score) AS total_score, COUNT(*) AS session_count, MAX(duration_seconds) AS max_session_duration, AVG(duration_seconds) AS avg_session_duration
FROM gaming_technology.game_sessions
GROUP BY player_id, server_id
HAVING COUNT(*) >= 5;