System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )

[User] List all trades for asset 'BTC' where the trade quantity is greater than 5.

[Assistant] SELECT trade_id, order_id, buyer_id, seller_id, quantity, price, traded_at FROM trading_platform.trades WHERE asset_id = 'BTC' AND quantity > 5;

[User] Calculate the total quantity traded for each day in the dataset.

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Could you also include the total trade value (quantity * price) for each day in that report?

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity, SUM(quantity * price) AS total_daily_value FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Now, for each day, show how the total quantity compares to the overall average daily quantity across all days in the dataset.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity, total_daily_quantity - AVG(total_daily_quantity) OVER () AS quantity_difference_from_average FROM DailySummary ORDER BY trade_day;

[User] Finally, only show the days where the total quantity was higher than the overall average daily quantity.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity FROM DailySummary WHERE total_daily_quantity > (SELECT AVG(total_daily_quantity) FROM DailySummary) ORDER BY trade_day;

[User] List all trades that occurred on July 10, 2024, showing the trade ID, asset symbol, quantity, and trade price.

[Assistant]
SELECT t.trade_id, a.symbol AS asset_symbol, t.quantity, t.price
FROM trading_platform.trades t
JOIN trading_platform.assets a ON t.asset_id = a.asset_id
WHERE DATE(t.traded_at) = '2024-07-10';

[User] For each asset, show the asset name, symbol, and the latest trade price.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, (
    SELECT t1.price FROM trading_platform.trades t1
    WHERE t1.asset_id = a.asset_id
    ORDER BY t1.traded_at DESC
    LIMIT 1
) AS latest_trade_price
FROM trading_platform.assets a;

[User] Actually, add the traded_at timestamp of the latest trade as well.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, latest_trade.price AS latest_trade_price, latest_trade.traded_at AS latest_traded_at
FROM trading_platform.assets a
LEFT JOIN LATERAL (
    SELECT t.price, t.traded_at
    FROM trading_platform.trades t
    WHERE t.asset_id = a.asset_id
    ORDER BY t.traded_at DESC
    LIMIT 1
) latest_trade ON true;

[User] Can you filter to only show assets with at least one trade after July 1, 2024?

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, latest_trade.price AS latest_trade_price, latest_trade.traded_at AS latest_traded_at
FROM trading_platform.assets a
JOIN LATERAL (
    SELECT t.price, t.traded_at
    FROM trading_platform.trades t
    WHERE t.asset_id = a.asset_id AND t.traded_at > '2024-07-01'
    ORDER BY t.traded_at DESC
    LIMIT 1
) latest_trade ON true;

[User] The query returns no rows for some assets because they have no trades after July 1. Please include all assets, showing NULL for the trade details if there are none since that date.

[Assistant]
SELECT a.asset_id, a.name AS asset_name, a.symbol AS asset_symbol, latest_trade.price AS latest_trade_price, latest_trade.traded_at AS latest_traded_at
FROM trading_platform.assets a
LEFT JOIN LATERAL (
    SELECT t.price, t.traded_at
    FROM trading_platform.trades t
    WHERE t.asset_id = a.asset_id AND t.traded_at > '2024-07-01'
    ORDER BY t.traded_at DESC
    LIMIT 1
) latest_trade ON true;

[User] List all orders that are currently pending and were created more than 24 hours ago.

[Assistant] SELECT * FROM trading_platform.orders WHERE status = 'pending' AND created_at < CURRENT_TIMESTAMP - INTERVAL '24 hours';

[User] Now show me the count of such orders grouped by order_type.

[Assistant] SELECT order_type, COUNT(order_id) AS order_count FROM trading_platform.orders WHERE status = 'pending' AND created_at < CURRENT_TIMESTAMP - INTERVAL '24 hours' GROUP BY order_type;

[User] Can you modify the query to also include the total quantity for each order type?

[Assistant] SELECT order_type, COUNT(order_id) AS order_count, SUM(quantity) AS total_quantity FROM trading_platform.orders WHERE status = 'pending' AND created_at < CURRENT_TIMESTAMP - INTERVAL '24 hours' GROUP BY order_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] Could you provide the booking ID, route number, and fare for all bookings?

[Assistant] SELECT T1.booking_id, T2.route_number, T1.fare FROM transportation.bookings AS T1 JOIN transportation.routes AS T2 ON T1.trip_id = T2.route_id;

[User] Now, filter the results to only include bookings with a fare greater than 100 and sort them by fare in descending order.

[Assistant] SELECT T1.booking_id, T2.route_number, T1.fare FROM transportation.bookings AS T1 JOIN transportation.routes AS T2 ON T1.trip_id = T2.route_id WHERE T1.fare > 100 ORDER BY T1.fare DESC;

[User] Show the route number and description for routes that have bookings associated with them.

[Assistant] SELECT DISTINCT T1.route_number, T1.description FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id;

[User] For these routes, what is the average fare of the associated bookings?

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number;

[User] Also, only include routes where the average fare is greater than 75.

[Assistant] SELECT T1.route_number, AVG(T2.fare) FROM transportation.routes AS T1 JOIN transportation.bookings AS T2 ON T1.route_id = T2.trip_id GROUP BY T1.route_number HAVING AVG(T2.fare) > 75;

[User] What is the average fare for bookings with status 'Completed'?

[Assistant] SELECT AVG(fare) FROM transportation.bookings WHERE status = 'Completed';

[User] What about the average fare for 'Cancelled' bookings?

[Assistant] SELECT AVG(fare) FROM transportation.bookings WHERE status = 'Cancelled';

[User] Show the booking ID and seat number for all bookings that have a fare equal to 50.

[Assistant]
SELECT booking_id, seat_number
FROM transportation.bookings
WHERE fare = 50;

[User] Also include the booking status and order the results by booking time ascending.

[Assistant]
SELECT booking_id, seat_number, status
FROM transportation.bookings
WHERE fare = 50
ORDER BY booking_time ASC;

[User] Find all bookings for which the special_requests field is not null. Show the booking ID, passenger ID, and the special request.

[Assistant]
SELECT booking_id, passenger_id, special_requests
FROM transportation.bookings
WHERE special_requests IS NOT NULL;

[User] Could you also show the associated route number and the city of the origin location for these bookings?

