System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 train_station_management.train_cars (
    car_id character varying(64) NOT NULL, -- Unique identifier for the train car
    train_id character varying(64) NOT NULL, -- Foreign key referencing trains
    car_number character varying(10) NOT NULL, -- Identifier of the car within the train set
    car_type character varying(64) NOT NULL, -- e.g., Locomotive, Passenger, Sleeper, Dining, Baggage
    class character varying(32), -- e.g., First, Business, Economy (null for non-passenger cars)
    capacity integer, -- Passenger capacity of this specific car (null for non-passenger cars)
    features text, -- Comma-separated list of features (e.g., 'WiFi', 'Power Outlet', 'Accessible Restroom')
    PRIMARY KEY (car_id),
    FOREIGN KEY (train_id) REFERENCES train_station_management.trains(train_id)
)

[User] What is the current location of a specific train car with car_id 'TC123'?

[Assistant] I'm sorry, but I can't provide the current location of a specific train car as this information is not stored in the database table. The table only contains static details about train cars such as car type, capacity, and features. For real-time location data, please refer to the train tracking system or contact the relevant department.

[User] Can you help me find the total passenger capacity for each train car on a specific route with route_id 'RT123'?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL;

[User] Can you modify the query to include only passenger cars with a capacity greater than 50?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you also add the route name and description to the result?

[Assistant]
SELECT tc.train_id, tc.car_id, tc.car_number, tc.capacity, r.route_name, r.description
FROM train_station_management.train_cars tc
JOIN train_station_management.trains t ON tc.train_id = t.train_id
JOIN train_station_management.routes r ON t.route_id = r.route_id
WHERE r.route_id = 'RT123' AND tc.capacity IS NOT NULL AND tc.capacity > 50;

[User] Can you assist me in finding all staff members assigned to schedules for a specific route with route_id 'RT456', including the train details and schedule status?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.schedules s ON s.train_id = st.primary_station_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] I noticed the query might not be correct. Can you revise it to ensure it connects staff to schedules properly through their primary station or related data?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456';

[User] Can you filter the results to include only staff with the role of 'Engineer' and schedules with status 'On Time'?

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, st.role, s.schedule_id, s.status, t.train_id
FROM train_station_management.staff st
JOIN train_station_management.route_stations rs ON st.primary_station_id = rs.station_id
JOIN train_station_management.schedules s ON s.route_id = rs.route_id
JOIN train_station_management.trains t ON s.train_id = t.train_id
WHERE s.route_id = 'RT456' AND st.role = 'Engineer' AND s.status = 'On Time';

[User] Can you retrieve the total number of tickets sold for each car type?

[Assistant]
SELECT tc.car_type, COUNT(t.ticket_id) AS total_tickets
FROM train_station_management.train_cars tc
JOIN train_station_management.tickets t ON tc.car_id = t.car_id
GROUP BY tc.car_type;

[User] Can you help me get the total number of passenger cars for each train car type in the database?

[Assistant]
SELECT car_type, COUNT(*) as total_cars
FROM train_station_management.train_cars
WHERE car_type = 'Passenger'
GROUP BY car_type;

[User] I need to find all tickets for a specific route 'RT456' along with the car details and route information.

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456';

[User] Can you filter this to show only tickets that have been checked in?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

[User] Can you also add the ticket type to the results?

[Assistant]
SELECT t.ticket_id, t.seat_number, t.price, t.ticket_type, tc.car_number, tc.car_type, r.route_name, r.description
FROM train_station_management.tickets t
JOIN train_station_management.train_cars tc ON t.car_id = tc.car_id
JOIN train_station_management.trains tr ON tc.train_id = tr.train_id
JOIN train_station_management.routes r ON tr.route_id = r.route_id
WHERE r.route_id = 'RT456' AND t.is_checked_in = true;

[User] Can you help me retrieve the details of all bookings for a specific route with route_id 'RT789', including the passenger names and the scheduled departure times?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789';

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

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

[User] Can you also add the route name and origin station ID to the results?

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending';

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

[Assistant]
SELECT b.booking_id, p.first_name, p.last_name, s.departure_datetime, b.status, b.total_price, r.route_name, r.origin_station_id
FROM train_station_management.bookings b
JOIN train_station_management.passengers p ON b.passenger_id = p.passenger_id
JOIN train_station_management.schedules s ON b.schedule_id = s.schedule_id
JOIN train_station_management.routes r ON s.route_id = r.route_id
WHERE s.route_id = 'RT789' AND b.status = 'Pending'
ORDER BY s.departure_datetime DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] List all contracts along with the username of the deployer, showing contract_id, contract address, deployed_at, and the username. Order by deployed_at descending.

