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 PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] Show me all group chats with their names and the time they were last active.

[Assistant] SELECT group_name, last_message_at FROM social_media.conversations WHERE is_group_chat = TRUE;

[User] Only show those group chats that were created after March 1, 2024.

[Assistant] SELECT group_name, last_message_at FROM social_media.conversations WHERE is_group_chat = TRUE AND created_at > '2024-03-01';

[User] Can you sort the results by last_message_at in descending order?

[Assistant] SELECT group_name, last_message_at FROM social_media.conversations WHERE is_group_chat = TRUE AND created_at > '2024-03-01' ORDER BY last_message_at DESC;

[User] List group conversation names and the count of messages sent in each conversation after '2024-06-01'.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name;

[User] Only show conversations that have more than 5 messages sent after that date.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name HAVING COUNT(T2.message_id) > 5;

[User] How many conversations are there where the last message was sent before January 1, 2024?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE last_message_at < '2024-01-01';

[User] List the names of group conversations and the usernames of participants who joined after '2023-01-01'.

[Assistant] SELECT T1.group_name, T3.username FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01';

[User] Only include conversations where the group name contains the word 'Project'.

[Assistant] SELECT T1.group_name, T3.username FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01' AND T1.group_name LIKE '%Project%';

[User] Can you also include the date each participant joined?

[Assistant] SELECT T1.group_name, T3.username, T2.joined_at FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01' AND T1.group_name LIKE '%Project%';

[User] Order the results by the join date descending.

[Assistant] SELECT T1.group_name, T3.username, T2.joined_at FROM social_media.conversations AS T1 JOIN social_media.participants AS T2 ON T1.conversation_id = T2.conversation_id JOIN social_media.users AS T3 ON T2.user_id = T3.user_id WHERE T1.is_group_chat = TRUE AND T2.joined_at > '2023-01-01' AND T1.group_name LIKE '%Project%' ORDER BY T2.joined_at DESC;

[User] How many group conversations are there?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = TRUE;

[User] Show all messages that include a media attachment, along with the sender's user ID and the conversation ID.

[Assistant] SELECT message_id, sender_user_id, conversation_id, media_url, media_type, sent_at FROM social_media.messages WHERE media_url IS NOT NULL AND media_url <> '';

[User] Only include messages sent after May 1st, 2024 and show the media_type as well.

[Assistant] SELECT message_id, sender_user_id, conversation_id, media_url, media_type, sent_at FROM social_media.messages WHERE media_url IS NOT NULL AND media_url <> '' AND sent_at > '2024-05-01';

[User] Show me all messages sent after July 1, 2024, including the sender_user_id, content, and sent_at.

[Assistant]
SELECT message_id, sender_user_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01';

[User] Can you also include the conversation_id and only show messages that have not been read yet?

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL;

[User] Now only show results where the message contains a media attachment and order the results by sent_at descending.

[Assistant]
SELECT message_id, sender_user_id, conversation_id, content, sent_at
FROM social_media.messages
WHERE sent_at > '2024-07-01' AND read_at IS NULL AND media_url IS NOT NULL AND media_url <> ''
ORDER BY sent_at DESC;

[User] How many messages in total have been sent that do not contain any media attachment?

[Assistant]
SELECT COUNT(*) AS non_media_message_count
FROM social_media.messages
WHERE media_url IS NULL OR media_url = '';

[User] List the sender_user_id and the total number of messages they have sent that include media attachments, along with the conversation_id.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> ''
GROUP BY sender_user_id, conversation_id;

[User] Only include media attachments where media_type is 'video'.

[Assistant]
SELECT sender_user_id, conversation_id, COUNT(*) AS video_media_message_count
FROM social_media.messages
WHERE media_url IS NOT NULL AND media_url <> '' AND media_type = 'video'
GROUP BY sender_user_id, conversation_id;

[User] Provide a breakdown of the total number of conversations, showing how many are group chats and how many are not. Also, show the count of conversations that have a recorded last message time.

[Assistant] SELECT COUNT(*) AS total_conversations, COUNT(CASE WHEN is_group_chat = true THEN 1 END) AS group_chat_count, COUNT(CASE WHEN is_group_chat = false THEN 1 END) AS private_chat_count, COUNT(last_message_at) AS conversations_with_messages_count FROM social_media.conversations;


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 character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)

[User] Show me the first name, last name, and email for all clients registered in January 2023.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1;

[User] Only show those who have provided a phone number.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL;

[User] Also, exclude any clients whose status is 'inactive'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive';

[User] Order the results by last name, then first name.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE EXTRACT(YEAR FROM date_registered) = 2023 AND EXTRACT(MONTH FROM date_registered) = 1 AND phone IS NOT NULL AND status != 'inactive' ORDER BY last_name, first_name;

[User] Show me the full name and email of clients whose status is 'prospect' and who registered before 2023-01-01.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE status = 'prospect' AND date_registered < '2023-01-01';

[User] Among these, list only those who do *not* have a company name specified.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE status = 'prospect' AND date_registered < '2023-01-01' AND company_name IS NULL;

[User] Actually, refine it further to only include those who registered in the year 2022, and order the results by last name.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE status = 'prospect' AND date_registered >= '2022-01-01' AND date_registered < '2023-01-01' AND company_name IS NULL ORDER BY last_name;

[User] Find all clients who do not have a company name listed and show their full name and email.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] Provide the count of transfers for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count
FROM web3.token_transfers
GROUP BY token_id;

[User] Actually, also include the total transferred value for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count,
       SUM(value) AS total_transferred_value
FROM web3.token_transfers
GROUP BY token_id;

[User] Find all addresses that have only sent tokens (appear in from_address) but have never received any (do not appear in to_address).

[Assistant] SELECT DISTINCT from_address FROM web3.token_transfers WHERE from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers);

[User] For these addresses that have only sent tokens, show the total value of tokens each has sent.

[Assistant] SELECT t1.from_address, SUM(t1.value) AS total_sent_value FROM web3.token_transfers AS t1 WHERE t1.from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers) GROUP BY t1.from_address;

[User] List the top 5 addresses that have received the most token transfers.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count FROM web3.token_transfers GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;

[User] Okay, but only for token_id '0xabc123...' and also show the total value received by each of these addresses for that token.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count, SUM(value) AS total_received_value FROM web3.token_transfers WHERE token_id = '0xabc123...' GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;

[User] For each recipient address, count how many token transfers they have received.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address;

[User] Only show addresses that have received more than 100 transfers.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address HAVING COUNT(*) > 100;

[User] Find token transfers within the same transaction where the recipient of an earlier transfer (based on log_index) becomes the sender of a later transfer. List the transaction ID, the earlier transfer ID, the later transfer ID, the shared address, and the value transferred in both cases.

[Assistant] SELECT t1.transaction_id, t1.transfer_id AS earlier_transfer_id, t2.transfer_id AS later_transfer_id, t1.to_address AS shared_address, t1.value AS earlier_transfer_value, t2.value AS later_transfer_value FROM web3.token_transfers AS t1 JOIN web3.token_transfers AS t2 ON t1.transaction_id = t2.transaction_id WHERE t1.to_address = t2.from_address AND t1.log_index < t2.log_index;

[User] List pairs of token transfers within the same transaction and for the same token_id where the transfer values are different. Show the transaction ID, token ID, and both transfer IDs and their values.

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

[User] Which transaction_id has the highest total value transferred? Show the transaction_id and the sum of values for that transaction.

