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.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )

[User] Which customers have made more than three premium payments in 2024? Show the customer_id and the number of payments.

[Assistant] SELECT customer_id, COUNT(*) AS payment_count FROM insurance.premium_payments WHERE payment_date >= '2024-01-01' AND payment_date < '2025-01-01' GROUP BY customer_id HAVING COUNT(*) > 3;

[User] Include only those payments where the status is 'completed'.

[Assistant] SELECT customer_id, COUNT(*) AS payment_count FROM insurance.premium_payments WHERE payment_date >= '2024-01-01' AND payment_date < '2025-01-01' AND status = 'completed' GROUP BY customer_id HAVING COUNT(*) > 3;

[User] Show me the total paid amount and the number of premium payments per customer for policies that have at least one payment over $5000.

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) GROUP BY customer_id;

[User] Can you also include the earliest payment date for each customer in the result?

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count, MIN(payment_date) AS earliest_payment_date FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) GROUP BY customer_id;

[User] Now restrict this to only show customers who have made payments using the 'bank transfer' method.

[Assistant] SELECT customer_id, SUM(amount_paid) AS total_paid, COUNT(*) AS payment_count, MIN(payment_date) AS earliest_payment_date FROM insurance.premium_payments WHERE policy_id IN (SELECT policy_id FROM insurance.premium_payments WHERE amount_paid > 5000) AND payment_method = 'bank transfer' GROUP BY customer_id;

[User] For each policy, find the latest payment date. Show the policy_id and the maximum payment_date.

[Assistant] SELECT policy_id, MAX(payment_date) AS latest_payment_date FROM insurance.premium_payments GROUP BY policy_id;

[User] Restrict the results to only show policies where the latest payment date was before '2024-01-01'.

[Assistant] SELECT policy_id, MAX(payment_date) AS latest_payment_date FROM insurance.premium_payments GROUP BY policy_id HAVING MAX(payment_date) < '2024-01-01';

[User] List all premium payments with a due date in March 2024.

[Assistant] SELECT * FROM insurance.premium_payments WHERE due_date >= '2024-03-01' AND due_date <= '2024-03-31';

[User] Count the number of completed premium payments grouped by payment_method.

[Assistant]
SELECT payment_method,
       COUNT(*) AS payment_count
FROM insurance.premium_payments
WHERE status = 'Completed'
GROUP BY payment_method;

[User] List all premium payments that have a status of 'pending'. Show the payment_id, policy_id, customer_id, and amount_paid.

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

[User] What is the total amount paid by each customer? Show the customer_id and the sum of amount_paid.

[Assistant] SELECT customer_id, SUM(amount_paid) FROM insurance.premium_payments GROUP BY customer_id;

[User] Could you refine that to only include payments made in the year 2023?

[Assistant] SELECT customer_id, SUM(amount_paid) FROM insurance.premium_payments WHERE EXTRACT(YEAR FROM payment_date) = 2023 GROUP BY customer_id;

[User] Now, only show the customers whose total amount paid in 2023 was greater than 5000.

[Assistant] SELECT customer_id, SUM(amount_paid) FROM insurance.premium_payments WHERE EXTRACT(YEAR FROM payment_date) = 2023 GROUP BY customer_id HAVING SUM(amount_paid) > 5000;

[User] For each customer, calculate the average number of days between their consecutive premium payments.

[Assistant]
SELECT t.customer_id,
       AVG(t.days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
) AS t
GROUP BY t.customer_id;

[User] Exclude any payments that are not 'Completed'.