[Assistant]
SELECT c.contract_id,
       c.address AS contract_address,
       c.deployed_at,
       u.username
FROM web3.contracts c
LEFT JOIN web3.wallets w ON c.deployer_address = w.address
LEFT JOIN web3.users u ON w.user_id = u.user_id
ORDER BY c.deployed_at DESC;

[User] Show each token's symbol, token_name, and the deployer_address and status of the contract where that token was created.

[Assistant]
SELECT t.token_symbol,
       t.token_name,
       c.deployer_address,
       c.status
FROM web3.tokens t
JOIN web3.contracts c ON t.contract_address = c.address;

[User] Get the total value and average gas_price for each from_address in transactions, but only include senders who have sent more than 5 transactions.

[Assistant]
SELECT from_address,
       SUM(value) AS total_value,
       AVG(gas_price) AS avg_gas_price,
       COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) > 5;

[User] Actually, I also want to include the number of distinct to_address recipients for each sender.

[Assistant]
SELECT from_address,
       SUM(value) AS total_value,
       AVG(gas_price) AS avg_gas_price,
       COUNT(*) AS tx_count,
       COUNT(DISTINCT to_address) AS distinct_recipients
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) > 5;

[User] Find all contracts deployed by users who have also conducted transactions with a value greater than 1 ETH (where 1 ETH = 1e18 wei).

[Assistant] SELECT DISTINCT c.contract_id, c.address, c.deployer_address FROM web3.contracts c JOIN web3.transactions t ON c.deployer_address = t.from_address WHERE t.value > 1e18;

[User] Show the number of wallets created for each user. Return user_id and wallet_count.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id;

[User] Now, can you only show users with more than 2 wallets in the result?

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM web3.wallets
GROUP BY user_id
HAVING COUNT(*) > 2;

[User] Find all tokens with their contract addresses and the number of wallets that hold each token, sorted by wallet count in descending order.

[Assistant] SELECT t.token_id, t.contract_address, COUNT(DISTINCT w.wallet_id) AS wallet_count FROM web3.tokens t LEFT JOIN web3.transactions tr ON t.contract_address = tr.to_address OR t.contract_address = tr.from_address JOIN web3.wallets w ON tr.from_address = w.address OR tr.to_address = w.address GROUP BY t.token_id, t.contract_address ORDER BY wallet_count DESC;

[User] Show me all contracts deployed on the 'ethereum' network along with their deployer addresses and the count of transactions they've been involved in, sorted by transaction count in descending order.

[Assistant] SELECT c.contract_id, c.address, c.deployer_address, COUNT(t.transaction_id) AS transaction_count FROM web3.contracts c LEFT JOIN web3.transactions t ON c.address = t.to_address OR c.address = t.from_address WHERE c.network_id = 'ethereum' GROUP BY c.contract_id, c.address, c.deployer_address ORDER BY transaction_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )

[User] Can you show me the number of lawyers grouped by specialization?

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization;

[User] Include only specializations that have more than two lawyers.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Also show the average tenure in years for each of those specializations.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2;

[User] Order the result by average tenure in descending order.

[Assistant] SELECT specialization, COUNT(*) AS lawyer_count, AVG(EXTRACT(EPOCH FROM (NOW() - hire_date)) / 31536000) AS avg_tenure_years FROM lawyers GROUP BY specialization HAVING COUNT(*) > 2 ORDER BY avg_tenure_years DESC;

[User] Show me the first_name, last_name, and firm_id of all lawyers whose email domain is 'legalfirm.com'.

[Assistant]
SELECT first_name,
       last_name,
       firm_id
FROM legal_services.lawyers
WHERE SPLIT_PART(email, '@', 2) = 'legalfirm.com';

[User] Find all pairs of lawyers who work for the same firm, showing each lawyer's first_name, last_name, email, and firm_id.

[Assistant]
SELECT l1.first_name AS lawyer1_first_name,
       l1.last_name AS lawyer1_last_name,
       l1.email AS lawyer1_email,
       l2.first_name AS lawyer2_first_name,
       l2.last_name AS lawyer2_last_name,
       l2.email AS lawyer2_email,
       l1.firm_id
FROM legal_services.lawyers l1
JOIN legal_services.lawyers l2
  ON l1.firm_id = l2.firm_id
  AND l1.lawyer_id < l2.lawyer_id;

[User] Show me the number of lawyers for each law firm, along with the firm's ID.

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count FROM legal_services.lawyers GROUP BY firm_id;

[User] Can you also include the number of partners per firm in the result?

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count, SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) AS partner_count FROM legal_services.lawyers GROUP BY firm_id;

[User] Please restrict the results to only those firms that have more than 3 partners.