[Assistant] SELECT transaction_id, SUM(value) AS total_transaction_value FROM web3.token_transfers GROUP BY transaction_id ORDER BY total_transaction_value DESC LIMIT 1;

[User] Show me the top 10 token transfers by value, including the token ID and the transaction ID, sorted in descending order.

[Assistant] SELECT token_id, transaction_id, value FROM web3.token_transfers ORDER BY value DESC LIMIT 10;

[User] List all pairs of token transfers occurring within the same transaction where one transferred value is greater than the other, showing both transfer IDs, the transaction ID, and both values.

[Assistant]
SELECT t1.transaction_id,
       t1.transfer_id AS transfer_id_1,
       t2.transfer_id AS transfer_id_2,
       t1.value       AS value_1,
       t2.value       AS value_2
FROM web3.token_transfers t1
JOIN web3.token_transfers t2
  ON t1.transaction_id = t2.transaction_id
 AND t1.value > t2.value;

[User] Find all pairs of token transfers where one transfer's sender and recipient are swapped with another transfer's sender and recipient, showing both transfer IDs.

[Assistant]
SELECT t1.from_address AS sender,
       t1.to_address   AS recipient,
       t1.transfer_id  AS transfer1_id,
       t2.transfer_id  AS transfer2_id
FROM web3.token_transfers t1
JOIN web3.token_transfers t2
  ON t1.from_address = t2.to_address
 AND t1.to_address   = t2.from_address
 AND t1.transfer_id < t2.transfer_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 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 NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_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, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
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 PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] Show the total number of game sessions played on each server that is currently 'online'. Include the server name, region, and the count of sessions.

[Assistant] SELECT s.server_name, s.region, COUNT(gs.session_id) AS total_sessions FROM gaming_technology.game_sessions gs JOIN gaming_technology.servers s ON gs.server_id = s.server_id WHERE s.status = 'online' AND gs.server_id IS NOT NULL GROUP BY s.server_name, s.region ORDER BY total_sessions DESC;

[User] Show each player's ID along with the name and quantity of every item they have in their inventory. Join the player inventory with item details.

[Assistant] SELECT pi.player_id, igi.item_name, pi.quantity FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id;

[User] Filter this list to only include items where the quantity is greater than 5 and the item type is 'Consumable'. Order by player_id and then by item_name.

[Assistant] SELECT pi.player_id, igi.item_name, pi.quantity FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items igi ON pi.item_id = igi.item_id WHERE pi.quantity > 5 AND igi.item_type = 'Consumable' ORDER BY pi.player_id, igi.item_name;

[User] For each game and month, I'd like to see how many sessions started, showing game_id, title, and start_month.

[Assistant]
SELECT g.game_id,
       g.title,
       DATE_TRUNC('month', gs.start_time) AS start_month,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
GROUP BY g.game_id, g.title, DATE_TRUNC('month', gs.start_time);

[User] Can you filter to only include months where the session_count is greater than 100 and also add the average session duration?

[Assistant]
SELECT g.game_id,
       g.title,
       DATE_TRUNC('month', gs.start_time) AS start_month,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
GROUP BY g.game_id, g.title, DATE_TRUNC('month', gs.start_time)
HAVING COUNT(gs.session_id) > 100;

[User] I would like to get the total number of sessions and the average score for each game, showing game_id and title.

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

[User] Could you exclude ongoing sessions from the calculation (where end_time is null)?

[Assistant]
SELECT g.game_id, g.title, COUNT(gs.session_id) AS total_sessions, AVG(gs.score) AS average_score
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
WHERE gs.end_time IS NOT NULL
GROUP BY g.game_id, g.title;

[User] Actually, only include games that have more than 50 sessions.

[Assistant]
SELECT g.game_id, g.title, COUNT(gs.session_id) AS total_sessions, AVG(gs.score) AS average_score
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
WHERE gs.end_time IS NOT NULL
GROUP BY g.game_id, g.title
HAVING COUNT(gs.session_id) > 50;

[User] Please also show the developer_id for each game.

[Assistant]
SELECT g.game_id, g.title, g.developer_id, COUNT(gs.session_id) AS total_sessions, AVG(gs.score) AS average_score
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
WHERE gs.end_time IS NOT NULL
GROUP BY g.game_id, g.title, g.developer_id
HAVING COUNT(gs.session_id) > 50;

[User] I need the total quantity of items each player has acquired, showing player_id and total_quantity.

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

[User] Actually, limit this to acquisitions in the last 7 days.

[Assistant]
SELECT player_id, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
WHERE acquired_at >= NOW() - INTERVAL '7 days'
GROUP BY player_id;

[User] Also include the count of distinct item types each player acquired in that period.

[Assistant]
SELECT player_id,
       COUNT(DISTINCT item_id) AS distinct_items,
       SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
WHERE acquired_at >= NOW() - INTERVAL '7 days'
GROUP BY player_id;

[User] Finally, only show players whose total_quantity exceeds 100.

[Assistant]
SELECT player_id,
       COUNT(DISTINCT item_id) AS distinct_items,
       SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
WHERE acquired_at >= NOW() - INTERVAL '7 days'
GROUP BY player_id
HAVING SUM(quantity) > 100;

[User] List all in-game items with their name, type, and rarity.

[Assistant] SELECT item_name, item_type, rarity FROM gaming_technology.in_game_items;

[User] Filter this list to include only items with 'Rare' or 'Epic' rarity and a cost amount greater than 0.

[Assistant] SELECT item_name, item_type, rarity, cost_amount FROM gaming_technology.in_game_items WHERE rarity IN ('Rare', 'Epic') AND cost_amount > 0;

[User] For these filtered items, count the total number of times each item appears in the player_inventory table (total acquisitions) and the number of unique players who acquired it.

[Assistant] SELECT igi.item_name, igi.item_type, igi.rarity, COUNT(pi.inventory_id) AS total_acquisitions, COUNT(DISTINCT pi.player_id) AS unique_players FROM gaming_technology.in_game_items AS igi JOIN gaming_technology.player_inventory AS pi ON igi.item_id = pi.item_id WHERE igi.rarity IN ('Rare', 'Epic') AND igi.cost_amount > 0 GROUP BY igi.item_name, igi.item_type, igi.rarity;

[User] Order the results by the total number of acquisitions descending and only show items with at least 5 total acquisitions.

[Assistant] SELECT igi.item_name, igi.item_type, igi.rarity, COUNT(pi.inventory_id) AS total_acquisitions, COUNT(DISTINCT pi.player_id) AS unique_players FROM gaming_technology.in_game_items AS igi JOIN gaming_technology.player_inventory AS pi ON igi.item_id = pi.item_id WHERE igi.rarity IN ('Rare', 'Epic') AND igi.cost_amount > 0 GROUP BY igi.item_name, igi.item_type, igi.rarity HAVING COUNT(pi.inventory_id) >= 5 ORDER BY total_acquisitions DESC;

[User] Which games have the highest average item cost for Legendary rarity items? Please show the game title, genre, and the average cost of those items.

[Assistant]
SELECT g.title, g.genre, AVG(igi.cost_amount) AS avg_legendary_cost
FROM gaming_technology.in_game_items igi
JOIN gaming_technology.games g ON igi.game_id = g.game_id
WHERE igi.rarity = 'Legendary' AND igi.cost_amount IS NOT NULL
GROUP BY g.title, g.genre
ORDER BY avg_legendary_cost DESC;

[User] Limit the result to only games that have at least 2 Legendary items.