[Assistant]
SELECT t.customer_id,
       AVG(t.days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY t.customer_id;

[User] Only include customers whose average days between payments is greater than 30 and show that value.

[Assistant]
SELECT customer_id,
       AVG(days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY customer_id
HAVING AVG(days_diff) > 30;

[User] Limit the result to the top 5 customers by average days between payments in descending order.

[Assistant]
SELECT customer_id,
       AVG(days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY customer_id
HAVING AVG(days_diff) > 30
ORDER BY avg_days_between DESC
LIMIT 5;

[User] Show the customer_id and pairs of payment_ids for any customers who have overlapping payment periods.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS payment1_id,
       p2.payment_id AS payment2_id
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
 AND p1.payment_id < p2.payment_id
 AND p1.payment_period_start <= p2.payment_period_end
 AND p1.payment_period_end   >= p2.payment_period_start;

[User] Show me all premium payments made by customer with ID 'CUST789'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789';

[User] From those payments, only include the ones with status 'Completed'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed';

[User] Also, filter the results to only show payments made between '2023-01-01' and '2023-12-31'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Okay, instead of all columns, just show the policy ID, payment date, and amount paid, ordered by payment date descending.

[Assistant] SELECT policy_id, payment_date, amount_paid FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31' ORDER BY payment_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.developers ( developer_id uuid NOT NULL DEFAULT gen_random_uuid(), name character varying(150) NOT NULL UNIQUE, country character varying(100), founded_year integer, website character varying(255), created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (developer_id) )
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, name character varying(150) NOT NULL, description text NOT NULL, icon_url character varying(255), points integer DEFAULT 0, hidden boolean DEFAULT false, PRIMARY KEY (achievement_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] Count how many achievements were unlocked on each calendar day. Show the date and the count.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count FROM gaming_technology.player_achievements GROUP BY unlock_date;

[User] Only include dates where more than 50 achievements were unlocked.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50;

[User] Additionally, include the number of *distinct players* who unlocked achievements on each of those dates.

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count, COUNT(DISTINCT player_id) AS distinct_players FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50;

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

[Assistant] SELECT DATE(unlocked_at) AS unlock_date, COUNT(*) AS achievement_count, COUNT(DISTINCT player_id) AS distinct_players FROM gaming_technology.player_achievements GROUP BY unlock_date HAVING COUNT(*) > 50 ORDER BY distinct_players DESC;

[User] For each player, show the player_id and the count of inventory items they acquired with a quantity greater than 1.

[Assistant] SELECT player_id, COUNT(inventory_id) AS items_qty_gt_1_count FROM gaming_technology.player_inventory WHERE quantity > 1 GROUP BY player_id;

[User] I want the number of achievements unlocked per country_code by active players, showing only countries with at least 100 unlocks.

[Assistant]
SELECT p.country_code, COUNT(*) AS unlock_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
WHERE p.status = 'active'
GROUP BY p.country_code
HAVING COUNT(*) >= 100;

[User] Please exclude entries where country_code is NULL and sort the output by unlock_count descending.

[Assistant]
SELECT p.country_code, COUNT(*) AS unlock_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
WHERE p.status = 'active'
  AND p.country_code IS NOT NULL
GROUP BY p.country_code
HAVING COUNT(*) >= 100
ORDER BY unlock_count DESC;

[User] For each game, count the total number of achievements unlocked across all players. Show game title and count.

[Assistant] SELECT g.title, COUNT(pa.player_achievement_id) AS total_unlocked_achievements FROM gaming_technology.games AS g JOIN gaming_technology.achievements AS a ON g.game_id = a.game_id JOIN gaming_technology.player_achievements AS pa ON a.achievement_id = pa.achievement_id GROUP BY g.title;

[User] Only include games that have more than 100 achievements unlocked.

[Assistant] SELECT g.title, COUNT(pa.player_achievement_id) AS total_unlocked_achievements FROM gaming_technology.games AS g JOIN gaming_technology.achievements AS a ON g.game_id = a.game_id JOIN gaming_technology.player_achievements AS pa ON a.achievement_id = pa.achievement_id GROUP BY g.title HAVING COUNT(pa.player_achievement_id) > 100;

[User] For these games, also show the number of servers hosting that game.

[Assistant] SELECT g.title, COUNT(pa.player_achievement_id) AS total_unlocked_achievements, COUNT(s.server_id) AS server_count FROM gaming_technology.games AS g JOIN gaming_technology.achievements AS a ON g.game_id = a.game_id JOIN gaming_technology.player_achievements AS pa ON a.achievement_id = pa.achievement_id LEFT JOIN gaming_technology.servers AS s ON g.game_id = s.game_id GROUP BY g.title HAVING COUNT(pa.player_achievement_id) > 100;

[User] Count the number of servers for each possible status recorded in the servers table.

[Assistant] SELECT status, COUNT(server_id) AS server_count FROM gaming_technology.servers GROUP BY status;

[User] Only include statuses where the server count is greater than 5.

[Assistant] SELECT status, COUNT(server_id) AS server_count FROM gaming_technology.servers GROUP BY status HAVING COUNT(server_id) > 5;

[User] For those filtered statuses, calculate the total number of current players across the servers in each status group.

[Assistant] SELECT status, COUNT(server_id) AS server_count, SUM(current_players) AS total_current_players FROM gaming_technology.servers GROUP BY status HAVING COUNT(server_id) > 5;

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

[Assistant] SELECT status, COUNT(server_id) AS server_count, SUM(current_players) AS total_current_players FROM gaming_technology.servers GROUP BY status HAVING COUNT(server_id) > 5 ORDER BY total_current_players DESC;

[User] Retrieve the title and release_date of all games on the 'PC' platform.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC';

[User] Now exclude any games released before 2018.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01';

[User] Also sort the results by release_date in ascending order.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01'
ORDER BY release_date ASC;

[User] Calculate the total points from all achievements unlocked by each player. Show player_id and total points.

[Assistant] SELECT pa.player_id, SUM(a.points) AS total_points FROM gaming_technology.player_achievements AS pa JOIN gaming_technology.achievements AS a ON pa.achievement_id = a.achievement_id GROUP BY pa.player_id;

[User] Only include players whose total points are greater than 500.

[Assistant] SELECT pa.player_id, SUM(a.points) AS total_points FROM gaming_technology.player_achievements AS pa JOIN gaming_technology.achievements AS a ON pa.achievement_id = a.achievement_id GROUP BY pa.player_id HAVING SUM(a.points) > 500;

[User] Now, also include the player's username and order the results by total_points in descending order.

[Assistant] SELECT p.username, pa.player_id, SUM(a.points) AS total_points FROM gaming_technology.player_achievements AS pa JOIN gaming_technology.achievements AS a ON pa.achievement_id = a.achievement_id JOIN gaming_technology.players AS p ON pa.player_id = p.player_id GROUP BY p.username, pa.player_id HAVING SUM(a.points) > 500 ORDER BY total_points DESC;

[User] Additionally, include the number of distinct games where they unlocked at least one achievement.

[Assistant] SELECT p.username, pa.player_id, SUM(a.points) AS total_points, COUNT(DISTINCT a.game_id) AS distinct_games FROM gaming_technology.player_achievements AS pa JOIN gaming_technology.achievements AS a ON pa.achievement_id = a.achievement_id JOIN gaming_technology.players AS p ON pa.player_id = p.player_id GROUP BY p.username, pa.player_id HAVING SUM(a.points) > 500 ORDER BY total_points DESC;

[User] Please list the top 5 players by number of achievements unlocked since 2023-01-01. Show each player's username and the total count of achievements they unlocked.

[Assistant]
SELECT p.username, COUNT(*) AS unlock_count
FROM gaming_technology.players p
JOIN gaming_technology.player_achievements pa
  ON p.player_id = pa.player_id
WHERE pa.unlocked_at >= '2023-01-01'
GROUP BY p.username
ORDER BY unlock_count DESC
LIMIT 5;

[User] For each player, list their username together with the titles of games they have any items from in their inventory.

[Assistant]
SELECT DISTINCT p.username, g.title
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id;

[User] Now restrict the list to only include items of rarity 'Epic'.

[Assistant]
SELECT DISTINCT p.username, g.title
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'Epic';

[User] Also include the quantity of each epic item and sort the output by quantity in descending order.

[Assistant]
SELECT p.username, g.title, i.item_name, pi.quantity
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'Epic'
ORDER BY pi.quantity DESC;

[User] Finally, filter out entries where the quantity is less than 2.

[Assistant]
SELECT p.username, g.title, i.item_name, pi.quantity
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE i.rarity = 'Epic'
  AND pi.quantity >= 2
ORDER BY pi.quantity DESC;

[User] How many items in total has each player acquired according to player_inventory?

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

[User] Change that to count the number of acquisition records per player instead of summing quantity.

[Assistant]
SELECT
  player_id,
  COUNT(inventory_id) AS acquisition_count
FROM gaming_technology.player_inventory
GROUP BY player_id;

[User] Filter to players with more than 5 acquisitions.

[Assistant]
SELECT
  player_id,
  COUNT(inventory_id) AS acquisition_count
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING COUNT(inventory_id) > 5;

[User] Sort the result by acquisition_count descending and limit to the top 10 players.

[Assistant]
SELECT
  player_id,
  COUNT(inventory_id) AS acquisition_count
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING COUNT(inventory_id) > 5
ORDER BY acquisition_count DESC
LIMIT 10;


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.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, bed_type.text, area_sqft.numeric, amenities.text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Retrieve each guest's full name and the date of their most recent review, including review_source.

[Assistant]
SELECT sub.guest_id, sub.full_name, sub.review_date AS last_review_date, sub.review_source
FROM (
  SELECT g.guest_id,
         g.first_name || ' ' || g.last_name AS full_name,
         r.review_date,
         r.review_source,
         ROW_NUMBER() OVER (PARTITION BY g.guest_id ORDER BY r.review_date DESC) AS rn
  FROM hospitality_technology.guests g
  JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
) sub
WHERE sub.rn = 1;

[User] I only want guests who have opted in for communication and whose latest review is public.

[Assistant]
SELECT sub.guest_id, sub.full_name, sub.review_date AS last_review_date, sub.review_source
FROM (
  SELECT g.guest_id,
         g.first_name || ' ' || g.last_name AS full_name,
         r.review_date,
         r.review_source,
         r.is_public,
         ROW_NUMBER() OVER (PARTITION BY g.guest_id ORDER BY r.review_date DESC) AS rn
  FROM hospitality_technology.guests g
  JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
  WHERE g.communication_consent = true
) sub
WHERE sub.rn = 1 AND sub.is_public = true;

[User] Also include the review comment and order the results by last_review_date descending, limiting to the top 10 entries.

[Assistant]
SELECT sub.guest_id, sub.full_name, sub.review_date AS last_review_date, sub.review_source, sub.comment
FROM (
  SELECT g.guest_id,
         g.first_name || ' ' || g.last_name AS full_name,
         r.review_date,
         r.review_source,
         r.comment,
         r.is_public,
         ROW_NUMBER() OVER (PARTITION BY g.guest_id ORDER BY r.review_date DESC) AS rn
  FROM hospitality_technology.guests g
  JOIN hospitality_technology.reviews r ON g.guest_id = r.guest_id
  WHERE g.communication_consent = true AND r.is_public = true
) sub
WHERE sub.rn = 1
ORDER BY sub.review_date DESC
LIMIT 10;

[User] For each department, list the total number of available services and the total combined price of those services.

[Assistant]
SELECT department, COUNT(*) AS service_count, SUM(price) AS total_price
FROM hospitality_technology.services
WHERE is_available = true
GROUP BY department;

[User] Actually, show only departments where the combined price exceeds 1000.

[Assistant]
SELECT department, COUNT(*) AS service_count, SUM(price) AS total_price
FROM hospitality_technology.services
WHERE is_available = true
GROUP BY department
HAVING SUM(price) > 1000;

[User] List all services in the 'Concierge' department along with their names, price, and whether they are currently available. Include the property name as well.

[Assistant]
SELECT s.service_name, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge';

[User] Could you filter only those services that are not currently available and sort by price ascending?

[Assistant]
SELECT s.service_name, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge'
  AND s.is_available = false
ORDER BY s.price ASC;

[User] Instead, show only properties in the city of 'Miami' and add the service category to the results.

[Assistant]
SELECT s.service_name, s.category, s.price, s.is_available, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.department = 'Concierge'
  AND s.is_available = false
  AND p.city = 'Miami'
ORDER BY s.price ASC;

[User] Show me the list of all guests who have reservations along with the room number, room type name, and property name for each reservation.

[Assistant]
SELECT g.first_name, g.last_name, r.room_number, rt.type_name AS room_type_name, p.property_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
LEFT JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
LEFT JOIN hospitality_technology.room_types rt ON res.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON res.property_id = p.property_id;

[User] Get a list of room types along with their property name and the count of rooms currently Available for each type.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS available_rooms_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.rooms r ON rt.room_type_id = r.room_type_id
  AND r.status = 'Available'
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
GROUP BY rt.type_name, p.property_name;

[User] List all reservations along with the guest's full name and the property name for reservations made in properties outside the USA.

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE p.country_code <> 'USA';

[User] Only include reservations with a total amount greater than 800, and sort the results by total_amount descending.

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, r.total_amount
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE p.country_code <> 'USA'
  AND r.total_amount > 800
ORDER BY r.total_amount DESC;

[User] Get the number of available services for each property. Include the property_name and service_count.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.services s
  ON p.property_id = s.property_id
  AND s.is_available = TRUE
GROUP BY p.property_name;

[User] Only include properties with more than 5 available services.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.services s
  ON p.property_id = s.property_id
  AND s.is_available = TRUE
GROUP BY p.property_name
HAVING COUNT(s.service_id) > 5;

[User] Also show the average price of these available services as avg_price.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS service_count,
       AVG(s.price)        AS avg_price
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.services s
  ON p.property_id = s.property_id
  AND s.is_available = TRUE
GROUP BY p.property_name
HAVING COUNT(s.service_id) > 5;

[User] Get each property's name, manager_staff_id, and the number of rooms with status 'OutOfOrder', including properties with zero OutOfOrder rooms.

[Assistant]
SELECT p.property_name, p.manager_staff_id, COUNT(r.room_id) AS out_of_order_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r
  ON p.property_id = r.property_id AND r.status = 'OutOfOrder'
GROUP BY p.property_name, p.manager_staff_id;

[User] Calculate the average length of stay in days for completed reservations for each property.

[Assistant]
SELECT p.property_id,
       p.property_name,
       AVG(res.check_out_date - res.check_in_date) AS avg_stay_days
FROM hospitality_technology.reservations res
JOIN hospitality_technology.properties p ON res.property_id = p.property_id
WHERE res.status = 'Completed'
GROUP BY p.property_id, p.property_name;

[User] Limit the results to properties where the average stay is more than 3 days.

[Assistant]
SELECT p.property_id,
       p.property_name,
       AVG(res.check_out_date - res.check_in_date) AS avg_stay_days
FROM hospitality_technology.reservations res
JOIN hospitality_technology.properties p ON res.property_id = p.property_id
WHERE res.status = 'Completed'
GROUP BY p.property_id, p.property_name
HAVING AVG(res.check_out_date - res.check_in_date) > 3;

[User] Also include the total number of completed reservations per property alongside the average length of stay.

[Assistant]
SELECT p.property_id,
       p.property_name,
       COUNT(res.reservation_id) AS total_reservations,
       AVG(res.check_out_date - res.check_in_date) AS avg_stay_days
FROM hospitality_technology.reservations res
JOIN hospitality_technology.properties p ON res.property_id = p.property_id
WHERE res.status = 'Completed'
GROUP BY p.property_id, p.property_name
HAVING AVG(res.check_out_date - res.check_in_date) > 3;

[User] Show all active staff members' full names and their positions.

[Assistant]
SELECT staff_id, first_name || ' ' || last_name AS staff_full_name, position
FROM hospitality_technology.staff
WHERE is_active = true;

[User] Also include the name of the property they work at.

[Assistant]
SELECT s.staff_id, s.first_name || ' ' || s.last_name AS staff_full_name, s.position, p.property_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_active = true;


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.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List all payments for reservations made at properties with a star rating of 5.0. Include the payment amount, guest ID, reservation ID, and property name.

[Assistant] SELECT T1.amount, T1.guest_id, T1.reservation_id, T3.property_name FROM hospitality_technology.payments AS T1 JOIN hospitality_technology.reservations AS T2 ON T1.reservation_id = T2.reservation_id JOIN hospitality_technology.properties AS T3 ON T2.property_id = T3.property_id WHERE T3.star_rating = 5.0

[User] List all public reviews that have a staff response, showing the review ID, overall rating, and the full name of the staff member who responded.

[Assistant] SELECT T1.review_id, T1.rating_overall, T2.first_name, T2.last_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.staff AS T2 ON T1.response_staff_id = T2.staff_id WHERE T1.is_public = true AND T1.response_staff_id IS NOT NULL

[User] Also include the property name for each of these reviews.

[Assistant] SELECT T1.review_id, T1.rating_overall, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.staff AS T2 ON T1.response_staff_id = T2.staff_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T1.is_public = true AND T1.response_staff_id IS NOT NULL

[User] Filter the results to only show reviews with an overall rating of 5 and those responded to in the last 90 days.

[Assistant] SELECT T1.review_id, T1.rating_overall, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.staff AS T2 ON T1.response_staff_id = T2.staff_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T1.is_public = true AND T1.response_staff_id IS NOT NULL AND T1.rating_overall = 5 AND T1.response_date >= CURRENT_DATE - INTERVAL '90 days'

[User] Which properties offer services in the 'Business Center' department, and what are the names and prices of those services?

[Assistant]
SELECT p.property_id, p.property_name, s.service_name, s.price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON p.property_id = s.property_id
WHERE s.department = 'Business Center';

[User] Actually, only show those services that are currently available and sort the results by price ascending.

[Assistant]
SELECT p.property_id, p.property_name, s.service_name, s.price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON p.property_id = s.property_id
WHERE s.department = 'Business Center' AND s.is_available = TRUE
ORDER BY s.price ASC;

[User] List all future reservations (where check_in_date > current_date) including guest full name, room_id, property_id, and the number of days until check-in.

[Assistant]
SELECT r.reservation_id, r.property_id, r.room_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       (r.check_in_date - CURRENT_DATE) AS days_until_check_in
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
WHERE r.check_in_date > CURRENT_DATE;

[User] Show me the number of service orders placed for each service category.

[Assistant]
SELECT s.category, COUNT(so.order_id) AS order_count
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY s.category;

[User] Only include categories with more than 10 orders and order by order_count descending.

[Assistant]
SELECT s.category, COUNT(so.order_id) AS order_count
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY s.category
HAVING COUNT(so.order_id) > 10
ORDER BY order_count DESC;

[User] List all public reviews with a rating_overall of at least 4, including review_id, guest_id, property_id, reservation_id, and review_date.

[Assistant]
SELECT review_id, guest_id, property_id, reservation_id, review_date
FROM hospitality_technology.reviews
WHERE is_public = true AND rating_overall >= 4;

[User] Only include reviews in the last 30 days and order by review_date descending.

[Assistant]
SELECT review_id, guest_id, property_id, reservation_id, review_date
FROM hospitality_technology.reviews
WHERE is_public = true
  AND rating_overall >= 4
  AND review_date >= NOW() - INTERVAL '30 days'
ORDER BY review_date DESC;

[User] Also include the type_name and base_rate of the room type associated with each review's reservation.

[Assistant]
SELECT rv.review_id,
       rv.guest_id,
       rv.property_id,
       rv.reservation_id,
       rv.review_date,
       rt.type_name,
       rt.base_rate
FROM hospitality_technology.reviews rv
JOIN hospitality_technology.reservations r ON rv.reservation_id = r.reservation_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE rv.is_public = true
  AND rv.rating_overall >= 4
  AND rv.review_date >= NOW() - INTERVAL '30 days'
ORDER BY rv.review_date DESC;

[User] List the names and prices of all services ordered by guests from 'Texas', along with the guest's full name.

[Assistant]
SELECT g.first_name, g.last_name, s.service_name, s.price
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE g.state_province = 'Texas';

[User] Only include services from the 'Activities' department and sort results by service price descending.

[Assistant]
SELECT g.first_name, g.last_name, s.service_name, s.price
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE g.state_province = 'Texas'
  AND s.department = 'Activities'
ORDER BY s.price DESC;

[User] Which reservations included at least two different services ordered? Display the reservation ID and a count of distinct services.

[Assistant]
SELECT reservation_id, COUNT(DISTINCT service_id) AS distinct_service_count
FROM hospitality_technology.service_orders
GROUP BY reservation_id
HAVING COUNT(DISTINCT service_id) >= 2;

[User] Actually, just show those reservations in which all ordered services were from the 'Business Center' department.

[Assistant]
SELECT so.reservation_id, COUNT(DISTINCT so.service_id) AS distinct_service_count
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY so.reservation_id
HAVING COUNT(DISTINCT so.service_id) >= 2
  AND COUNT(DISTINCT CASE WHEN s.department = 'Business Center' THEN so.service_id END) = COUNT(DISTINCT so.service_id);

[User] Show me all service orders along with their status and the associated review comment for the same reservation, if there is one.

[Assistant]
SELECT so.order_id, so.status, r.comment
FROM hospitality_technology.service_orders so
LEFT JOIN hospitality_technology.reviews r ON so.reservation_id = r.reservation_id;

[User] Filter to only include service orders where guests left a comment.

[Assistant]
SELECT so.order_id, so.status, r.comment
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.reviews r ON so.reservation_id = r.reservation_id
WHERE r.comment IS NOT NULL AND r.comment <> '';

[User] Also, only show those service orders for services in the 'Activities' category.

[Assistant]
SELECT so.order_id, so.status, r.comment
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.reviews r ON so.reservation_id = r.reservation_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE r.comment IS NOT NULL AND r.comment <> ''
  AND s.category = 'Activities';

[User] For each review, show me the review comment and the associated service names that the guest has ordered during the same reservation.

[Assistant]
SELECT r.review_id, r.comment, s.service_name
FROM hospitality_technology.reviews r
JOIN hospitality_technology.reservations res ON r.reservation_id = res.reservation_id
JOIN hospitality_technology.service_orders so ON so.reservation_id = res.reservation_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id;

[User] Limit the results to reviews with overall rating below 3 and only include services from the 'Wellness' category.

[Assistant]
SELECT r.review_id, r.comment, s.service_name
FROM hospitality_technology.reviews r
JOIN hospitality_technology.reservations res ON r.reservation_id = res.reservation_id
JOIN hospitality_technology.service_orders so ON so.reservation_id = res.reservation_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
WHERE r.rating_overall < 3 AND s.category = 'Wellness';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)
CREATE TABLE web3.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)

[User] For each user with at least two wallets, calculate the average time difference in hours between consecutive wallet creations. Return user_id and avg_diff_hours.

[Assistant] SELECT user_id, AVG(EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600) AS avg_diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) t WHERE prev_created IS NOT NULL GROUP BY user_id;