[Assistant]
SELECT b.booking_id, b.passenger_id, b.special_requests, r.route_number, l.city AS origin_city
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id
JOIN transportation.locations l ON r.origin_location_id = l.location_id
WHERE b.special_requests IS NOT NULL;

[User] Only show bookings where the special_requests field contains the word 'wheelchair'.

[Assistant]
SELECT b.booking_id, b.passenger_id, b.special_requests, r.route_number, l.city AS origin_city
FROM transportation.bookings b
JOIN transportation.routes r ON b.trip_id = r.route_id
JOIN transportation.locations l ON r.origin_location_id = l.location_id
WHERE b.special_requests ILIKE '%wheelchair%';


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 character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)

[User] Find cases where an address received tokens in one transfer and then sent tokens in another. List the receive transfer_id, the send transfer_id, the address, and both transfer values.

[Assistant]
SELECT recv.transfer_id AS receive_transfer_id,
       send.transfer_id AS send_transfer_id,
       recv.to_address AS address,
       recv.value       AS received_value,
       send.value       AS sent_value
FROM web3.token_transfers recv
JOIN web3.token_transfers send
  ON recv.to_address = send.from_address;

[User] Find pairs of distinct token transfers that occurred in the same transaction and were initiated by the same sender address. List the transaction ID, the common sender address, and both transfer IDs.

[Assistant]
SELECT
  t1.transaction_id,
  t1.from_address,
  t1.transfer_id AS transfer_id_1,
  t2.transfer_id AS transfer_id_2
FROM web3.token_transfers AS t1
JOIN web3.token_transfers AS t2
  ON t1.transaction_id = t2.transaction_id
  AND t1.from_address = t2.from_address
WHERE
  t1.transfer_id < t2.transfer_id;

[User] For each sender address, count how many distinct tokens they have transferred. Show from_address and token_count.

[Assistant]
SELECT from_address, COUNT(DISTINCT token_id) AS token_count
FROM web3.token_transfers
GROUP BY from_address;

[User] Now filter to only include senders who have transferred more than 5 distinct tokens.

[Assistant]
SELECT from_address, COUNT(DISTINCT token_id) AS token_count
FROM web3.token_transfers
GROUP BY from_address
HAVING COUNT(DISTINCT token_id) > 5;

[User] For each token, show the token_id and the total number of unique addresses that have ever received it.

[Assistant]
SELECT token_id, COUNT(DISTINCT to_address) AS unique_recipients
FROM web3.token_transfers
GROUP BY token_id;

[User] List all token transfers between two distinct addresses, showing transfer_id, from_address, to_address, value, and transaction_id.

[Assistant]
SELECT transfer_id, from_address, to_address, value, transaction_id
FROM web3.token_transfers
WHERE from_address <> to_address;

[User] Actually, I only want to see transfers where the value transferred is greater than 1000 tokens.

[Assistant]
SELECT transfer_id, from_address, to_address, value, transaction_id
FROM web3.token_transfers
WHERE from_address <> to_address AND value > 1000;


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.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )

[User] Show me the number of guests registered in each city. Order the results by city name.

[Assistant] SELECT city, COUNT(guest_id) AS guest_count FROM guests GROUP BY city ORDER BY city;

[User] Find all guests who live in the same city and list each guest's name along with the name of another guest in that city.

[Assistant]
SELECT g1.first_name || ' ' || g1.last_name AS guest_name,
       g2.first_name || ' ' || g2.last_name AS other_guest_name,
       g1.city
FROM guests g1
JOIN guests g2
  ON g1.city = g2.city
 AND g1.guest_id <> g2.guest_id;

[User] Now restrict to only cities with more than two guests and order by city ascending.

[Assistant]
SELECT pairs.city,
       pairs.guest_name,
       pairs.other_guest_name
FROM (
  SELECT g1.first_name || ' ' || g1.last_name AS guest_name,
         g2.first_name || ' ' || g2.last_name AS other_guest_name,
         g1.city
  FROM guests g1
  JOIN guests g2
    ON g1.city = g2.city
   AND g1.guest_id <> g2.guest_id
) AS pairs
JOIN (
  SELECT city
  FROM guests
  GROUP BY city
  HAVING COUNT(*) > 2
) AS multi
  ON pairs.city = multi.city
ORDER BY pairs.city ASC;

[User] Find pairs of guests living in the same city, returning each pair’s full names and the city.

[Assistant]
SELECT g1.first_name || ' ' || g1.last_name AS guest1,
       g2.first_name || ' ' || g2.last_name AS guest2,
       g1.city
FROM hospitality_technology.guests g1
JOIN hospitality_technology.guests g2
  ON g1.city = g2.city
 AND g1.guest_id < g2.guest_id;

[User] List all guests who have communication consent enabled along with their email addresses.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email
FROM guests
WHERE communication_consent = TRUE;

[User] Now only include those guests who also have a loyalty_member_id.

[Assistant]
SELECT guest_id,
       first_name || ' ' || last_name AS full_name,
       email,
       loyalty_member_id
FROM guests
WHERE communication_consent = TRUE
  AND loyalty_member_id IS NOT NULL;

[User] Show me all guests from 'CA' along with their full name and email address.

[Assistant] SELECT guest_id, CONCAT(first_name, ' ', last_name) AS full_name, email FROM hospitality_technology.guests WHERE country_code = 'CA';


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_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )

[User] Show me all tokens which have a 6-hour price change percentage above 2% and the current price, on the Arbitrum chain.

[Assistant]
SELECT token_symbol, price, price_change_percentage_6h
FROM token_dexpool_info
WHERE chain = 'Arbitrum'
  AND price_change_percentage_6h > 2;

[User] Show tokens held by CEX addresses that have a positive ROI from smart money. Display the token symbol, chain, the exchange holding it, the CEX USD value of the holding, and the smart money ROI. Limit the results to the top 10 tokens ranked by smart money ROI in descending order.

[Assistant] SELECT c.token_symbol, c.chain, c.exchange, c.usd_value, s.roi FROM cex_token_balance c JOIN smart_money_token_performance s ON c.token_address = s.token_address AND c.chain = s.chain WHERE s.roi > 0 ORDER BY s.roi DESC LIMIT 10;

[User] Modify the query to also include the token's narrative and its current price from the basic info table.