[Assistant]
SELECT g.title, g.genre, AVG(igi.cost_amount) AS avg_legendary_cost
FROM gaming_technology.in_game_items igi
JOIN gaming_technology.games g ON igi.game_id = g.game_id
WHERE igi.rarity = 'Legendary' AND igi.cost_amount IS NOT NULL
GROUP BY g.title, g.genre
HAVING COUNT(igi.item_id) >= 2
ORDER BY avg_legendary_cost DESC;

[User] Can you also add the developer's name for each game?

[Assistant]
SELECT g.title, g.genre, d.name AS developer_name, AVG(igi.cost_amount) AS avg_legendary_cost
FROM gaming_technology.in_game_items igi
JOIN gaming_technology.games g ON igi.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE igi.rarity = 'Legendary' AND igi.cost_amount IS NOT NULL
GROUP BY g.title, g.genre, d.name
HAVING COUNT(igi.item_id) >= 2
ORDER BY avg_legendary_cost DESC;

[User] Now, restrict the results to games released after 2022-01-01.

[Assistant]
SELECT g.title, g.genre, d.name AS developer_name, AVG(igi.cost_amount) AS avg_legendary_cost
FROM gaming_technology.in_game_items igi
JOIN gaming_technology.games g ON igi.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE igi.rarity = 'Legendary'
  AND igi.cost_amount IS NOT NULL
  AND g.release_date > '2022-01-01'
GROUP BY g.title, g.genre, d.name
HAVING COUNT(igi.item_id) >= 2
ORDER BY avg_legendary_cost DESC;

[User] Show total session duration and average score for each player across all their sessions. Display the player ID, total duration, and average score.

[Assistant] SELECT player_id, SUM(duration_seconds) AS total_duration, AVG(score) AS average_score FROM gaming_technology.game_sessions GROUP BY player_id;

[User] Only include players whose total session duration is greater than 1 hour (3600 seconds).

[Assistant] SELECT player_id, SUM(duration_seconds) AS total_duration, AVG(score) AS average_score FROM gaming_technology.game_sessions GROUP BY player_id HAVING SUM(duration_seconds) > 3600;

[User] For these players, show the title of the game they spent the most time playing and the total duration for that game.

[Assistant] WITH PlayerTotalDuration AS (SELECT player_id, SUM(duration_seconds) AS overall_total_duration FROM gaming_technology.game_sessions GROUP BY player_id HAVING SUM(duration_seconds) > 3600), PlayerGameDuration AS (SELECT player_id, game_id, SUM(duration_seconds) AS game_total_duration, ROW_NUMBER() OVER(PARTITION BY player_id ORDER BY SUM(duration_seconds) DESC) as rn FROM gaming_technology.game_sessions WHERE player_id IN (SELECT player_id FROM PlayerTotalDuration) GROUP BY player_id, game_id) SELECT ptd.player_id, g.title AS most_played_game_title, pgd.game_total_duration FROM PlayerTotalDuration AS ptd JOIN PlayerGameDuration AS pgd ON ptd.player_id = pgd.player_id AND pgd.rn = 1 JOIN gaming_technology.games AS g ON pgd.game_id = g.game_id;

[User] Can you provide a list of all players who have acquired at least one item, along with the item name, its type, and the title of the game that item belongs to?

[Assistant]
SELECT pi.player_id, items.item_name, items.item_type, g.title AS game_title
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.games g ON items.game_id = g.game_id
GROUP BY pi.player_id, items.item_name, items.item_type, g.title;

[User] Actually, I'd like to only see cases where a player has acquired more than 2 different types of items. Can you adjust the query?

[Assistant]
SELECT pi.player_id, items.item_name, items.item_type, g.title AS game_title
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.games g ON items.game_id = g.game_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id, items.item_name, items.item_type, g.title;

[User] I'd also like to know the total quantity of items each qualifying player has acquired. Can you add that to the results?

[Assistant]
SELECT pi.player_id, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id;

[User] Can you also display the country of each player if I had such a 'country_code' column in a 'players' table? Show it in the result along with the player_id and total_quantity.

[Assistant]
SELECT pi.player_id, p.country_code, SUM(pi.quantity) AS total_quantity
FROM gaming_technology.player_inventory pi
JOIN gaming_technology.in_game_items items ON pi.item_id = items.item_id
JOIN gaming_technology.players p ON pi.player_id = p.player_id
WHERE pi.player_id IN (
    SELECT pi2.player_id
    FROM gaming_technology.player_inventory pi2
    JOIN gaming_technology.in_game_items items2 ON pi2.item_id = items2.item_id
    GROUP BY pi2.player_id
    HAVING COUNT(DISTINCT items2.item_type) > 2
)
GROUP BY pi.player_id, p.country_code;

[User] Which games were developed by companies in 'United Kingdom'? List the game title and the developer's name.

[Assistant] SELECT T1.title, T2.name FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T2.country = 'United Kingdom';

[User] For these games, what is the total duration of all game sessions played? Show game title and total duration in seconds.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title;

[User] Only include games where the total session duration is more than 1000000 seconds.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title HAVING SUM(T3.duration_seconds) > 1000000;

[User] Order the results by total duration in descending order and limit to the top 5.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title HAVING SUM(T3.duration_seconds) > 1000000 ORDER BY total_duration DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )

[User] List all active SUI coins (status 'exists') with their `coin_type`, `symbol`, `name`, and the total balance across all owners.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
GROUP BY sc.coin_type, sm.symbol, sm.name;

[User] Only include coins where the description contains 'staking'.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
  AND sm.description LIKE '%staking%'
GROUP BY sc.coin_type, sm.symbol, sm.name;

[User] Also show the number of distinct owners per `coin_type`.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
  AND sm.description LIKE '%staking%'
GROUP BY sc.coin_type, sm.symbol, sm.name;

[User] Finally, sort by `total_balance` descending and limit to the top 3 coins.