[User] Actually, restrict the results to users whose avg_diff_hours is less than 24 hours and sort by avg_diff_hours ascending.

[Assistant] WITH diffs AS (SELECT user_id, EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600 AS diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) sub WHERE prev_created IS NOT NULL) SELECT user_id, AVG(diff_hours) AS avg_diff_hours FROM diffs GROUP BY user_id HAVING AVG(diff_hours) < 24 ORDER BY avg_diff_hours;

[User] Show each contract address and the count of successful transactions sent to that contract.

[Assistant] SELECT c.address, COUNT(t.transaction_id) AS success_tx_count FROM web3.contracts c JOIN web3.transactions t ON t.to_address = c.address AND t.status = 'success' GROUP BY c.address;

[User] List all transactions along with the user_id of the sender when the sender’s address matches a wallet. Return transaction_id, from_address, and user_id.

[Assistant] SELECT t.transaction_id, t.from_address, w.user_id FROM web3.transactions t JOIN web3.wallets w ON t.from_address = w.address;

[User] List each transaction ID that includes token transfers, along with the distinct symbols of the tokens transferred in that transaction.

[Assistant] SELECT T1.transaction_id, STRING_AGG(DISTINCT T3.token_symbol, ', ') FROM web3.transactions AS T1 JOIN web3.token_transfers AS T2 ON T1.transaction_id = T2.transaction_id JOIN web3.tokens AS T3 ON T2.token_id = T3.token_id GROUP BY T1.transaction_id