[Assistant] SELECT c.token_symbol, c.chain, c.exchange, c.usd_value, s.roi, b.narrative, b.price FROM cex_token_balance c JOIN smart_money_token_performance s ON c.token_address = s.token_address AND c.chain = s.chain JOIN token_basic_info b ON c.token_address = b.token_address AND c.chain = b.chain WHERE s.roi > 0 ORDER BY s.roi DESC LIMIT 10;

[User] For each chain, which token has the lowest average cost as reported by smart money, and what is its current price and ROI?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Now, I only want to see tokens where the ROI is above 0.5.

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi
FROM smart_money_token_performance smtp
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi;

[User] Can you also return the token narrative from the token_basic_info table for each result?

[Assistant]
SELECT smtp.chain, smtp.token_symbol, MIN(smtp.avg_cost) AS lowest_avg_cost, smtp.price, smtp.roi, tbi.narrative
FROM smart_money_token_performance smtp
JOIN token_basic_info tbi ON smtp.token_symbol = tbi.token_symbol AND smtp.chain = tbi.chain
WHERE smtp.roi > 0.5
GROUP BY smtp.chain, smtp.token_symbol, smtp.price, smtp.roi, tbi.narrative;

[User] What is the total USD value of tokens held by 'Binance' on the 'BSC' chain according to the latest snapshot?

[Assistant] SELECT SUM(usd_value) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] Also, show the number of distinct token symbols held by Binance on BSC in that same snapshot.

[Assistant] SELECT SUM(usd_value), COUNT(DISTINCT token_symbol) FROM cex_token_balance WHERE exchange = 'Binance' AND chain = 'BSC' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance)

[User] List tokens on the 'Arbitrum' chain with a 24-hour price change percentage greater than 10% and a market cap above 1,000,000 USD. Show their symbol, name, price, 24-hour change percentage, and market cap. Order the results by the 24-hour change percentage in descending order.

[Assistant] SELECT token_symbol, token_name, price, price_change_percentage_24h, market_cap FROM token_basic_info WHERE chain = 'Arbitrum' AND price_change_percentage_24h > 10 AND market_cap > 1000000 ORDER BY price_change_percentage_24h 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 transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )

[User] Show a count of drivers per status.

[Assistant]
SELECT status, COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

[User] Can you also list the earliest hire date for each status?

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status;

[User] I only want to see statuses with more than 5 drivers.

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 5;

[User] Please sort the output by driver_count in descending order.

[Assistant]
SELECT status, COUNT(*) AS driver_count, MIN(hire_date) AS earliest_hire_date
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 5
ORDER BY driver_count DESC;

[User] Calculate the total number of drivers for each status.

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status;

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

[Assistant]
SELECT status,
       COUNT(*) AS driver_count
FROM transportation.drivers
GROUP BY status
HAVING COUNT(*) > 10;

[User] List all drivers whose licenses are set to expire within the next 60 days, along with their full name, license number, and contact number.

[Assistant]
SELECT driver_id, first_name, last_name, license_number, contact_number
FROM transportation.drivers
WHERE license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] For each driver, show their driver_id, first_name, last_name, along with any other driver whose license_expiry_date is earlier than theirs.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date;

[User] Exclude pairs where the two expiry dates are not in the same calendar year.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date);

[User] Also only include pairs where the difference between their expiry dates is more than 30 days.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date,
       DATE_PART('day', d1.license_expiry_date - d2.license_expiry_date) AS days_difference
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
WHERE d1.license_expiry_date - d2.license_expiry_date > INTERVAL '30 days';

[User] List pairs of drivers whose license expiry dates fall within 30 days of each other. Show both driver_ids, names, and the two expiry dates.

[Assistant] SELECT d1.driver_id AS driver1_id, d1.first_name AS driver1_first, d1.last_name AS driver1_last, d1.license_expiry_date AS expiry1, d2.driver_id AS driver2_id, d2.first_name AS driver2_first, d2.last_name AS driver2_last, d2.license_expiry_date AS expiry2 FROM transportation.drivers d1 JOIN transportation.drivers d2 ON d1.driver_id < d2.driver_id AND ABS((d1.license_expiry_date - d2.license_expiry_date)) <= INTERVAL '30 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] Show me all notifications sent in the last 7 days, including the user ID and message.

[Assistant] SELECT user_id, message, sent_at FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days';

[User] From that list, only show the notifications that have not been read yet.

[Assistant] SELECT user_id, message, sent_at FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL;

[User] Instead of listing them, can you just give me the total count of unread notifications sent in the last 7 days?

[Assistant] SELECT COUNT(*) FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL;

[User] Now, show the count of unread notifications sent in the last 7 days for each user ID.

[Assistant] SELECT user_id, COUNT(*) FROM trading_platform.notifications WHERE sent_at >= NOW() - INTERVAL '7 days' AND read_at IS NULL GROUP BY user_id;

[User] Get a list of users who have both read and unread notifications. For each user, show their user_id, the count of unread notifications as unread_count, and the count of read notifications as read_count.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;

[User] Actually, I want to filter to only include those users whose unread_count is at least 3.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
  HAVING COUNT(*) >= 3
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;

[User] For each user, list their user_id along with their first and last notification messages and the sent_at timestamps.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id;

[User] Limit to users who have more than 5 notifications.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id
JOIN (
  SELECT user_id
  FROM trading_platform.notifications
  GROUP BY user_id
  HAVING COUNT(*) > 5
) AS filtered ON f.user_id = filtered.user_id;