[Assistant]
SELECT sc.coin_type,
       sm.symbol,
       sm.name,
       SUM(CAST(sc.balance AS bigint)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm
  ON sc.coin_type = sm.coin_type
WHERE sc.status = 'exists'
  AND sm.status = 'exists'
  AND sm.description LIKE '%staking%'
GROUP BY sc.coin_type, sm.symbol, sm.name
ORDER BY total_balance DESC
LIMIT 3;

[User] Which SUI coins are currently marked as 'exists' and have a balance over 500000 for any owner? Please show the coin_type, balance, and owner.

[Assistant] SELECT coin_type, balance, owner FROM sui_coins WHERE status = 'exists' AND CAST(balance AS bigint) > 500000;

[User] Can you also include the symbol and name of each coin by joining with the sui_coins_metadata table?

[Assistant] SELECT sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND CAST(sc.balance AS bigint) > 500000;

[User] Only include coins where the description in the metadata contains the word 'reward'.

[Assistant] SELECT sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND CAST(sc.balance AS bigint) > 500000 AND scm.description ILIKE '%reward%';

[User] Actually, limit the results to the top 10 coins with the highest balance.

[Assistant] SELECT sc.coin_type, sc.balance, sc.owner, scm.symbol, scm.name FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE sc.status = 'exists' AND CAST(sc.balance AS bigint) > 500000 AND scm.description ILIKE '%reward%' ORDER BY CAST(sc.balance AS bigint) DESC LIMIT 10;

[User] List all ERC20 tokens (from token_metas) that have 'Governance' in their name.

[Assistant] SELECT contract_address, symbol, name FROM token_metas WHERE is_erc20 = 1 AND name ILIKE '%Governance%';

[User] For these tokens, show their total_supply and decimals as well.

[Assistant] SELECT contract_address, symbol, name, total_supply, decimals FROM token_metas WHERE is_erc20 = 1 AND name ILIKE '%Governance%';

[User] Now, join with token_prices_latest to add the latest price for each token.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.name ILIKE '%Governance%';

[User] Restrict results to only tokens with a latest price above 5.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.is_erc20 = 1 AND tm.name ILIKE '%Governance%' AND tpl.price > 5;

[User] List the ERC20 tokens (from token_metas) with exactly 6 decimals. Show their symbol, contract_address, and name.

[Assistant] SELECT symbol, contract_address, name FROM token_metas WHERE is_erc20 = 1 AND decimals = 6;

[User] Can you also include the total current supply for each token?

[Assistant] SELECT symbol, contract_address, name, total_supply FROM token_metas WHERE is_erc20 = 1 AND decimals = 6;

[User] Now, join with token_prices_latest to also include the latest price for each token.

[Assistant]
SELECT tm.symbol, tm.contract_address, tm.name, tm.total_supply, tpl.price AS latest_price
FROM token_metas tm
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
WHERE tm.is_erc20 = 1 AND tm.decimals = 6;

[User] Only include tokens where the latest price is between 0.5 and 2.0 USD, and limit the result to the top 5 tokens by price descending.

[Assistant]
SELECT tm.symbol, tm.contract_address, tm.name, tm.total_supply, tpl.price AS latest_price
FROM token_metas tm
JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tpl.blockchain = 'Ethereum'
WHERE tm.is_erc20 = 1 AND tm.decimals = 6 AND tpl.price BETWEEN 0.5 AND 2.0
ORDER BY tpl.price DESC
LIMIT 5;

[User] Show all SUI coins owned by each address where the coin's status is 'exists'. Include the coin_type, owner, and balance.

[Assistant]
SELECT coin_type, owner, balance
FROM sui_coins
WHERE status = 'exists';

[User] Can you add the symbol and name for each coin by joining with sui_coins_metadata where the metadata status is also 'exists'?

[Assistant]
SELECT sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists';

[User] Only include coins where the balance is greater than 1,000,000 and sort by balance descending. Limit to the top 10 results.

[Assistant]
SELECT sc.coin_type, sc.owner, sc.balance, scm.symbol, scm.name
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists' AND sc.balance > '1000000'
ORDER BY sc.balance DESC
LIMIT 10;

[User] For each Avalanche token tick, calculate the total transfer volume and transaction count over the past 7 days using token_activities_avalanche. Include the token tick, total_volume, and tx_count.

[Assistant]
SELECT
  tick,
  SUM(amt) AS total_volume,
  COUNT(*) AS tx_count
FROM token_activities_avalanche
WHERE block_timestamp >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY tick;

[User] Also include the creator address from token_info for each tick, and filter where total_volume > 1000 and creator starts with '0x1'.

[Assistant]
SELECT
  a.tick,
  SUM(a.amt) AS total_volume,
  COUNT(*) AS tx_count,
  i.creator
FROM token_activities_avalanche a
JOIN token_info i
  ON a.tick = i.tick
WHERE a.block_timestamp >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY a.tick, i.creator
HAVING SUM(a.amt) > 1000
  AND i.creator LIKE '0x1%';

[User] Sort the results by total_volume descending and limit to the top 5 tokens.

[Assistant]
SELECT
  a.tick,
  SUM(a.amt) AS total_volume,
  COUNT(*) AS tx_count,
  i.creator
FROM token_activities_avalanche a
JOIN token_info i
  ON a.tick = i.tick
WHERE a.block_timestamp >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY a.tick, i.creator
HAVING SUM(a.amt) > 1000
  AND i.creator LIKE '0x1%'
ORDER BY total_volume DESC
LIMIT 5;

[User] Show me all wallets holding SUI coins with a balance greater than 2,000,000. Include the coin_type, balance, and owner address.

[Assistant] SELECT coin_type, balance, owner FROM sui_coins WHERE status = 'exists' AND CAST(balance AS bigint) > 2000000;

[User] Can you also include the name and symbol of each coin by joining with the metadata table?

[Assistant]
SELECT sc.coin_type, scm.name, scm.symbol, sc.balance, sc.owner
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS bigint) > 2000000;

[User] I want to limit the result to coins whose description contains 'staking'.

[Assistant]
SELECT sc.coin_type, scm.name, scm.symbol, sc.balance, sc.owner, scm.description
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS bigint) > 2000000 AND LOWER(scm.description) LIKE '%staking%';

[User] Now sort the results by balance in descending order and show only the top 10 records.

[Assistant]
SELECT sc.coin_type, scm.name, scm.symbol, sc.balance, sc.owner, scm.description
FROM sui_coins sc
JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type
WHERE sc.status = 'exists' AND scm.status = 'exists' AND CAST(sc.balance AS bigint) > 2000000 AND LOWER(scm.description) LIKE '%staking%'
ORDER BY CAST(sc.balance AS bigint) DESC
LIMIT 10;

[User] Show me all ERC20 token contracts that have had at least 200 approvals. Include the token symbol and total approval count.

[Assistant]
SELECT m.contract_address, m.symbol, COUNT(*) AS approval_count
FROM erc20_approval a
JOIN token_metas m ON a.contract_address = m.contract_address
GROUP BY m.contract_address, m.symbol
HAVING COUNT(*) >= 200;

[User] Can you also show the name and decimals for each of these tokens?

[Assistant]
SELECT m.contract_address, m.symbol, m.name, m.decimals, COUNT(*) AS approval_count
FROM erc20_approval a
JOIN token_metas m ON a.contract_address = m.contract_address
GROUP BY m.contract_address, m.symbol, m.name, m.decimals
HAVING COUNT(*) >= 200;

[User] Now, add the latest USD price for each token by joining with token_prices_latest.

[Assistant]
SELECT m.contract_address, m.symbol, m.name, m.decimals, COUNT(*) AS approval_count, tpl.price AS latest_usd_price
FROM erc20_approval a
JOIN token_metas m ON a.contract_address = m.contract_address
LEFT JOIN token_prices_latest tpl ON tpl.address = m.contract_address AND tpl.symbol = m.symbol
GROUP BY m.contract_address, m.symbol, m.name, m.decimals, tpl.price
HAVING COUNT(*) >= 200;

[User] Only include tokens where the latest price is above 2.0 USD and sort by latest price descending.

[Assistant]
SELECT m.contract_address, m.symbol, m.name, m.decimals, COUNT(*) AS approval_count, tpl.price AS latest_usd_price
FROM erc20_approval a
JOIN token_metas m ON a.contract_address = m.contract_address
LEFT JOIN token_prices_latest tpl ON tpl.address = m.contract_address AND tpl.symbol = m.symbol
WHERE tpl.price > 2.0
GROUP BY m.contract_address, m.symbol, m.name, m.decimals, tpl.price
HAVING COUNT(*) >= 200
ORDER BY tpl.price DESC;

[User] Show the contract address and total number of approvals for all ERC20 tokens from the erc20_approval table.

[Assistant]
SELECT contract_address, COUNT(*) AS total_approvals
FROM erc20_approval
GROUP BY contract_address;

[User] Can you also include each token's symbol and name from the token_metas table?