[User] For each transaction status, what is the average transaction value?

[Assistant] SELECT status, AVG(value) FROM web3.transactions GROUP BY status

[User] Could you filter this to only show statuses where the average value is greater than 100?

[Assistant] SELECT status, AVG(value) FROM web3.transactions GROUP BY status HAVING AVG(value) > 100

[User] List all users and the total value of all transactions they have initiated. Show user_id, username, and total_transaction_value.

[Assistant]
SELECT u.user_id, u.username, COALESCE(SUM(t.value), 0) AS total_transaction_value
FROM web3.users u
LEFT JOIN web3.wallets w ON u.user_id = w.user_id
LEFT JOIN web3.transactions t ON w.address = t.from_address
GROUP BY u.user_id, u.username;

[User] Actually, only show users who have initiated at least one transaction, and sort them by total_transaction_value descending.

[Assistant]
SELECT u.user_id, u.username, SUM(t.value) AS total_transaction_value
FROM web3.users u
JOIN web3.wallets w ON u.user_id = w.user_id
JOIN web3.transactions t ON w.address = t.from_address
GROUP BY u.user_id, u.username
HAVING SUM(t.value) > 0
ORDER BY total_transaction_value DESC;

[User] Show all contracts and the names of all events they have ever emitted. Include contract_id, contract address, and event_name.