[User] Also include total_notification_count in the result.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), counts AS (
  SELECT user_id, COUNT(*) AS total_notification_count
  FROM trading_platform.notifications
  GROUP BY user_id
  HAVING COUNT(*) > 5
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at, c.total_notification_count
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id
JOIN counts c ON f.user_id = c.user_id;

[User] Order by total_notification_count descending and limit to top 10.

[Assistant]
WITH firsts AS (
  SELECT user_id, notification_id AS first_id, message AS first_message, sent_at AS first_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MIN(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), lasts AS (
  SELECT user_id, notification_id AS last_id, message AS last_message, sent_at AS last_sent_at
  FROM trading_platform.notifications
  WHERE (user_id, sent_at) IN (
    SELECT user_id, MAX(sent_at)
    FROM trading_platform.notifications
    GROUP BY user_id
  )
), counts AS (
  SELECT user_id, COUNT(*) AS total_notification_count
  FROM trading_platform.notifications
  GROUP BY user_id
  HAVING COUNT(*) > 5
)
SELECT f.user_id, f.first_id, f.first_message, f.first_sent_at, l.last_id, l.last_message, l.last_sent_at, c.total_notification_count
FROM firsts f
JOIN lasts l ON f.user_id = l.user_id
JOIN counts c ON f.user_id = c.user_id
ORDER BY c.total_notification_count DESC
LIMIT 10;

[User] Find all notifications that were sent more than 24 hours ago and are still unread. Show the notification ID, user ID, and sent_at timestamp.

[Assistant] SELECT notification_id, user_id, sent_at FROM notifications WHERE read_at IS NULL AND sent_at < NOW() - INTERVAL '24 hour';

[User] Could you provide the total number of notifications sent on each day?

[Assistant] SELECT DATE(sent_at), COUNT(*) FROM notifications GROUP BY DATE(sent_at) ORDER BY DATE(sent_at);

[User] Now, show only the days where more than 50 notifications were sent. Also, for those days, calculate the average time it took for notifications sent on that day to be read (only consider notifications that have been read).

[Assistant] SELECT DATE(sent_at), COUNT(*), AVG(EXTRACT(EPOCH FROM (read_at - sent_at))) FROM notifications WHERE read_at IS NOT NULL GROUP BY DATE(sent_at) HAVING COUNT(*) > 50 ORDER BY DATE(sent_at);


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 smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )

[User] List token symbols on any chain that have both a realized ratio above 0.8 and an ROI greater than 5. Show their symbol, chain, realized ratio, and ROI.

[Assistant] SELECT token_symbol, chain, realized_ratio, roi FROM smart_money_token_performance WHERE realized_ratio > 0.8 AND roi > 5

[User] Can you also include their PNL and Net Flow in the result?

[Assistant] SELECT token_symbol, chain, realized_ratio, roi, pnl, net_flow FROM smart_money_token_performance WHERE realized_ratio > 0.8 AND roi > 5

[User] For each chain, what is the average price of tokens recorded in the smart_money_token_performance table?

[Assistant] SELECT chain, AVG(price) AS average_token_price FROM smart_money_token_performance GROUP BY chain;

[User] List all token symbols on the 'Ethereum' chain with a Realized Ratio greater than 0.9. Show the symbol and realized ratio.

[Assistant] SELECT token_symbol, realized_ratio FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9;

[User] Can you also include their current Price and Net Flow?

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9;

[User] Now, filter these results to only include tokens where the Net Flow is positive.

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9 AND net_flow > 0;

[User] Order the results by Net Flow descending and show the top 10.

[Assistant] SELECT token_symbol, realized_ratio, price, net_flow FROM smart_money_token_performance WHERE chain = 'Ethereum' AND realized_ratio > 0.9 AND net_flow > 0 ORDER BY net_flow DESC LIMIT 10;

[User] How many distinct token symbols are recorded for each chain in the smart money performance data?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) FROM smart_money_token_performance GROUP BY chain

[User] List all smart money addresses that have a negative PNL but a positive Realized Ratio. Show the address, chain, PNL, and Realized Ratio.

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < 0 AND realized_ratio > 0

[User] Can you refine the results to only include addresses where the absolute value of PNL is greater than 1000?

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < -1000 AND realized_ratio > 0


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
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)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] Show me all patients who have had at least one appointment with a doctor specializing in 'Cardiology'. Include the patient's full name, appointment time, and doctor's full name.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology';

[User] Can you only include appointments that are marked as 'Completed'?

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed';

[User] Only show appointments that lasted at least 45 minutes.

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed' AND a.duration_minutes >= 45;

[User] Could you also include the doctor's specialty in the result?

[Assistant]
SELECT p.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, a.appointment_time, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, d.specialty
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE d.specialty = 'Cardiology' AND a.status = 'Completed' AND a.duration_minutes >= 45;

[User] List each patient's first and last name along with their total number of appointments in 2024.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY p.first_name, p.last_name;

[User] Now exclude all 'Cancelled' appointments from the count.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
  AND a.status <> 'Cancelled'
GROUP BY p.first_name, p.last_name;

[User] Also, only show patients who have more than 2 appointments and sort the result by appointment_count in descending order.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
LEFT JOIN healthcare.appointments a
  ON p.patient_id = a.patient_id
  AND a.appointment_time BETWEEN '2024-01-01' AND '2024-12-31'
  AND a.status <> 'Cancelled'
GROUP BY p.first_name, p.last_name
HAVING COUNT(a.appointment_id) > 2
ORDER BY appointment_count DESC;

[User] List the medication name and manufacturer of all medications where the description contains the word 'extended'.

[Assistant]
SELECT medication_name, manufacturer
FROM healthcare.medications
WHERE description ILIKE '%extended%';

[User] Only include medications where the ndc_code is not null and has more than 8 characters.

[Assistant]
SELECT medication_name, manufacturer
FROM healthcare.medications
WHERE description ILIKE '%extended%'
  AND ndc_code IS NOT NULL
  AND length(ndc_code) > 8;

[User] Provide each patient's most recent medical-record doctor's full name along with their primary insurance plan name. Return patient_id, first_name, last_name, primary_plan_name, doctor_first_name, doctor_last_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name      AS primary_plan_name,
       d.first_name      AS doctor_first_name,
       d.last_name       AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id
 AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans AS ip
  ON pi.plan_id = ip.plan_id
JOIN (
  SELECT DISTINCT ON (patient_id)
         patient_id,
         doctor_id,
         record_date
  FROM healthcare.medical_records
  ORDER BY patient_id, record_date DESC
) AS mr
  ON p.patient_id = mr.patient_id
JOIN healthcare.doctors AS d
  ON mr.doctor_id = d.doctor_id;

[User] Actually, restrict to only those whose primary plan_type is 'PPO'.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name      AS primary_plan_name,
       d.first_name      AS doctor_first_name,
       d.last_name       AS doctor_last_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id
 AND pi.is_primary = TRUE
JOIN healthcare.insurance_plans AS ip
  ON pi.plan_id = ip.plan_id
JOIN (
  SELECT DISTINCT ON (patient_id)
         patient_id,
         doctor_id,
         record_date
  FROM healthcare.medical_records
  ORDER BY patient_id, record_date DESC
) AS mr
  ON p.patient_id = mr.patient_id
JOIN healthcare.doctors AS d
  ON mr.doctor_id = d.doctor_id