[Assistant]
SELECT ea.contract_address, tm.symbol, tm.name, COUNT(*) AS total_approvals
FROM erc20_approval ea
JOIN token_metas tm ON ea.contract_address = tm.contract_address
GROUP BY ea.contract_address, tm.symbol, tm.name;

[User] Only show tokens that have more than 50 total approvals.

[Assistant]
SELECT ea.contract_address, tm.symbol, tm.name, COUNT(*) AS total_approvals
FROM erc20_approval ea
JOIN token_metas tm ON ea.contract_address = tm.contract_address
GROUP BY ea.contract_address, tm.symbol, tm.name
HAVING COUNT(*) > 50;

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

[Assistant]
SELECT ea.contract_address, tm.symbol, tm.name, COUNT(*) AS total_approvals
FROM erc20_approval ea
JOIN token_metas tm ON ea.contract_address = tm.contract_address
GROUP BY ea.contract_address, tm.symbol, tm.name
HAVING COUNT(*) > 50
ORDER BY total_approvals DESC;

[User] Show me all Sui coins with at least 6 decimal places and status 'exists' from the metadata table. List coin_type, symbol, name, and decimals.

[Assistant]
SELECT coin_type, symbol, name, decimals
FROM sui_coins_metadata
WHERE status = 'exists' AND decimals >= 6;

[User] Can you show the total balance for each coin_type by joining sui_coins, only if the coin status is also 'exists' in sui_coins?

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, SUM(sc.balance::numeric) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND scm.decimals >= 6 AND sc.status = 'exists'
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals;

[User] Now, only include coin types with total_balance over 1,000,000. Please also add the description column from the metadata.

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description, SUM(sc.balance::numeric) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND scm.decimals >= 6 AND sc.status = 'exists'
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description
HAVING SUM(sc.balance::numeric) > 1000000;

[User] Order the results by total_balance descending and only return the top 5 coins.

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description, SUM(sc.balance::numeric) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND scm.decimals >= 6 AND sc.status = 'exists'
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals, scm.description
HAVING SUM(sc.balance::numeric) > 1000000
ORDER BY total_balance DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)

[User] I need to find all pairs of diagnoses for the same patient where one diagnosis is chronic and the other is non-chronic. Show patient_id, chronic diagnosis_id as chronic_id, non-chronic diagnosis_id as acute_id, chronic diagnosis_date, and acute diagnosis_date.

[Assistant]
SELECT d1.patient_id,
       d1.diagnosis_id AS chronic_id,
       d2.diagnosis_id AS acute_id,
       d1.diagnosis_date AS chronic_date,
       d2.diagnosis_date AS acute_date
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.patient_id = d2.patient_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = FALSE;

[User] Actually, only include pairs where the chronic diagnosis date is after the acute diagnosis date.

[Assistant]
SELECT d1.patient_id,
       d1.diagnosis_id AS chronic_id,
       d2.diagnosis_id AS acute_id,
       d1.diagnosis_date AS chronic_date,
       d2.diagnosis_date AS acute_date
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.patient_id = d2.patient_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = FALSE
  AND d1.diagnosis_date > d2.diagnosis_date;

[User] Also restrict the results to diagnoses made in 2023.

[Assistant]
SELECT d1.patient_id,
       d1.diagnosis_id AS chronic_id,
       d2.diagnosis_id AS acute_id,
       d1.diagnosis_date AS chronic_date,
       d2.diagnosis_date AS acute_date
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.patient_id = d2.patient_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = FALSE
  AND d1.diagnosis_date > d2.diagnosis_date
  AND d1.diagnosis_date BETWEEN '2023-01-01' AND '2023-12-31'
  AND d2.diagnosis_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Which diagnosis codes have been used for more than 5 different patients? Show the diagnosis_code and the patient count.

[Assistant] SELECT diagnosis_code, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.diagnoses GROUP BY diagnosis_code HAVING COUNT(DISTINCT patient_id) > 5;

[User] Please also show the code_type for each diagnosis_code in the results.

[Assistant] SELECT diagnosis_code, code_type, COUNT(DISTINCT patient_id) AS patient_count FROM healthcare.diagnoses GROUP BY diagnosis_code, code_type HAVING COUNT(DISTINCT patient_id) > 5;

[User] Provide the count of diagnoses by status.

[Assistant]
SELECT status,
       COUNT(*) AS count
FROM healthcare.diagnoses
GROUP BY status;

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

[Assistant]
SELECT status,
       COUNT(*) AS count
FROM healthcare.diagnoses
GROUP BY status
HAVING COUNT(*) > 10;

[User] Find the diagnosis code and description for all non-chronic diagnoses for patient 'patient_789' made by doctor 'doctor_abc'.

[Assistant] SELECT diagnosis_code, description FROM healthcare.diagnoses WHERE patient_id = 'patient_789' AND doctor_id = 'doctor_abc' AND is_chronic = false;

[User] List all pairs of diagnoses that belong to the same medical record. Show record_id, diagnosis_id from the first entry as diag1_id, and diagnosis_id from the second entry as diag2_id.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id;

[User] Only include pairs where both diagnoses are chronic.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = TRUE;

[User] Can you list all chronic diagnoses made in January 2024, showing diagnosis_id, diagnosis_code, and status, along with the doctor_id who made each diagnosis?

[Assistant] SELECT diagnosis_id, diagnosis_code, status, doctor_id FROM healthcare.diagnoses WHERE is_chronic = true AND diagnosis_date >= '2024-01-01' AND diagnosis_date < '2024-02-01';

[User] Add the patient_id and sort the results first by doctor_id ascending and then diagnosis_date ascending.

[Assistant] SELECT diagnosis_id, diagnosis_code, status, doctor_id, patient_id FROM healthcare.diagnoses WHERE is_chronic = true AND diagnosis_date >= '2024-01-01' AND diagnosis_date < '2024-02-01' ORDER BY doctor_id ASC, diagnosis_date ASC;

[User] Count how many diagnoses entries are currently marked as 'Resolved'.

[Assistant] SELECT COUNT(*) FROM healthcare.diagnoses WHERE status = 'Resolved';

[User] Provide a count of diagnoses for each status, grouped by the code type.

[Assistant] SELECT code_type, status, COUNT(*) FROM healthcare.diagnoses GROUP BY code_type, status;

[User] Filter this result to only show code types where the total number of diagnoses across all statuses for that code type is greater than 50.

[Assistant] SELECT code_type, status, COUNT(*) FROM healthcare.diagnoses GROUP BY code_type, status HAVING code_type IN (SELECT code_type FROM healthcare.diagnoses GROUP BY code_type HAVING COUNT(*) > 50);

[User] List the patient ID and subscriber name for all patients who have both at least one diagnosis recorded and at least one primary insurance policy.

[Assistant] SELECT DISTINCT pi.patient_id, pi.subscriber_name FROM healthcare.patient_insurance pi JOIN healthcare.diagnoses d ON pi.patient_id = d.patient_id WHERE pi.is_primary = true;

[User] Refine this list to only include patients whose most recent diagnosis is marked as chronic.

[Assistant] WITH LatestDiagnosis AS ( SELECT patient_id, diagnosis_id, diagnosis_date, is_chronic, ROW_NUMBER() OVER(PARTITION BY patient_id ORDER BY diagnosis_date DESC) as rn FROM healthcare.diagnoses ) SELECT DISTINCT pi.patient_id, pi.subscriber_name FROM healthcare.patient_insurance pi JOIN LatestDiagnosis ld ON pi.patient_id = ld.patient_id WHERE pi.is_primary = true AND ld.rn = 1 AND ld.is_chronic = true;