[Assistant]
SELECT c.contract_id, c.address, e.event_name
FROM web3.contracts c
JOIN web3.events e ON c.contract_id = e.contract_id
ORDER BY c.contract_id, e.event_name;

[User] For each token, list its symbol and the number of transfers recorded in token_transfers.

[Assistant]
SELECT
  t.token_symbol,
  COUNT(tt.transfer_id) AS transfer_count
FROM web3.tokens t
LEFT JOIN web3.token_transfers tt
  ON t.token_id = tt.token_id
GROUP BY t.token_symbol;

[User] Actually, I also want to include the total transferred value for each token.

[Assistant]
SELECT
  t.token_symbol,
  COUNT(tt.transfer_id) AS transfer_count,
  COALESCE(SUM(tt.value), 0) AS total_transferred_value
FROM web3.tokens t
LEFT JOIN web3.token_transfers tt
  ON t.token_id = tt.token_id
GROUP BY t.token_symbol;

[User] Show all contracts along with the number of events each contract has emitted. Include the contract address and the event count.

[Assistant]
SELECT c.address, COUNT(e.event_id) AS event_count
FROM web3.contracts c
LEFT JOIN web3.events e ON c.contract_id = e.contract_id
GROUP BY c.address;

[User] Show each contract's address along with the total number of events it has emitted and the total number of transactions sent to it.

[Assistant]
SELECT
  c.address,
  COUNT(e.event_id) AS event_count,
  COUNT(t.transaction_id) AS tx_count
FROM web3.contracts c
LEFT JOIN web3.events e
  ON c.contract_id = e.contract_id
LEFT JOIN web3.transactions t
  ON c.address = t.to_address
GROUP BY c.address;


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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )

[User] List all locations situated within the state of California.

[Assistant] SELECT location_id, name, city, state_province FROM transportation.locations WHERE state_province = 'CA';

[User] Now, refine this list to only include locations that are specifically in Los Angeles.

[Assistant] SELECT location_id, name, city, state_province FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles';

[User] Could you also include the type of location and its postal code in the result?

[Assistant] SELECT location_id, name, city, state_province, type, postal_code FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles';