[Assistant] SELECT firm_id, COUNT(*) AS lawyer_count, SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) AS partner_count FROM legal_services.lawyers GROUP BY firm_id HAVING SUM(CASE WHEN is_partner THEN 1 ELSE 0 END) > 3;

[User] How many lawyers are there in each specialization, and what is the count per specialization?

[Assistant]
SELECT specialization,
       COUNT(*) AS lawyer_count
FROM legal_services.lawyers
GROUP BY specialization;

[User] List all pairs of lawyers from the same firm who were hired in the same month and year. Include each lawyer's first_name, last_name, firm_id, and the shared hire_month_year.

[Assistant]
SELECT a.first_name AS lawyer1_first_name,
       a.last_name  AS lawyer1_last_name,
       b.first_name AS lawyer2_first_name,
       b.last_name  AS lawyer2_last_name,
       a.firm_id,
       TO_CHAR(a.hire_date, 'YYYY-MM') AS hire_month_year
FROM legal_services.lawyers a
JOIN legal_services.lawyers b
  ON a.firm_id = b.firm_id
 AND TO_CHAR(a.hire_date, 'YYYY-MM') = TO_CHAR(b.hire_date, 'YYYY-MM')
 AND a.lawyer_id < b.lawyer_id;

[User] Give me a list of all specializations available at each law firm.

[Assistant]
SELECT DISTINCT firm_id, specialization
FROM legal_services.lawyers;

[User] For each specialization, show the number of lawyers in the firm who have that specialization.

[Assistant]
SELECT firm_id, specialization, COUNT(*) AS lawyer_count
FROM legal_services.lawyers
GROUP BY firm_id, specialization;


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;


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;


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;


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;


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';


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;


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;


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';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )

[User] Can you list the names of agencies that do not have a parent agency assigned, ordered by their established date?

[Assistant]
SELECT agency_id, agency_name, established_date
FROM government_services.agencies
WHERE parent_agency_id IS NULL
ORDER BY established_date;

[User] How many agencies exist at each jurisdiction level?

[Assistant]
SELECT jurisdiction_level, COUNT(*) AS agency_count
FROM government_services.agencies
GROUP BY jurisdiction_level;

[User] Now exclude jurisdiction levels that have fewer than 5 agencies.

[Assistant]
SELECT jurisdiction_level, COUNT(*) AS agency_count
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5;

[User] Also, show me the average establishment year for those jurisdiction levels.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5;

[User] Sort the results by agency_count descending and limit to 3.

[Assistant]
SELECT jurisdiction_level,
       COUNT(*) AS agency_count,
       AVG(EXTRACT(YEAR FROM established_date)) AS avg_established_year
FROM government_services.agencies
GROUP BY jurisdiction_level
HAVING COUNT(*) >= 5
ORDER BY agency_count DESC
LIMIT 3;

[User] I would like to see a list of agencies and the names of their respective parent agencies.

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id;

[User] Could you only show agencies that actually have a parent agency, and order the result by the agency name?

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
ORDER BY a.agency_name;

[User] List each child agency ID and name along with its parent agency ID and name.

[Assistant]
SELECT c.agency_id AS child_id,
       c.agency_name AS child_name,
       p.agency_id AS parent_id,
       p.agency_name AS parent_name
FROM government_services.agencies AS c
JOIN government_services.agencies AS p
  ON c.parent_agency_id = p.agency_id;

[User] Show me all agencies established after 2020 and their jurisdiction level.

[Assistant]
SELECT agency_id, agency_name, jurisdiction_level, established_date
FROM government_services.agencies
WHERE established_date > '2020-12-31';

[User] Can you also include their parent agency's name in the result?

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31';

[User] Only show agencies where the parent agency's jurisdiction level is 'Federal'.

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31' AND p.jurisdiction_level = 'Federal';

[User] Sort the list by established date descending and show only the top 5 agencies.

[Assistant]
SELECT a.agency_id, a.agency_name, a.jurisdiction_level, a.established_date, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
WHERE a.established_date > '2020-12-31' AND p.jurisdiction_level = 'Federal'
ORDER BY a.established_date DESC
LIMIT 5;

[User] Can you show me a list of all agencies along with their parent agency names?

[Assistant]
SELECT a.agency_id, a.agency_name, pa.agency_name AS parent_agency_name
FROM government_services.agencies a
LEFT JOIN government_services.agencies pa ON a.parent_agency_id = pa.agency_id;

[User] Only show agencies that actually have a parent agency.

[Assistant]
SELECT a.agency_id, a.agency_name, pa.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies pa ON a.parent_agency_id = pa.agency_id;

[User] Provide a count of agencies grouped by their jurisdiction level.

[Assistant] SELECT jurisdiction_level, COUNT(*) FROM government_services.agencies GROUP BY jurisdiction_level;