[User] For each doctor, count the number of chronic diagnoses they have made. Show the doctor's full name and the count.

[Assistant] SELECT doc.first_name, doc.last_name, COUNT(d.diagnosis_id) FROM healthcare.doctors doc JOIN healthcare.diagnoses d ON doc.doctor_id = d.doctor_id WHERE d.is_chronic = TRUE GROUP BY doc.doctor_id, doc.first_name, doc.last_name ORDER BY COUNT(d.diagnosis_id) 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 hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    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] List all reviews that have a staff response, including the review comment, staff response text, and the ID of the staff who responded.

[Assistant] SELECT comment, staff_response, response_staff_id FROM hospitality_technology.reviews WHERE staff_response IS NOT NULL

[User] Filter this list to only include reviews submitted in 2023 with an overall rating of 3 or less.

[Assistant] SELECT comment, staff_response, response_staff_id FROM hospitality_technology.reviews WHERE staff_response IS NOT NULL AND EXTRACT(YEAR FROM review_date) = 2023 AND rating_overall <= 3

[User] Now, only show responses from staff members whose position is 'Front Desk'.

[Assistant] SELECT r.comment, r.staff_response, s.staff_id, s.first_name, s.last_name, s.position 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 AND EXTRACT(YEAR FROM r.review_date) = 2023 AND r.rating_overall <= 3 AND s.position = 'Front Desk'

[User] Which room types have a base rate above 250 USD, and what are their maximum occupancies?

[Assistant]
SELECT room_type_id, type_name, base_rate, max_occupancy
FROM hospitality_technology.room_types
WHERE base_rate > 250;

[User] For these room types, can you also add the property_id?

[Assistant]
SELECT room_type_id, property_id, type_name, base_rate, max_occupancy
FROM hospitality_technology.room_types
WHERE base_rate > 250;

[User] Now join this with the payments table to show the total payment amount for each property where such a room type exists.

[Assistant]
SELECT r.property_id, SUM(p.amount) AS total_payment_amount
FROM hospitality_technology.room_types r
JOIN hospitality_technology.payments p ON r.property_id = p.reservation_id
WHERE r.base_rate > 250
GROUP BY r.property_id;

[User] Retrieve all room types with a base_rate above 150 for each property.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150;

[User] Also filter to only include room types with max_occupancy >= 3.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150
  AND max_occupancy >= 3;

[User] Finally, show guest first and last names of guests created after '2023-01-01' who could book these room types.

[Assistant]
SELECT g.first_name, g.last_name, rt.property_id, rt.type_name, rt.base_rate
FROM hospitality_technology.room_types rt
CROSS JOIN hospitality_technology.guests g
WHERE rt.base_rate > 150
  AND rt.max_occupancy >= 3
  AND g.created_at > '2023-01-01';

[User] List all staff members hired in 2024, showing their first name, last name, and hire date.

[Assistant] SELECT first_name, last_name, hire_date FROM hospitality_technology.staff WHERE EXTRACT(YEAR FROM hire_date) = 2024

[User] Now, only include those whose position is 'Manager'.

[Assistant] SELECT first_name, last_name, hire_date FROM hospitality_technology.staff WHERE EXTRACT(YEAR FROM hire_date) = 2024 AND position = 'Manager'

[User] Show me the full name of guests who have left reviews along with the overall rating they gave.

[Assistant] SELECT g.first_name, g.last_name, r.rating_overall FROM hospitality_technology.reviews r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id

[User] Filter this list to only include reviews with an overall rating of 4 or higher and order the results by overall rating descending then by review date descending.

[Assistant] SELECT g.first_name, g.last_name, r.rating_overall FROM hospitality_technology.reviews r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id WHERE r.rating_overall >= 4 ORDER BY r.rating_overall DESC, r.review_date DESC

[User] Show each staff member's first name, last name, and the average base rate of room types available at the property where they work.

[Assistant] SELECT T1.first_name, T1.last_name, T2.avg_base_rate FROM hospitality_technology.staff AS T1 JOIN (SELECT property_id, AVG(base_rate) AS avg_base_rate FROM hospitality_technology.room_types GROUP BY property_id) AS T2 ON T1.property_id = T2.property_id

[User] Show all service orders with the service_id, guest's full name, and the status of each order.

[Assistant]
SELECT so.order_id, so.service_id, g.first_name, g.last_name, so.status
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id;

[User] Only display service orders with status 'InProgress' or 'Pending', and sort them by order_timestamp ascending.

[Assistant]
SELECT so.order_id, so.service_id, g.first_name, g.last_name, so.status
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
WHERE so.status IN ('InProgress', 'Pending')
ORDER BY so.order_timestamp ASC;

[User] List properties and the average base rate of their room types.

[Assistant] SELECT T1.property_name ,  AVG(T2.base_rate) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id GROUP BY T1.property_name

[User] Filter to only show properties where the average base rate is above 250.

[Assistant] SELECT T1.property_name ,  AVG(T2.base_rate) FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id GROUP BY T1.property_name HAVING AVG(T2.base_rate)  >  250

[User] Also, only include properties in 'New York' or 'Florida' and order by average base rate descending.

[Assistant] SELECT T1.property_name ,  AVG(T2.base_rate) AS avg_base_rate FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id WHERE T1.state IN ('New York', 'Florida') GROUP BY T1.property_name HAVING AVG(T2.base_rate)  >  250 ORDER BY avg_base_rate DESC

[User] Show properties and the names of their room types.

[Assistant] SELECT T1.property_name ,  T2.type_name FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id

[User] Only list properties in 'California' and include the base rate.

[Assistant] SELECT T1.property_name ,  T2.type_name ,  T2.base_rate FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.room_types AS T2 ON T1.property_id  =  T2.property_id WHERE T1.state  =  'California'

[User] List all room types with their type name, base rate, and the name of the property they belong to.

[Assistant]
SELECT rt.room_type_id, rt.type_name, rt.base_rate, p.property_name
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_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 financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)

[User] For each customer, provide a summary of their account statuses, showing their full name, account status, and the count of accounts for each status.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status ORDER BY c.last_name, c.first_name, a.status;

[User] Refine this to only include customers who have accounts in at least two different statuses.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status HAVING c.customer_id IN ( SELECT customer_id FROM financial_services.accounts GROUP BY customer_id HAVING COUNT(DISTINCT status) >= 2 ) ORDER BY c.last_name, c.first_name, a.status;

[User] For each customer, show their full name and the average amount of all transactions linked to any of their accounts.

[Assistant] SELECT c.first_name || ' ' || c.last_name AS customer_full_name, AVG(t.amount) AS average_transaction_amount FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id JOIN financial_services.transactions AS t ON a.account_id = t.account_id OR a.account_id = t.related_account_id GROUP BY c.customer_id, customer_full_name;

[User] Only consider transactions that occurred within the last 90 days for this calculation.

[Assistant] SELECT c.first_name || ' ' || c.last_name AS customer_full_name, AVG(t.amount) AS average_transaction_amount FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id JOIN financial_services.transactions AS t ON a.account_id = t.account_id OR a.account_id = t.related_account_id WHERE t.transaction_date >= CURRENT_DATE - INTERVAL '90 day' GROUP BY c.customer_id, customer_full_name;

[User] Filter the results to only show customers where this average transaction amount is greater than 1000.