[User] Finally, order these locations by their name in alphabetical order.

[Assistant] SELECT location_id, name, city, state_province, type, postal_code FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles' ORDER BY name;

[User] Show me all locations in New York with latitude above 40.7, including their type and coordinates.

[Assistant] SELECT name, type, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7;

[User] There's a typo in your SQL - it should be 'locations' not 'locatons'. Also, can you include the city and order by latitude in descending order?

[Assistant] SELECT name, type, city, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7 ORDER BY latitude DESC;

[User] Now filter these results to only show locations of type 'gas station' or 'depot' and include their postal codes.

[Assistant] SELECT name, type, city, postal_code, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7 AND type IN ('gas station', 'depot') ORDER BY latitude DESC;

[User] Can you show me the name, city, and type for all locations that are in the same city but have different types?

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type;

[User] Please only include locations where the city is 'Chicago'.

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type WHERE l1.city = 'Chicago';

[User] Find all cities that contain at least one location of type 'Depot' and at least one location of type 'Station'.

[Assistant] SELECT city FROM transportation.locations WHERE type IN ('Depot', 'Station') GROUP BY city HAVING COUNT(DISTINCT CASE WHEN type = 'Depot' THEN location_id END) > 0 AND COUNT(DISTINCT CASE WHEN type = 'Station' THEN location_id END) > 0;

[User] Can you give me all locations in Los Angeles?

[Assistant]
SELECT location_id, name, type, address_line1, city, state_province, postal_code, country, latitude, longitude, timezone
FROM transportation.locations
WHERE city = 'Los Angeles';

[User] I want to see only locations of type 'Depot' in Los Angeles.

[Assistant]
SELECT location_id, name, type, address_line1, city, state_province, postal_code, country, latitude, longitude, timezone
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot';

[User] Can you show me their postal codes and sort them by name in ascending order?

[Assistant]
SELECT location_id, name, postal_code
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot'
ORDER BY name ASC;

[User] Actually, I also want to see the state_province in the output.

[Assistant]
SELECT location_id, name, postal_code, state_province
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot'
ORDER BY name ASC;

[User] Find all distinct pairs of locations that are located in the same city. List their IDs, names, and the shared city.

[Assistant] SELECT l1.location_id AS location1_id, l1.name AS location1_name, l2.location_id AS location2_id, l2.name AS location2_name, l1.city FROM transportation.locations AS l1 JOIN transportation.locations AS l2 ON l1.city = l2.city AND l1.location_id < l2.location_id;

[User] List the name and location ID for all locations where the postal code is missing.

[Assistant] SELECT name, location_id FROM transportation.locations WHERE postal_code IS NULL;

[User] Also include the city and order the results by city ascending.

[Assistant] SELECT name, location_id, city FROM transportation.locations WHERE postal_code IS NULL ORDER BY city ASC;

[User] List the name, city, state, and country for all locations with a latitude greater than 40 and a longitude less than -70.

[Assistant] SELECT name, city, state_province, country FROM transportation.locations WHERE latitude > 40 AND longitude < -70;

[User] Now, filter this list to only include locations of type 'Airport'.

[Assistant] SELECT name, city, state_province, country FROM transportation.locations WHERE latitude > 40 AND longitude < -70 AND type = 'Airport';

[User] List all pairs of locations where both are located in the same timezone but are in different cities. Include both location IDs, names, the timezone, and their respective cities.

[Assistant]
SELECT l1.location_id AS location1_id, l1.name AS location1_name, l2.location_id AS location2_id, l2.name AS location2_name, l1.timezone, l1.city AS city1, l2.city AS city2
FROM transportation.locations l1
JOIN transportation.locations l2 ON l1.timezone = l2.timezone
    AND l1.city <> l2.city
    AND l1.location_id < l2.location_id;

[User] Show all cities in the USA that have more than one distinct location type represented. List the city, country, and number of distinct location types.

[Assistant]
SELECT city, country, COUNT(DISTINCT type) AS distinct_location_types
FROM transportation.locations
WHERE country = 'USA'
GROUP BY city, country
HAVING COUNT(DISTINCT type) > 1;


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_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] I want to identify pairs of players who unlocked the same achievement within one hour of each other. List player1_id, player2_id, achievement_id, and the time difference in minutes.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id <> pa2.player_id
WHERE ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) <= 60;

[User] Actually, ensure we only list each pair once by showing only cases where player1_id < player2_id.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id < pa2.player_id
WHERE ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) <= 60;

[User] Also, only include cases where the time difference is less than 30 minutes.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id < pa2.player_id
WHERE ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) < 30;

[User] And only for achievements unlocked after '2023-01-01'.

[Assistant]
SELECT pa1.player_id AS player1_id,
       pa2.player_id AS player2_id,
       pa1.achievement_id,
       ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) AS time_diff_minutes
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.achievement_id = pa2.achievement_id
     AND pa1.player_id < pa2.player_id
WHERE pa1.unlocked_at >= '2023-01-01'
  AND pa2.unlocked_at >= '2023-01-01'
  AND ABS(EXTRACT(EPOCH FROM (pa1.unlocked_at - pa2.unlocked_at)) / 60) < 30;

[User] List all pairs of achievements unlocked by the same player, showing player_id, achievement1, and achievement2.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS achievement1,
       pa2.achievement_id AS achievement2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa1.unlocked_at < pa2.unlocked_at;

[User] Now include only pairs where the second achievement was unlocked within 7 days of the first.

[Assistant]
SELECT pa1.player_id,
       pa1.achievement_id AS achievement1,
       pa2.achievement_id AS achievement2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
 AND pa1.unlocked_at < pa2.unlocked_at
 AND pa2.unlocked_at <= pa1.unlocked_at + INTERVAL '7 days';

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

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

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

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

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

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

[User] Finally, limit to 20 rows.

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

[User] Can you show me all achievement unlock records where the same player unlocked two different achievements within the same day? Please show player_id, achievement_id_1, achievement_id_2, and the unlock dates for each.

[Assistant]
SELECT pa1.player_id, pa1.achievement_id as achievement_id_1, pa2.achievement_id as achievement_id_2, pa1.unlocked_at as unlock_date_1, pa2.unlocked_at as unlock_date_2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
  AND pa1.achievement_id <> pa2.achievement_id
  AND DATE(pa1.unlocked_at) = DATE(pa2.unlocked_at)
  AND pa1.unlocked_at < pa2.unlocked_at;