WHERE ip.plan_type = 'PPO';

[User] Find patients who currently have both a primary and a secondary insurance policy. For each, show patient_id, full name, primary policy_number, and secondary policy_number.

[Assistant]
SELECT p.patient_id,
       p.first_name || ' ' || p.last_name AS patient_name,
       pri.policy_number AS primary_policy,
       sec.policy_number AS secondary_policy
FROM healthcare.patients p
JOIN healthcare.patient_insurance pri ON p.patient_id = pri.patient_id AND pri.is_primary = TRUE
JOIN healthcare.patient_insurance sec ON p.patient_id = sec.patient_id AND sec.is_primary = FALSE;


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.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )

[User] Show me all users who have commented on a post and have also liked any comment on that same post. I want their user IDs and the corresponding post IDs.

[Assistant]
SELECT DISTINCT c.user_id, c.post_id
FROM social_media.comments c
JOIN social_media.likes l ON l.comment_id IS NOT NULL AND l.post_id = c.post_id AND l.user_id = c.user_id

[User] Can you also include the comment content that was liked and the time the like was created?

[Assistant]
SELECT DISTINCT c.user_id, c.post_id, c2.content AS liked_comment_content, l.created_at AS like_created_at
FROM social_media.comments c
JOIN social_media.likes l ON l.comment_id IS NOT NULL AND l.post_id = c.post_id AND l.user_id = c.user_id
JOIN social_media.comments c2 ON c2.comment_id = l.comment_id

[User] Show me the content of all comments that have received at least one like.

[Assistant] SELECT DISTINCT T1.content FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id;

[User] Also include the creation time of these comments and the user_id of the commenter?

[Assistant] SELECT DISTINCT T1.comment_id, T1.content, T1.created_at, T1.user_id FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id;

[User] Only show comments created before '2024-05-01'.

[Assistant] SELECT DISTINCT T1.comment_id, T1.content, T1.created_at, T1.user_id FROM social_media.comments AS T1 JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T1.created_at < '2024-05-01';

[User] Show me all users who have liked both a comment and a post, including their user IDs.

[Assistant]
SELECT DISTINCT l1.user_id
FROM social_media.likes l1
JOIN social_media.likes l2 ON l1.user_id = l2.user_id
WHERE l1.post_id IS NOT NULL AND l2.comment_id IS NOT NULL;

[User] Please also include the post ID and the comment ID for each user.

[Assistant]
SELECT DISTINCT l1.user_id, l1.post_id, l2.comment_id
FROM social_media.likes l1
JOIN social_media.likes l2 ON l1.user_id = l2.user_id
WHERE l1.post_id IS NOT NULL AND l2.comment_id IS NOT NULL;

[User] Now only show users who liked at least two different posts and two different comments, and include the count of distinct posts and comments they liked.

[Assistant]
SELECT user_id, COUNT(DISTINCT post_id) AS distinct_post_count, COUNT(DISTINCT comment_id) AS distinct_comment_count
FROM social_media.likes
WHERE post_id IS NOT NULL OR comment_id IS NOT NULL
GROUP BY user_id
HAVING COUNT(DISTINCT post_id) >= 2 AND COUNT(DISTINCT comment_id) >= 2;

[User] List all comment IDs that have not received any likes.

[Assistant] SELECT T1.comment_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;

[User] Can you also include the content of these comments and the post_id they belong to?

[Assistant] SELECT T1.comment_id, T1.content, T1.post_id FROM social_media.comments AS T1 LEFT JOIN social_media.likes AS T2 ON T1.comment_id = T2.comment_id WHERE T2.like_id IS NULL;

[User] List all conversation IDs with the total number of messages sent in each conversation.

[Assistant]
SELECT conversation_id, COUNT(*) AS message_count
FROM social_media.messages
GROUP BY conversation_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Can you show me all user IDs that have both email and push notifications disabled, along with whether their profile is set to private?

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

[User] I also want to see the last time they updated their settings.

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

[User] Show the user IDs of all users whose theme is set to 'blue'.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE theme = 'blue';

[User] Can you show me the user IDs and their theme settings for all users who have enabled email notifications and have updated their settings in 2024?

[Assistant] SELECT user_id, theme FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] What if I also want to see if their profile is private or not?

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] Actually, I want to see users who have both email AND push notifications enabled.

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = TRUE AND updated_at >= '2024-01-01';

[User] Now, limit the results to users whose theme is 'light' only.

[Assistant] SELECT user_id, theme, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = TRUE AND theme = 'light' AND updated_at >= '2024-01-01';

[User] Show me all user IDs who changed their profile settings after June 1, 2024.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE updated_at > '2024-06-01';

[User] Which users have disabled both email and push notifications? Please provide their user IDs and whether their profiles are private.

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

[User] Also, only include those users who have updated their settings in the last 60 days.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE AND updated_at >= NOW() - INTERVAL '60 days';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )

[User] What is the total investment_value per fundraising round for the year 2023? Order by total investment descending.

[Assistant]
SELECT
  substr(investment_date,1,7) AS month,
  rounds_name,
  SUM(investment_value) AS total_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%'
GROUP BY substr(investment_date,1,7), rounds_name
ORDER BY total_investment DESC;

[User] Which project had the largest single fundraising in each investment round, along with the round's name and introduction?

[Assistant] SELECT t1.project_name, t1.rounds_name, t1.investment_value, t1.introduction FROM project_fundraising_record t1 INNER JOIN (SELECT rounds_name, MAX(investment_value) AS max_value FROM project_fundraising_record GROUP BY rounds_name) t2 ON t1.rounds_name = t2.rounds_name AND t1.investment_value = t2.max_value;

[User] Instead of just one, can you show the top two fundraisings in each round?

[Assistant] SELECT project_name, rounds_name, investment_value, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Can you add the valuation for each project in the output as well?

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Show me only those top two projects per round where the valuation is greater than 100 million.

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2 AND valuation > 100000000;

[User] How many projects raised funds in 2023?

[Assistant]
SELECT COUNT(*) AS project_count
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] Also provide the average investment_value for these projects.

[Assistant]
SELECT COUNT(*) AS project_count, AVG(investment_value) AS avg_investment
FROM project_fundraising_record
WHERE investment_date LIKE '2023-%';

[User] Which projects raised funds in January 2022?

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

[User] Please also show their introductions.

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