[Assistant] SELECT c.first_name || ' ' || c.last_name AS customer_full_name, AVG(t.amount) AS average_transaction_amount FROM financial_services.customers AS c JOIN financial_services.accounts AS a ON c.customer_id = a.customer_id JOIN financial_services.transactions AS t ON a.account_id = t.account_id OR a.account_id = t.related_account_id WHERE t.transaction_date >= CURRENT_DATE - INTERVAL '90 day' GROUP BY c.customer_id, customer_full_name HAVING AVG(t.amount) > 1000;

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

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

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

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

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

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

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

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

[User] List all pairs of employees who work in the same department but at different branches. For each pair, show the employee_id and branch_id for both members.

[Assistant]
SELECT a.employee_id AS employee_id_a, a.branch_id AS branch_id_a, b.employee_id AS employee_id_b, b.branch_id AS branch_id_b, a.department
FROM financial_services.employees a
JOIN financial_services.employees b ON a.department = b.department AND a.employee_id < b.employee_id AND a.branch_id <> b.branch_id;

[User] Can you also add their full names and filter so only Active employees are included for both members of the pair?

[Assistant]
SELECT a.employee_id AS employee_id_a, a.first_name || ' ' || a.last_name AS name_a, a.branch_id AS branch_id_a,
       b.employee_id AS employee_id_b, b.first_name || ' ' || b.last_name AS name_b, b.branch_id AS branch_id_b, a.department
FROM financial_services.employees a
JOIN financial_services.employees b ON a.department = b.department AND a.employee_id < b.employee_id AND a.branch_id <> b.branch_id
WHERE a.status = 'Active' AND b.status = 'Active';

[User] Please include the job titles for both employees and order the results by a.department ascending, then by name_a ascending.

[Assistant]
SELECT a.employee_id AS employee_id_a, a.first_name || ' ' || a.last_name AS name_a, a.job_title AS job_title_a, a.branch_id AS branch_id_a,
       b.employee_id AS employee_id_b, b.first_name || ' ' || b.last_name AS name_b, b.job_title AS job_title_b, b.branch_id AS branch_id_b, a.department
FROM financial_services.employees a
JOIN financial_services.employees b ON a.department = b.department AND a.employee_id < b.employee_id AND a.branch_id <> b.branch_id
WHERE a.status = 'Active' AND b.status = 'Active'
ORDER BY a.department ASC, name_a ASC;

[User] Show me the account details (account_id, account_number, balance) for all active (status = 'Open') checking accounts opened in the last 6 months, along with the customer_id.

[Assistant] SELECT a.account_id, a.account_number, a.balance, a.customer_id FROM financial_services.accounts a WHERE a.account_type = 'Checking' AND a.status = 'Open' AND a.opened_date >= CURRENT_DATE - INTERVAL '6 months';

[User] Now modify the query to only include accounts with a balance greater than $10,000 and sort them by balance in descending order.

[Assistant] SELECT a.account_id, a.account_number, a.balance, a.customer_id FROM financial_services.accounts a WHERE a.account_type = 'Checking' AND a.status = 'Open' AND a.opened_date >= CURRENT_DATE - INTERVAL '6 months' AND a.balance > 10000 ORDER BY a.balance DESC;

[User] List all customer_ids who have both a checking account and a savings account with a combined balance exceeding $50,000.

[Assistant] SELECT c.customer_id FROM financial_services.accounts c JOIN financial_services.accounts s ON c.customer_id = s.customer_id WHERE c.account_type = 'Checking' AND s.account_type = 'Savings' AND (c.balance + s.balance) > 50000 GROUP BY c.customer_id;

[User] For each customer, show the number of open accounts and their combined balance, joining the accounts table with itself on customer_id for demonstration.

[Assistant]
SELECT a.customer_id, COUNT(a.account_id) AS open_accounts_count, SUM(a.balance) AS combined_balance
FROM financial_services.accounts a
WHERE a.status = 'Open'
GROUP BY a.customer_id;

[User] I got an error, can you show how to join the table to itself even though we are just using one source of data?

[Assistant]
SELECT a.customer_id, COUNT(a.account_id) AS open_accounts_count, SUM(a.balance) AS combined_balance
FROM financial_services.accounts a
JOIN financial_services.accounts b ON a.customer_id = b.customer_id
WHERE a.status = 'Open'
GROUP BY a.customer_id;

[User] Now, only show those customers who have more than 2 open accounts.

[Assistant]
SELECT a.customer_id, COUNT(a.account_id) AS open_accounts_count, SUM(a.balance) AS combined_balance
FROM financial_services.accounts a
JOIN financial_services.accounts b ON a.customer_id = b.customer_id
WHERE a.status = 'Open'
GROUP BY a.customer_id
HAVING COUNT(a.account_id) > 2;

[User] Show me all accounts (account_id, account_number, balance) that have a balance greater than $50,000 and are in USD currency, along with the security details (ticker_symbol, security_name) for securities traded on the same exchange as the account's last_updated_at date.

[Assistant] SELECT a.account_id, a.account_number, a.balance, s.ticker_symbol, s.security_name FROM financial_services.accounts a JOIN financial_services.securities s ON a.currency = s.currency WHERE a.balance > 50000 AND a.currency = 'USD' AND s.exchange IS NOT NULL;

[User] Now modify the query to only include accounts with status 'Open' and securities from the 'Technology' sector, sorted by account balance in descending order.

[Assistant] SELECT a.account_id, a.account_number, a.balance, s.ticker_symbol, s.security_name FROM financial_services.accounts a JOIN financial_services.securities s ON a.currency = s.currency WHERE a.balance > 50000 AND a.currency = 'USD' AND a.status = 'Open' AND s.sector = 'Technology' AND s.exchange IS NOT NULL ORDER BY a.balance DESC;

[User] Provide the average high price for securities on each exchange, using market data from the last 6 months.

[Assistant] SELECT s.exchange, AVG(md.high_price) AS average_high_price FROM financial_services.market_data AS md JOIN financial_services.securities AS s ON md.security_id = s.security_id WHERE md.data_timestamp >= CURRENT_DATE - INTERVAL '6 month' GROUP BY s.exchange;

[User] Exclude any exchanges where the total trading volume in this period is less than 1,000,000.

[Assistant] SELECT s.exchange, AVG(md.high_price) AS average_high_price FROM financial_services.market_data AS md JOIN financial_services.securities AS s ON md.security_id = s.security_id WHERE md.data_timestamp >= CURRENT_DATE - INTERVAL '6 month' GROUP BY s.exchange HAVING SUM(md.volume) >= 1000000;

[User] Order the results by the average high price in descending order.

[Assistant] SELECT s.exchange, AVG(md.high_price) AS average_high_price FROM financial_services.market_data AS md JOIN financial_services.securities AS s ON md.security_id = s.security_id WHERE md.data_timestamp >= CURRENT_DATE - INTERVAL '6 month' GROUP BY s.exchange HAVING SUM(md.volume) >= 1000000 ORDER BY average_high_price DESC;

[User] Summarize the accounts table by account type and currency, showing the average balance for each combination.

[Assistant] SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency ORDER BY account_type, currency;

[User] Only include combinations where the average balance is greater than 5000.

[Assistant] SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency HAVING AVG(balance) > 5000 ORDER BY average_balance 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.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )

[User] I need a list of genres and pairs of game titles in the same genre.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre;

[User] Please avoid duplicate pairs by ensuring each pair appears only once.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title;

[User] Only include genres that have at least three games.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  );