[User] Add a condition to only include records where both achievements were unlocked on or after January 1st, 2024.

[Assistant]
SELECT pa1.player_id, pa1.achievement_id as achievement_id_1, pa2.achievement_id as achievement_id_2, pa1.unlocked_at as unlock_date_1, pa2.unlocked_at as unlock_date_2
FROM gaming_technology.player_achievements pa1
JOIN gaming_technology.player_achievements pa2
  ON pa1.player_id = pa2.player_id
  AND pa1.achievement_id <> pa2.achievement_id
  AND DATE(pa1.unlocked_at) = DATE(pa2.unlocked_at)
  AND pa1.unlocked_at < pa2.unlocked_at
WHERE pa1.unlocked_at >= '2024-01-01' AND pa2.unlocked_at >= '2024-01-01';

[User] How many achievements has each player unlocked and what's the earliest unlocked timestamp for each?

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id;

[User] Exclude players with fewer than 3 achievements.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 3;

[User] Order the results by first_unlocked ascending.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 3
ORDER BY first_unlocked ASC;

[User] Only show the top 10 players after ordering.

[Assistant]
SELECT player_id,
       COUNT(*) AS total_unlocked,
       MIN(unlocked_at) AS first_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(*) >= 3
ORDER BY first_unlocked ASC
LIMIT 10;

[User] Show the number of achievements unlocked by each player per month. Display player_id, month (as YYYY-MM), and achievement_count.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM');

[User] Filter to months where players unlocked at least 5 achievements.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5;

[User] Sort the results by year_month ascending and then by achievement_count descending.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5
ORDER BY year_month ASC, achievement_count DESC;

[User] Limit the results to 10 rows.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5
ORDER BY year_month ASC, achievement_count DESC
LIMIT 10;

[User] Can you show me how many achievements each player unlocks per day? Return player_id, unlock_date, and achievement_count.

[Assistant]
SELECT player_id,
       CAST(unlocked_at AS date) AS unlock_date,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, CAST(unlocked_at AS date);

[User] Actually, I'd like to exclude days where players unlocked fewer than 3 achievements.

[Assistant]
SELECT player_id,
       CAST(unlocked_at AS date) AS unlock_date,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, CAST(unlocked_at AS date)
HAVING COUNT(*) >= 3;

[User] Also, only show results for the last 30 days.

[Assistant]
SELECT player_id,
       CAST(unlocked_at AS date) AS unlock_date,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
WHERE unlocked_at >= NOW() - INTERVAL '30 days'
GROUP BY player_id, CAST(unlocked_at AS date)
HAVING COUNT(*) >= 3;

[User] Finally, order the results by achievement_count descending.

[Assistant]
SELECT player_id,
       CAST(unlocked_at AS date) AS unlock_date,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
WHERE unlocked_at >= NOW() - INTERVAL '30 days'
GROUP BY player_id, CAST(unlocked_at AS date)
HAVING COUNT(*) >= 3
ORDER BY achievement_count DESC;

[User] Show me the number of unique achievements unlocked by each player.

[Assistant]
SELECT player_id, COUNT(DISTINCT achievement_id) AS unique_achievements_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id;

[User] Can you include only players who unlocked more than 3 unique achievements?

[Assistant]
SELECT player_id, COUNT(DISTINCT achievement_id) AS unique_achievements_unlocked
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(DISTINCT achievement_id) > 3;

[User] Add another column to show the date when each player unlocked their first achievement.

[Assistant]
SELECT player_id, COUNT(DISTINCT achievement_id) AS unique_achievements_unlocked,
       MIN(unlocked_at) AS first_achievement_unlocked_at
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(DISTINCT achievement_id) > 3;

[User] Now order the results by unique_achievements_unlocked descending, then by first_achievement_unlocked_at ascending.

[Assistant]
SELECT player_id, COUNT(DISTINCT achievement_id) AS unique_achievements_unlocked,
       MIN(unlocked_at) AS first_achievement_unlocked_at
FROM gaming_technology.player_achievements
GROUP BY player_id
HAVING COUNT(DISTINCT achievement_id) > 3
ORDER BY unique_achievements_unlocked DESC, first_achievement_unlocked_at ASC;

[User] Can you list for each player their most recent and second most recent achievements, showing columns player_id, recent_achievement_id, second_recent_achievement_id, and recent_unlocked_at?

[Assistant]
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       prev.achievement_id AS second_recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at
FROM (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn
  FROM gaming_technology.player_achievements
) recent
JOIN (
  SELECT player_id, achievement_id,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn
  FROM gaming_technology.player_achievements
) prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1 AND prev.rn = 2;

[User] Actually, please exclude any players who have less than two unlock records.

[Assistant]
WITH ranked AS (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn,
         COUNT(*) OVER (PARTITION BY player_id) AS cnt
  FROM gaming_technology.player_achievements
)
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       prev.achievement_id AS second_recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at
FROM ranked recent
JOIN ranked prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1
  AND prev.rn = 2
  AND recent.cnt >= 2;

[User] Also include the unlocked_at timestamp of the second most recent achievement.

[Assistant]
WITH ranked AS (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn,
         COUNT(*) OVER (PARTITION BY player_id) AS cnt
  FROM gaming_technology.player_achievements
)
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at,
       prev.achievement_id AS second_recent_achievement_id,
       prev.unlocked_at AS second_recent_unlocked_at
FROM ranked recent
JOIN ranked prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1
  AND prev.rn = 2
  AND recent.cnt >= 2;

[User] Finally, order the output by recent_unlocked_at in descending order.

[Assistant]
WITH ranked AS (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn,
         COUNT(*) OVER (PARTITION BY player_id) AS cnt
  FROM gaming_technology.player_achievements
)
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at,
       prev.achievement_id AS second_recent_achievement_id,
       prev.unlocked_at AS second_recent_unlocked_at
FROM ranked recent
JOIN ranked prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1 AND prev.rn = 2 AND recent.cnt >= 2
ORDER BY recent.unlocked_at DESC;

[User] For each player who has unlocked at least two achievements, find the time difference in minutes between their first and last achievement unlock. Show player_id and the difference labeled last_minus_first_minutes.

[Assistant] SELECT player_id, EXTRACT(EPOCH FROM (MAX(unlocked_at) - MIN(unlocked_at))) / 60 AS last_minus_first_minutes FROM gaming_technology.player_achievements GROUP BY player_id HAVING COUNT(player_achievement_id) >= 2;