[User] List all fundraising rounds where the average investment amount exceeded $10M, and show how many projects participated in each round.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000;

[User] Now, only consider rounds with at least 3 projects.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3;

[User] Add the total raised amount in each selected round.

[Assistant] SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment, SUM(investment_value) AS total_raised FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3;

[User] Show the result ordered by total_raised in descending order, and only the top 2 rounds.

[Assistant] SELECT rounds_name, project_count, avg_investment, total_raised FROM (SELECT rounds_name, COUNT(DISTINCT project_id) AS project_count, AVG(investment_value) AS avg_investment, SUM(investment_value) AS total_raised FROM project_fundraising_record GROUP BY rounds_name HAVING AVG(investment_value) > 10000000 AND COUNT(DISTINCT project_id) >= 3) t ORDER BY total_raised DESC LIMIT 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 financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )

[User] Show me the average interest rate for each account_type.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate
FROM financial_services.accounts
GROUP BY account_type;

[User] Only include account types with at least 5 accounts and order by average_interest_rate ascending.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate, COUNT(*) AS account_count
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] Add the minimum and maximum interest rate for each account_type to the result.

[Assistant]
SELECT account_type, COUNT(*) AS account_count, AVG(interest_rate) AS average_interest_rate,
       MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] List all accounts with a balance below 1000, showing the account_id, account_number, and currency.

[Assistant]
SELECT account_id, account_number, currency
FROM financial_services.accounts
WHERE balance < 1000;

[User] Now, also include accounts with a negative balance and order the result by balance ascending.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE balance < 1000 OR balance < 0
ORDER BY balance ASC;

[User] I only want to see the accounts where status is not 'Closed'.

[Assistant]
SELECT account_id, account_number, currency, balance
FROM financial_services.accounts
WHERE (balance < 1000 OR balance < 0) AND status <> 'Closed'
ORDER BY balance ASC;

[User] What is the average balance for each account_type among accounts with status 'Open'?

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type;

[User] Exclude account types with fewer than 3 accounts.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3;

[User] Sort the results by average balance descending.

[Assistant] SELECT account_type, AVG(balance) AS avg_balance FROM financial_services.accounts WHERE status = 'Open' GROUP BY account_type HAVING COUNT(*) >= 3 ORDER BY avg_balance DESC;

[User] List accounts that were opened in the same month and year as another account for the same customer, but have a different account type. Show the account_id, customer_id, account_type, and opened_date for these accounts.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type

[User] Only include pairs where the first account's balance is higher than the second account's balance.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type AND T1.balance  >  T2.balance

[User] I made a mistake, I want the second account's balance to be *lower* than the first account's balance.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type AND T2.balance  <  T1.balance

[User] Also, only show results where the account_type for the first account is 'Savings'.

[Assistant] SELECT T1.account_id ,  T1.customer_id ,  T1.account_type ,  T1.opened_date FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id AND date_part('year', T1.opened_date) = date_part('year', T2.opened_date) AND date_part('month', T1.opened_date) = date_part('month', T2.opened_date) WHERE T1.account_id  <>  T2.account_id AND T1.account_type  <>  T2.account_type AND T2.balance  <  T1.balance AND T1.account_type  =  'Savings'

[User] List all accounts for customers who have at least one account with a balance over 10000 and another account with a balance under 1000. Show customer_id, account_id, account_type, balance, and currency.

[Assistant] SELECT account_id ,  customer_id ,  account_type ,  balance ,  currency FROM financial_services.accounts WHERE customer_id IN ( SELECT T1.customer_id FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id WHERE T1.balance  >  10000 AND T2.balance  <  1000 )

[User] Actually, I only want to see the accounts that meet the specific balance criteria (over 10k or under 1k), not all accounts for those customers. And only include accounts where the status is 'Open'.

[Assistant] SELECT account_id ,  customer_id ,  account_type ,  balance ,  currency FROM financial_services.accounts WHERE customer_id IN ( SELECT T1.customer_id FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id WHERE T1.balance  >  10000 AND T2.balance  <  1000 ) AND (balance  >  10000 OR balance  <  1000) AND status  =  'Open'

[User] Could you also include the opened_date and sort the results by customer_id, then by balance descending?