[User] Also sort the output by genre ascending and game1 ascending.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
WHERE g1.title < g2.title
  AND g1.genre IN (
    SELECT genre
    FROM gaming_technology.games
    GROUP BY genre
    HAVING COUNT(*) >= 3
  )
ORDER BY g1.genre ASC, g1.title ASC;

[User] List each game along with the title and release_date of the next game released by the same developer.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Actually, only include next games released within one year of the original game.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Also show the gap in days between the two release dates.

[Assistant]
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date,
       (g2.release_date - g1.release_date) AS days_gap
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY days_gap DESC;

[User] Finally, limit to developers who have at least 5 games.

[Assistant]
WITH dev_counts AS (
  SELECT developer_id, COUNT(*) AS game_count
  FROM gaming_technology.games
  GROUP BY developer_id
  HAVING COUNT(*) >= 5
)
SELECT g1.game_id AS original_game_id,
       g1.title AS original_title,
       g2.game_id AS next_game_id,
       g2.title AS next_title,
       g2.release_date AS next_release_date,
       (g2.release_date - g1.release_date) AS days_gap
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g2.release_date > g1.release_date
  AND g2.release_date <= g1.release_date + INTERVAL '1 year'
JOIN dev_counts dc
  ON g1.developer_id = dc.developer_id
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.games g3
  WHERE g3.developer_id = g1.developer_id
    AND g3.release_date > g1.release_date
    AND g3.release_date < g2.release_date
)
ORDER BY g1.developer_id, g1.release_date;

[User] Can you list each game alongside another game in the same genre but by a different developer?

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id;

[User] Exclude any pairs where either game was released before 2019.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01';

[User] Limit the output to the first 10 pairs ordered by genre and developer_id.

[Assistant]
SELECT g1.genre, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.genre = g2.genre
  AND g1.developer_id <> g2.developer_id
WHERE g1.release_date >= '2019-01-01'
  AND g2.release_date >= '2019-01-01'
ORDER BY g1.genre, g1.developer_id
LIMIT 10;

[User] I need a count of games per platform and the earliest release date on each platform.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform;

[User] Actually, only include platforms with at least 5 games.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5;

[User] Also, order the results by first_release ascending.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5
ORDER BY first_release ASC;

[User] And please exclude any records where platform is null.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
WHERE platform IS NOT NULL
GROUP BY platform
HAVING COUNT(*) >= 5
ORDER BY first_release ASC;

[User] How many games are there per platform, and what is the earliest release_date for each platform?

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform;

[User] Only include platforms with at least 10 games.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10;

[User] Sort the results by game_count descending.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10
ORDER BY game_count DESC;

[User] Also include the number of unique genres available on each platform.

[Assistant]
SELECT platform,
       COUNT(*) AS game_count,
       MIN(release_date) AS earliest_release,
       COUNT(DISTINCT genre) AS genre_count
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 10
ORDER BY game_count DESC;

[User] How many games are available on each platform?

[Assistant]
SELECT platform, COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY platform;

[User] Exclude platforms with fewer than five games.

[Assistant]
SELECT platform, COUNT(*) AS game_count
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5;

[User] Also show the earliest release_date for each platform.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5;

[User] Finally, order by game_count descending.

[Assistant]
SELECT platform, COUNT(*) AS game_count, MIN(release_date) AS first_release
FROM gaming_technology.games
GROUP BY platform
HAVING COUNT(*) >= 5
ORDER BY game_count DESC;

[User] List all pairs of games developed by the same developer, returning developer_id, title of the first game, and title of the second game.

[Assistant]
SELECT g1.developer_id, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id;

[User] Only include developers who have created more than 3 games.

[Assistant]
SELECT g1.developer_id, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
WHERE g1.developer_id IN (
  SELECT developer_id
  FROM gaming_technology.games
  GROUP BY developer_id
  HAVING COUNT(*) > 3
);

[User] Also show the total number of games each developer has made alongside each pair.

[Assistant]
SELECT g1.developer_id, cnt.total_games, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
JOIN (
  SELECT developer_id, COUNT(*) AS total_games
  FROM gaming_technology.games
  GROUP BY developer_id
) cnt ON g1.developer_id = cnt.developer_id
WHERE cnt.total_games > 3;

[User] I only want pairs where both games were released after '2021-01-01'.

[Assistant]
SELECT g1.developer_id, cnt.total_games, g1.title AS game1, g2.title AS game2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
JOIN (
  SELECT developer_id, COUNT(*) AS total_games
  FROM gaming_technology.games
  GROUP BY developer_id
) cnt ON g1.developer_id = cnt.developer_id
WHERE cnt.total_games > 3
  AND g1.release_date > '2021-01-01'
  AND g2.release_date > '2021-01-01';

[User] Which developers founded after 2010 have published games using the 'Unreal Engine'? List the developer's name, country, game title, and the release year.

[Assistant]
SELECT d.name AS developer_name, d.country, g.title AS game_title, EXTRACT(YEAR FROM g.release_date) AS release_year
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine';

[User] Show only games released in or after 2022.

[Assistant]
SELECT d.name AS developer_name, d.country, g.title AS game_title, EXTRACT(YEAR FROM g.release_date) AS release_year
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine' AND g.release_date >= '2022-01-01';

[User] Include the developer's website and the full release date for each game.

[Assistant]
SELECT d.name AS developer_name, d.country, d.website AS developer_website, g.title AS game_title, g.release_date
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine' AND g.release_date >= '2022-01-01';

[User] Now, limit the results to developers located in 'Canada'.

[Assistant]
SELECT d.name AS developer_name, d.country, d.website AS developer_website, g.title AS game_title, g.release_date
FROM gaming_technology.developers d
JOIN gaming_technology.games g
  ON d.developer_id = g.developer_id
WHERE d.founded_year > 2010 AND g.engine = 'Unreal Engine' AND g.release_date >= '2022-01-01' AND d.country = 'Canada';

[User] For each year since 2015, show the total number of games released per year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
ORDER BY year ASC;

[User] Include the number of distinct developers who released games each year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
ORDER BY year ASC;

[User] Now only show years where more than 20 games were released.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
HAVING COUNT(*) > 20
ORDER BY year ASC;

[User] Please also add the average number of games released per developer for each year.

[Assistant]
SELECT EXTRACT(YEAR FROM release_date) AS year, COUNT(*) AS total_games, COUNT(DISTINCT developer_id) AS developer_count, ROUND(COUNT(*)::numeric / NULLIF(COUNT(DISTINCT developer_id), 0), 2) AS avg_games_per_developer
FROM gaming_technology.games
WHERE release_date >= '2015-01-01'
GROUP BY year
HAVING COUNT(*) > 20
ORDER BY year ASC;

[User] List all games released in 2023 along with their titles, platforms, and the names of their developers.

[Assistant]
SELECT g.game_id, g.title, g.platform, d.name AS developer_name
FROM gaming_technology.games g
JOIN gaming_technology.developers d
  ON g.developer_id = d.developer_id
WHERE g.release_date >= '2023-01-01' AND g.release_date <= '2023-12-31';

[User] Also include the country of each developer in the output.

[Assistant]
SELECT g.game_id, g.title, g.platform, d.name AS developer_name, d.country AS developer_country
FROM gaming_technology.games g
JOIN gaming_technology.developers d
  ON g.developer_id = d.developer_id
WHERE g.release_date >= '2023-01-01' AND g.release_date <= '2023-12-31';