[User] Only include players where the difference is greater than 60 minutes.

[Assistant] SELECT player_id, EXTRACT(EPOCH FROM (MAX(unlocked_at) - MIN(unlocked_at))) / 60 AS last_minus_first_minutes FROM gaming_technology.player_achievements GROUP BY player_id HAVING COUNT(player_achievement_id) >= 2 AND EXTRACT(EPOCH FROM (MAX(unlocked_at) - MIN(unlocked_at))) / 60 > 60;

[User] Now, instead of the total difference, I want to find players who unlocked at least two *different* achievements within the *same hour* on the same day. Show their player_id and the date.

[Assistant] SELECT DISTINCT p1.player_id, DATE(p1.unlocked_at) AS unlock_date FROM gaming_technology.player_achievements p1 JOIN gaming_technology.player_achievements p2 ON p1.player_id = p2.player_id AND p1.achievement_id <> p2.achievement_id WHERE DATE(p1.unlocked_at) = DATE(p2.unlocked_at) AND EXTRACT(HOUR FROM p1.unlocked_at) = EXTRACT(HOUR FROM p2.unlocked_at);

[User] Filter this list to only show players who achieved this on a date after '2024-01-01' and order by the date descending.

[Assistant] SELECT DISTINCT p1.player_id, DATE(p1.unlocked_at) AS unlock_date FROM gaming_technology.player_achievements p1 JOIN gaming_technology.player_achievements p2 ON p1.player_id = p2.player_id AND p1.achievement_id <> p2.achievement_id WHERE DATE(p1.unlocked_at) = DATE(p2.unlocked_at) AND EXTRACT(HOUR FROM p1.unlocked_at) = EXTRACT(HOUR FROM p2.unlocked_at) AND DATE(p1.unlocked_at) > '2024-01-01' ORDER BY unlock_date DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Get the count of unread 'message' notifications per group chat, showing conversation_id, group_name, and unread_message_notifications.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_message_notifications
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'message'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name;

[User] Actually, only include group chats where unread_message_notifications > 5.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_message_notifications
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'message'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(n.notification_id) > 5;

[User] List all users with private profiles who have disabled push notifications, including their user_id and email_notifications_enabled status.

[Assistant]
SELECT user_id,
       email_notifications_enabled
FROM social_media.user_settings
WHERE private_profile = true
  AND push_notifications_enabled = false;

[User] I want to see for each group chat the count of unread 'mention' notifications received by its recipients. Include conversation_id, group_name, and unread_mentions.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name;

[User] Now only include group chats created within the past year.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name;

[User] Order the results by unread_mentions descending.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name
ORDER BY unread_mentions DESC;

[User] Limit to the top 5 group chats.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name
ORDER BY unread_mentions DESC
LIMIT 5;

[User] How many unread messages does each sender have? Show sender_user_id and count of messages where read_at is null.

[Assistant]
SELECT sender_user_id, COUNT(*) AS unread_messages
FROM social_media.messages
WHERE read_at IS NULL
GROUP BY sender_user_id;

[User] List all messages that haven’t triggered any notification; show message_id, sender_user_id, and sent_at.

[Assistant]
SELECT m.message_id, m.sender_user_id, m.sent_at
FROM social_media.messages AS m
LEFT JOIN social_media.notifications AS n
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE n.notification_id IS NULL;

[User] Actually, only include those sent before '2024-06-01'.

[Assistant]
SELECT m.message_id, m.sender_user_id, m.sent_at
FROM social_media.messages AS m
LEFT JOIN social_media.notifications AS n
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE n.notification_id IS NULL
  AND m.sent_at < '2024-06-01';

[User] I want to find all notifications for messages containing the word 'holiday' in their content; include notification_id, message content, and notification created_at.

[Assistant]
SELECT n.notification_id, m.content, n.created_at
FROM social_media.notifications AS n
JOIN social_media.messages AS m
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE m.content LIKE '%holiday%';

[User] Could you filter this to only include notifications sent after '2024-05-01' and order by created_at descending?

[Assistant]
SELECT n.notification_id, m.content, n.created_at
FROM social_media.notifications AS n
JOIN social_media.messages AS m
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE m.content LIKE '%holiday%'
  AND n.created_at > '2024-05-01'
ORDER BY n.created_at DESC;

[User] Show me all notifications where the target entity type is 'comment', and for each notification, include the content of the corresponding comment.

[Assistant] SELECT n.*, c.content AS comment_content FROM social_media.notifications n JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment';

[User] Now, only include notifications that are of type 'like' or 'reply'.

[Assistant] SELECT n.*, c.content AS comment_content FROM social_media.notifications n JOIN social_media.comments c ON n.target_entity_id = c.comment_id WHERE n.target_entity_type = 'comment' AND n.notification_type IN ('like', 'reply');

[User] How many comments were created in the month of March 2024?

[Assistant] SELECT COUNT(*) FROM social_media.comments WHERE created_at >= '2024-03-01' AND created_at < '2024-04-01';

[User] List all unread notifications for group conversations, including the conversation name, sender_user_id, and notification creation time.

[Assistant]
SELECT c.group_name, n.sender_user_id, n.created_at
FROM social_media.notifications n
JOIN social_media.conversations c
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
WHERE c.is_group_chat = TRUE
  AND n.read_at IS NULL;

[User] Actually, show only those notifications created in the last 7 days.

[Assistant]
SELECT c.group_name, n.sender_user_id, n.created_at
FROM social_media.notifications n
JOIN social_media.conversations c
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
WHERE c.is_group_chat = TRUE
  AND n.read_at IS NULL
  AND n.created_at >= now() - interval '7 days';

[User] Get all notifications for posts tagged with hashtag 'H123', showing notification_id and created_at.

[Assistant]
SELECT n.notification_id, n.created_at
FROM social_media.notifications n
JOIN social_media.post_hashtags ph
  ON n.target_entity_type = 'post'
  AND n.target_entity_id = ph.post_id
WHERE ph.hashtag_id = 'H123';

[User] Now filter to only include notifications of type 'comment'.

[Assistant]
SELECT n.notification_id, n.created_at
FROM social_media.notifications n
JOIN social_media.post_hashtags ph
  ON n.target_entity_type = 'post'
  AND n.target_entity_id = ph.post_id
WHERE ph.hashtag_id = 'H123'
  AND n.notification_type = 'comment';