[Assistant] SELECT account_id ,  customer_id ,  account_type ,  balance ,  currency ,  opened_date FROM financial_services.accounts WHERE customer_id IN ( SELECT T1.customer_id FROM financial_services.accounts AS T1 JOIN financial_services.accounts AS T2 ON T1.customer_id  =  T2.customer_id WHERE T1.balance  >  10000 AND T2.balance  <  1000 ) AND (balance  >  10000 OR balance  <  1000) AND status  =  'Open' ORDER BY customer_id ASC ,  balance DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain 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 token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
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, 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 ( 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 mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount 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 text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( 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, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] Show me the historical balance entries for wallet address '0xabc...' and contract address '0xdef...', including the block number and amount.

[Assistant] SELECT block_number, amount FROM erc20_balances_historical WHERE wallet_address = '0xabc...' AND contract_address = '0xdef...'

[User] For these entries, please also include the token symbol and name by joining with the `token_metas` table.

[Assistant] SELECT T1.block_number, T1.amount, T2.symbol, T2.name FROM erc20_balances_historical AS T1 JOIN token_metas AS T2 ON T1.contract_address = T2.contract_address WHERE T1.wallet_address = '0xabc...' AND T1.contract_address = '0xdef...'

[User] Now, add the latest USD price for this token by joining the `token_prices_latest` table.

[Assistant] SELECT T1.block_number, T1.amount, T2.symbol, T2.name, T3.price FROM erc20_balances_historical AS T1 JOIN token_metas AS T2 ON T1.contract_address = T2.contract_address JOIN token_prices_latest AS T3 ON T2.contract_address = T3.address WHERE T1.wallet_address = '0xabc...' AND T1.contract_address = '0xdef...'

[User] Finally, filter the results to only show historical entries where the latest USD price is greater than 100.

[Assistant] SELECT T1.block_number, T1.amount, T2.symbol, T2.name, T3.price FROM erc20_balances_historical AS T1 JOIN token_metas AS T2 ON T1.contract_address = T2.contract_address JOIN token_prices_latest AS T3 ON T2.contract_address = T3.address WHERE T1.wallet_address = '0xabc...' AND T1.contract_address = '0xdef...' AND T3.price > 100

[User] How many total records are there in the `erc20_approval` table?

[Assistant] SELECT COUNT(*) FROM erc20_approval

[User] And how many records are in the `erc1155_approval_for_all` table?

[Assistant] SELECT COUNT(*) FROM erc1155_approval_for_all

[User] List all unique wallet addresses that are present in the `nft_holders` table.

[Assistant] SELECT DISTINCT wallet_address FROM nft_holders

[User] How many unique wallet addresses have ever held an ERC20 token according to the `erc20_balances_historical` table?

[Assistant] SELECT COUNT(DISTINCT wallet_address) FROM erc20_balances_historical

[User] For Avalanche tokens, show me the token `tick`, `creator`, and `max_supply` from the `token_info_avalanche` table.

[Assistant] SELECT tick, creator, max_supply FROM token_info_avalanche

[User] Now, for each of these ticks, calculate the total transfer volume (`amt`) from the `token_activities_avalanche` table over the last 30 days.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply

[User] Filter the results to only include ticks where the `total_volume` is greater than 10000.

[Assistant] SELECT T1.tick, T2.creator, T2.max_supply, SUM(T1.amt) AS total_volume FROM token_activities_avalanche AS T1 JOIN token_info_avalanche AS T2 ON T1.tick = T2.tick WHERE T1.block_timestamp >= CURRENT_TIMESTAMP - INTERVAL '30' DAY GROUP BY T1.tick, T2.creator, T2.max_supply HAVING SUM(T1.amt) > 10000

[User] How many NFTs are currently held for each contract address and token ID? Please show contract address, token id, and total amount held.

[Assistant] SELECT contract_address, token_id, SUM(CAST(amount AS BIGINT)) as total_held FROM nft_holders GROUP BY contract_address, token_id;

[User] Can you also show the highest rarity_score for each NFT from the nft_metadata table?

[Assistant]
SELECT h.contract_address, h.token_id, SUM(CAST(h.amount AS BIGINT)) as total_held, MAX(m.rarity_score) as max_rarity_score
FROM nft_holders h
LEFT JOIN nft_metadata m ON h.contract_address = m.contract_address AND h.token_id = m.token_id
GROUP BY h.contract_address, h.token_id;

[User] Now, only show NFTs where the max_rarity_score is above 90 and list them in descending order of total_held.

[Assistant]
SELECT h.contract_address, h.token_id, SUM(CAST(h.amount AS BIGINT)) as total_held, MAX(m.rarity_score) as max_rarity_score
FROM nft_holders h
LEFT JOIN nft_metadata m ON h.contract_address = m.contract_address AND h.token_id = m.token_id
GROUP BY h.contract_address, h.token_id
HAVING MAX(m.rarity_score) > 90
ORDER BY total_held DESC;

[User] For Sui coins, can you show the coin_type and owner address for each coin where the balance is greater than 100000?

[Assistant] SELECT coin_type, owner FROM sui_coins WHERE CAST(balance AS NUMERIC) > 100000;

[User] Can you also show the symbol and name for each coin by joining with sui_coins_metadata?

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS NUMERIC) > 100000;

[User] Limit the results to only coins where the metadata status is 'exists' and sort the output by owner address ascending.

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

[User] Actually, only show coins owned by addresses starting with '0xabc' and display the first 5 results only.

[Assistant] SELECT sc.coin_type, scm.symbol, scm.name, sc.owner FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS NUMERIC) > 100000 AND scm.status = 'exists' AND sc.owner LIKE '0xabc%' ORDER BY sc.owner ASC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )

[User] Get all pairs of services from the same department where one service is more expensive than another. Show department, service1_name, price1, service2_name, price2.

[Assistant] SELECT s1.department, s1.service_name AS service1_name, s1.price AS price1, s2.service_name AS service2_name, s2.price AS price2 FROM hospitality_technology.services s1 JOIN hospitality_technology.services s2 ON s1.department = s2.department AND s1.price > s2.price;

[User] Now only show pairs where the price difference is greater than 50.

[Assistant] SELECT s1.department, s1.service_name AS service1_name, s1.price AS price1, s2.service_name AS service2_name, s2.price AS price2 FROM hospitality_technology.services s1 JOIN hospitality_technology.services s2 ON s1.department = s2.department AND s1.price > s2.price WHERE s1.price - s2.price > 50;

[User] What is the average price of services grouped by category? Display category and average_price.

[Assistant] SELECT category, AVG(price) AS average_price FROM hospitality_technology.services GROUP BY category;

[User] Only include categories where the average_price is above 100 and order by average_price descending.

[Assistant] SELECT category, AVG(price) AS average_price FROM hospitality_technology.services GROUP BY category HAVING AVG(price) > 100 ORDER BY average_price DESC;

[User] For each department, what is the highest priced available service? Please show department, service_name, and price.

[Assistant] SELECT department, service_name, price FROM hospitality_technology.services WHERE is_available = TRUE AND (department, price) IN (SELECT department, MAX(price) FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department);

[User] The SQL failed due to using a tuple in the IN clause. Can you rewrite it in a way that's compatible with most databases?

[Assistant] SELECT s.department, s.service_name, s.price FROM hospitality_technology.services s JOIN (SELECT department, MAX(price) AS max_price FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department) sub ON s.department = sub.department AND s.price = sub.max_price WHERE s.is_available = TRUE;

[User] Now, only show departments where the maximum price is over 150.

[Assistant] SELECT s.department, s.service_name, s.price FROM hospitality_technology.services s JOIN (SELECT department, MAX(price) AS max_price FROM hospitality_technology.services WHERE is_available = TRUE GROUP BY department) sub ON s.department = sub.department AND s.price = sub.max_price WHERE s.is_available = TRUE AND sub.max_price > 150;

[User] Which available services in the 'Wellness' category are offered by each property? Please show property_id, service_name, and price.

[Assistant] SELECT property_id, service_name, price FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = TRUE;

[User] Instead, show only those services with a price greater than 80 and include the department in the result.

[Assistant] SELECT property_id, service_name, price, department FROM hospitality_technology.services WHERE category = 'Wellness' AND is_available = TRUE AND price > 80;

[User] List all food and beverage services (category = 'Food & Beverage') with their names, prices, and units, where the price is less than $20.

[Assistant] SELECT service_name, price, unit FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20;

[User] Now, filter these results to only include services that are priced per item (unit = 'Per Item').

[Assistant] SELECT service_name, price, unit FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item';

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

[Assistant] SELECT service_name, price, unit, department FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item';

[User] Actually, I only need services from the 'F&B' department, and order them by price in ascending order.

[Assistant] SELECT service_name, price, unit, department FROM hospitality_technology.services WHERE category = 'Food & Beverage' AND price < 20 AND unit = 'Per Item' AND department = 'F&B' ORDER BY price 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 trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] List all peers with their IP addresses who have not been seen in the last 7 days.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen < NOW() - INTERVAL '7 days';

[User] Count the number of metadata entries for each asset.

[Assistant]
SELECT asset_id, COUNT(*) AS metadata_count
FROM trading_platform.metadata
GROUP BY asset_id;

[User] Show me, for each wallet address, the total sum of amounts for all unspent UTXOs, along with the user ID who owns the wallet.

[Assistant]
SELECT w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.address, w.user_id;

[User] Now, include only the wallets where the total unspent amount is greater than 50, and show the wallet_id as well.

[Assistant]
SELECT w.wallet_id, w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.wallet_id, w.address, w.user_id
HAVING COALESCE(SUM(u.amount), 0) > 50;

[User] List the asset names and symbols for all assets of type 'token'.

[Assistant] SELECT name, symbol FROM trading_platform.assets WHERE type = 'token';

[User] Show me the order ID, order type, and asset name for all orders that resulted in at least one trade.

[Assistant] SELECT DISTINCT o.order_id, o.order_type, a.name FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id;

[User] The previous result shows duplicate order IDs if an order had multiple trades. I only want each order listed once. Also, add the total quantity traded for each order, not the quantity from the order table itself.

[Assistant] SELECT o.order_id, o.order_type, a.name, SUM(t.quantity) AS total_traded_quantity FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id GROUP BY o.order_id, o.order_type, a.name;

[User] That's better. Now, only show 'buy' orders where the total traded quantity is greater than 50.

[Assistant] SELECT o.order_id, o.order_type, a.name, SUM(t.quantity) AS total_traded_quantity FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id WHERE o.order_type = 'buy' GROUP BY o.order_id, o.order_type, a.name HAVING SUM(t.quantity) > 50;

[User] Can you also include the user ID of the user who placed the order?

[Assistant] SELECT o.order_id, o.user_id, o.order_type, a.name, SUM(t.quantity) AS total_traded_quantity FROM trading_platform.orders o JOIN trading_platform.trades t ON o.order_id = t.order_id JOIN trading_platform.assets a ON o.asset_id = a.asset_id WHERE o.order_type = 'buy' GROUP BY o.order_id, o.user_id, o.order_type, a.name HAVING SUM(t.quantity) > 50;


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.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Retrieve all unique chief complaints from medical_records.

[Assistant]
SELECT DISTINCT chief_complaint
FROM healthcare.medical_records;

[User] Now show chief complaints that occur more than 3 times along with their occurrence count.

[Assistant]
SELECT chief_complaint,
       COUNT(*) AS complaint_count
FROM healthcare.medical_records
GROUP BY chief_complaint
HAVING COUNT(*) > 3;

[User] Show prescriptions with their corresponding chief complaint from the medical record. Return prescription_id, record_id, and chief_complaint.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id;

[User] Only include prescriptions where chief_complaint contains 'fever' and the route is 'Oral'.

[Assistant]
SELECT p.prescription_id, p.record_id, mr.chief_complaint
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral';

[User] Also include the medication_name by joining the medications table and sort the results by prescription_date ascending.

[Assistant]
SELECT p.prescription_id,
       p.record_id,
       mr.chief_complaint,
       m.medication_name
FROM healthcare.prescriptions p
LEFT JOIN healthcare.medical_records mr ON p.record_id = mr.record_id
LEFT JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE mr.chief_complaint ILIKE '%fever%'
  AND p.route = 'Oral'
ORDER BY p.prescription_date ASC;

[User] List scheduled appointments, including the patient's full name, the doctor's full name, and the appointment time.

[Assistant] SELECT p.first_name, p.last_name, d.first_name, d.last_name, a.appointment_time FROM healthcare.appointments AS a JOIN healthcare.patients AS p ON a.patient_id = p.patient_id JOIN healthcare.doctors AS d ON a.doctor_id = d.doctor_id WHERE a.status = 'scheduled'

[User] Now, refine the results to only include appointments where the doctor's specialty is 'Cardiology'.

[Assistant] SELECT p.first_name, p.last_name, d.first_name, d.last_name, a.appointment_time FROM healthcare.appointments AS a JOIN healthcare.patients AS p ON a.patient_id = p.patient_id JOIN healthcare.doctors AS d ON a.doctor_id = d.doctor_id WHERE a.status = 'scheduled' AND d.specialty = 'Cardiology'

[User] Further filter these cardiology appointments to those occurring after '2024-07-01'.

[Assistant] SELECT p.first_name, p.last_name, d.first_name, d.last_name, a.appointment_time FROM healthcare.appointments AS a JOIN healthcare.patients AS p ON a.patient_id = p.patient_id JOIN healthcare.doctors AS d ON a.doctor_id = d.doctor_id WHERE a.status = 'scheduled' AND d.specialty = 'Cardiology' AND a.appointment_time > '2024-07-01'

[User] Also, include the appointment duration and order the results by appointment time ascending.

[Assistant] SELECT p.first_name, p.last_name, d.first_name, d.last_name, a.appointment_time, a.duration_minutes FROM healthcare.appointments AS a JOIN healthcare.patients AS p ON a.patient_id = p.patient_id JOIN healthcare.doctors AS d ON a.doctor_id = d.doctor_id WHERE a.status = 'scheduled' AND d.specialty = 'Cardiology' AND a.appointment_time > '2024-07-01' ORDER BY a.appointment_time ASC

[User] List all prescriptions, showing the prescription ID, the medication name, and the dosage.

[Assistant] SELECT p.prescription_id, m.medication_name, p.dosage FROM healthcare.prescriptions AS p JOIN healthcare.medications AS m ON p.medication_id = m.medication_id

[User] Count the number of medications provided by the manufacturer 'Novartis'.

[Assistant] SELECT count(*) FROM healthcare.medications WHERE manufacturer = 'Novartis'