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] For each chain, which token symbol has the highest pnl and what are its roi and avg_cost?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl;

[User] Could you please also include the realized_ratio for those tokens in the result?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost, t.realized_ratio
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl;

[User] Actually, could you show only results where roi is greater than 3 and realized_ratio is above 0.4?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost, t.realized_ratio
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl
WHERE t.roi > 3 AND t.realized_ratio > 0.4;

[User] And can you order the results by roi descending?

[Assistant]
SELECT t.chain, t.token_symbol, t.pnl, t.roi, t.avg_cost, t.realized_ratio
FROM smart_money_token_performance t
INNER JOIN (
  SELECT chain, MAX(pnl) AS max_pnl
  FROM smart_money_token_performance
  GROUP BY chain
) m
ON t.chain = m.chain AND t.pnl = m.max_pnl
WHERE t.roi > 3 AND t.realized_ratio > 0.4
ORDER BY t.roi DESC;

[User] Which 3 tokens across all chains have the highest realized_ratio and what are their avg_cost and roi?

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi
FROM smart_money_token_performance
ORDER BY realized_ratio DESC
LIMIT 3;

[User] I get an error, could you also display their pnl in the result?

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi, pnl
FROM smart_money_token_performance
ORDER BY realized_ratio DESC
LIMIT 3;

[User] Actually, I want tokens where realized_ratio is above 0.7 and net_flow is positive only.

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi, pnl
FROM smart_money_token_performance
WHERE realized_ratio > 0.7 AND net_flow > 0
ORDER BY realized_ratio DESC
LIMIT 3;

[User] And can you order the result by pnl descending instead?

[Assistant]
SELECT token_symbol, chain, realized_ratio, avg_cost, roi, pnl
FROM smart_money_token_performance
WHERE realized_ratio > 0.7 AND net_flow > 0
ORDER BY pnl DESC
LIMIT 3;

[User] List all pairs of tokens on the same chain where one has positive net_flow and another has negative net_flow, showing their symbols and net_flows.

[Assistant]
SELECT a.chain,
       a.token_symbol AS token_pos,
       a.net_flow    AS net_flow_pos,
       b.token_symbol AS token_neg,
       b.net_flow    AS net_flow_neg
FROM smart_money_token_performance a
JOIN smart_money_token_performance b
  ON a.chain = b.chain
 AND a.net_flow > 0
 AND b.net_flow < 0
 AND a.token_symbol < b.token_symbol;

[User] Actually, exclude pairs where the absolute difference in net_flow between the two tokens is less than 1000.

[Assistant]
SELECT a.chain,
       a.token_symbol AS token_pos,
       a.net_flow    AS net_flow_pos,
       b.token_symbol AS token_neg,
       b.net_flow    AS net_flow_neg
FROM smart_money_token_performance a
JOIN smart_money_token_performance b
  ON a.chain = b.chain
 AND a.net_flow > 0
 AND b.net_flow < 0
 AND a.token_symbol < b.token_symbol
 AND ABS(a.net_flow - b.net_flow) >= 1000;

[User] Also include the ROI for both tokens.

[Assistant]
SELECT a.chain,
       a.token_symbol AS token_pos,
       a.net_flow    AS net_flow_pos,
       a.roi         AS roi_pos,
       b.token_symbol AS token_neg,
       b.net_flow    AS net_flow_neg,
       b.roi         AS roi_neg
FROM smart_money_token_performance a
JOIN smart_money_token_performance b
  ON a.chain = b.chain
 AND a.net_flow > 0
 AND b.net_flow < 0
 AND a.token_symbol < b.token_symbol
 AND ABS(a.net_flow - b.net_flow) >= 1000;

[User] Finally, order by absolute net_flow difference descending and limit to the top 5.

[Assistant]
SELECT a.chain,
       a.token_symbol AS token_pos,
       a.net_flow    AS net_flow_pos,
       a.roi         AS roi_pos,
       b.token_symbol AS token_neg,
       b.net_flow    AS net_flow_neg,
       b.roi         AS roi_neg
FROM smart_money_token_performance a
JOIN smart_money_token_performance b
  ON a.chain = b.chain
 AND a.net_flow > 0
 AND b.net_flow < 0
 AND a.token_symbol < b.token_symbol
WHERE ABS(a.net_flow - b.net_flow) >= 1000
ORDER BY ABS(a.net_flow - b.net_flow) DESC
LIMIT 5;

[User] Which token on each chain has the highest ROI and what is its associated PNL and net_flow?

[Assistant]
SELECT a.chain,
       a.token_symbol,
       a.roi,
       a.pnl,
       a.net_flow
FROM smart_money_token_performance a
JOIN (
  SELECT chain, MAX(roi) AS max_roi
  FROM smart_money_token_performance
  GROUP BY chain
) b ON a.chain = b.chain AND a.roi = b.max_roi;

[User] Actually, I’d like to see the top 2 tokens with the highest ROI per chain instead of only the top one.

[Assistant]
WITH ranked AS (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY chain ORDER BY roi DESC) AS rn
  FROM smart_money_token_performance
)
SELECT chain, token_symbol, roi, pnl, net_flow
FROM ranked
WHERE rn <= 2;

[User] I got an error about ties when two tokens share the same ROI. Please adjust the query to include ties for the highest ROI.

[Assistant]
WITH ranked AS (
  SELECT *,
         DENSE_RANK() OVER (PARTITION BY chain ORDER BY roi DESC) AS dr
  FROM smart_money_token_performance
)
SELECT chain, token_symbol, roi, pnl, net_flow
FROM ranked
WHERE dr = 1;

[User] Can you also include the avg_cost for each result?

[Assistant]
WITH ranked AS (
  SELECT *,
         DENSE_RANK() OVER (PARTITION BY chain ORDER BY roi DESC) AS dr
  FROM smart_money_token_performance
)
SELECT chain, token_symbol, roi, pnl, net_flow, avg_cost
FROM ranked
WHERE dr = 1;

[User] What is the average ROI and average realized_ratio for each chain?

[Assistant]
SELECT chain,
       AVG(roi) AS avg_roi,
       AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
GROUP BY chain;

[User] Now filter to only include chains where average ROI is above 0.5.

[Assistant]
WITH stats AS (
  SELECT chain,
         AVG(roi) AS avg_roi,
         AVG(realized_ratio) AS avg_realized_ratio
  FROM smart_money_token_performance
  GROUP BY chain
)
SELECT chain, avg_roi, avg_realized_ratio
FROM stats
WHERE avg_roi > 0.5;

[User] What is the total net_flow and average realized_ratio for tokens on the Polygon chain?

[Assistant]
SELECT SUM(net_flow) AS total_net_flow, AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
WHERE chain = 'Polygon';

[User] Now, show me the same metrics for the Arbitrum chain.

[Assistant]
SELECT SUM(net_flow) AS total_net_flow, AVG(realized_ratio) AS avg_realized_ratio
FROM smart_money_token_performance
WHERE chain = 'Arbitrum';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )

[User] How many cases are associated with each unique lead lawyer ID? Show the lead lawyer ID and the count of cases, but only for lawyers who lead at least 5 cases. Sort the results by the case count in descending order.

[Assistant] SELECT lead_lawyer_id, count(case_id) FROM legal_services.cases GROUP BY lead_lawyer_id HAVING count(case_id) >= 5 ORDER BY count(case_id) DESC;

[User] List all cases opened in the 'State Court' jurisdiction in the year 2023, including their name, number, and client ID.

[Assistant] SELECT case_name, case_number, client_id FROM legal_services.cases WHERE court_jurisdiction = 'State Court' AND date_opened >= '2023-01-01' AND date_opened < '2024-01-01';

[User] Can you narrow this down to only show cases where the case type is 'Criminal'?

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal';

[User] Show the distribution of cases by their current status, listing each status and the total count of cases in that status.

[Assistant] SELECT status, COUNT(*) AS case_count FROM legal_services.cases GROUP BY status ORDER BY case_count DESC;

[User] Find pairs of cases that share the same client and have the same status, but are different cases. Display the case name and case number for both cases in the pair, along with the shared client ID and shared status.

[Assistant] SELECT T1.case_name, T1.case_number, T2.case_name, T2.case_number, T1.client_id, T1.status FROM legal_services.cases AS T1 JOIN legal_services.cases AS T2 ON T1.client_id = T2.client_id AND T1.status = T2.status WHERE T1.case_id < T2.case_id;

[User] List the case name, case number, and date opened for all cases with a status of 'Pending'.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE status = 'Pending';

[User] Now, only show cases from that list where the case type is 'Criminal'.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE status = 'Pending' AND case_type = 'Criminal';

[User] Additionally, filter for cases opened in the year 2024 and sort the results by the date opened, with the oldest cases first.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE status = 'Pending' AND case_type = 'Criminal' AND date_opened BETWEEN '2024-01-01' AND '2024-12-31' ORDER BY date_opened 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 social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

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

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

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

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

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

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

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

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

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

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

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

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

[User] How many group conversations are there?

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)

[User] List all post IDs and the corresponding hashtag names where posts were created near latitude 40.0 and longitude -74.0.

[Assistant]
SELECT p.post_id, h.tag_name
FROM social_media.posts p
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE ABS(p.location_lat - 40.0) < 0.1 AND ABS(p.location_lon + 74.0) < 0.1;

[User] Only show the results where the hashtag name contains the word 'event'.

[Assistant]
SELECT p.post_id, h.tag_name
FROM social_media.posts p
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE ABS(p.location_lat - 40.0) < 0.1 AND ABS(p.location_lon + 74.0) < 0.1
  AND h.tag_name ILIKE '%event%';

[User] Which users participated in conversations where the hashtag 'AI' was used in associated posts? I want both usernames and conversation IDs.

[Assistant]
SELECT cp.user_id, cp.conversation_id
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI';

[User] Can you also include the date the user joined those conversations?

[Assistant]
SELECT cp.user_id, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI';

[User] Now, restrict the results to only conversations that the user joined after January 1, 2024.

[Assistant]
SELECT cp.user_id, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI' AND cp.joined_at > '2024-01-01';

[User] If the same user participated in multiple conversations for the same tag, show only distinct combinations of user and conversation.

[Assistant]
SELECT DISTINCT cp.user_id, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI' AND cp.joined_at > '2024-01-01';

[User] List group conversation names and the IDs of notifications associated with them, where the notification type is 'mention'.

[Assistant] SELECT T1.group_name, T2.notification_id FROM social_media.conversations AS T1 INNER JOIN social_media.notifications AS T2 ON T1.conversation_id = T2.target_entity_id WHERE T1.is_group_chat = TRUE AND T2.notification_type = 'mention';

[User] Only include notifications that have not been read (read_at is null).

[Assistant] SELECT T1.group_name, T2.notification_id FROM social_media.conversations AS T1 INNER JOIN social_media.notifications AS T2 ON T1.conversation_id = T2.target_entity_id WHERE T1.is_group_chat = TRUE AND T2.notification_type = 'mention' AND T2.read_at IS NULL;

[User] List all notifications related to messages. Please show notification_id, recipient_user_id, conversation_id, and the creation time.

[Assistant]
SELECT notification_id, recipient_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation';

[User] Actually, please only include notifications that haven't been read yet.

[Assistant]
SELECT notification_id, recipient_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation' AND read_at IS NULL;

[User] Could you also show the sender_user_id for each notification?

[Assistant]
SELECT notification_id, recipient_user_id, sender_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation' AND read_at IS NULL;

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

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

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

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

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

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

[User] Order the results by unread_mentions descending.

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

[User] Limit to the top 5 group chats.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] For each service category, show the category and the number of distinct citizens who have scheduled at least one appointment for a service in that category. Order the results by the number of citizens in descending order.

[Assistant]
SELECT s.category,
       COUNT(DISTINCT a.citizen_id) AS distinct_citizen_count
FROM government_services.appointments a
JOIN government_services.services s ON a.service_id = s.service_id
GROUP BY s.category
ORDER BY distinct_citizen_count DESC;

[User] For each citizen who has at least one document pending verification and at least one appointment not completed, display the citizen's full name, the document type, the document's upload timestamp, the appointment ID, and the appointment status.

[Assistant]
SELECT c.citizen_id,
       c.first_name || ' ' || c.last_name AS full_name,
       d.document_type,
       d.upload_timestamp,
       a.appointment_id,
       a.status
FROM government_services.citizens c
JOIN government_services.documents d ON c.citizen_id = d.citizen_id
JOIN government_services.appointments a ON c.citizen_id = a.citizen_id
WHERE d.verification_status = 'Pending'
  AND a.status <> 'Completed';

[User] List the service_id, service_name, and agency_id for all active services that have an online application URL provided.

[Assistant]
SELECT service_id,
       service_name,
       agency_id
FROM government_services.services
WHERE is_active = TRUE
  AND online_application_url IS NOT NULL;

[User] Show the names of all services and the names of their corresponding agencies that are offered at accessible locations in 'Chicago'.

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

[User] For each citizen who has made a payment for an application that is still in 'Processing' status, list their full name, application_id, payment_id, amount, currency, and the application status.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name,
       a.application_id,
       p.payment_id,
       p.amount,
       p.currency,
       a.status AS application_status
FROM government_services.citizens c
JOIN government_services.applications a ON c.citizen_id = a.citizen_id
JOIN government_services.payments p ON a.application_id = p.application_id
WHERE a.status = 'Processing';

[User] List the city and the count of accessible and inaccessible service locations separately. Return city, accessible_count, and inaccessible_count.

[Assistant]
SELECT city,
       SUM(CASE WHEN is_accessible THEN 1 ELSE 0 END) AS accessible_count,
       SUM(CASE WHEN is_accessible = false THEN 1 ELSE 0 END) AS inaccessible_count
FROM government_services.service_locations
GROUP BY city;


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.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)
)

[User] List each patient's first and last medical record entries, showing patient_id, earliest_record_id, earliest_record_date, latest_record_id, and latest_record_date.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date
        FROM healthcare.medical_records
        GROUP BY patient_id
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] Filter to include only patients who have at least three medical record entries.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date,
            COUNT(*) AS total_records
        FROM healthcare.medical_records
        GROUP BY patient_id
        HAVING COUNT(*) >= 3
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] Also include for each patient the count of distinct days on which records were made, labeled active_days.

[Assistant]
SELECT
    fl.patient_id,
    fr.record_id AS earliest_record_id,
    fr.record_date AS earliest_record_date,
    lr.record_id AS latest_record_id,
    lr.record_date AS latest_record_date,
    fl.active_days
FROM
    (
        SELECT
            patient_id,
            MIN(record_date) AS first_date,
            MAX(record_date) AS last_date,
            COUNT(*) AS total_records,
            COUNT(DISTINCT date_trunc('day', record_date)) AS active_days
        FROM healthcare.medical_records
        GROUP BY patient_id
        HAVING COUNT(*) >= 3
    ) fl
    JOIN healthcare.medical_records fr
      ON fr.patient_id = fl.patient_id
     AND fr.record_date = fl.first_date
    JOIN healthcare.medical_records lr
      ON lr.patient_id = fl.patient_id
     AND lr.record_date = fl.last_date;

[User] What is the total count of medical records created in the year 2023 where the assessment field is not empty?

[Assistant] SELECT COUNT(*) FROM healthcare.medical_records mr WHERE (mr.assessment IS NOT NULL AND mr.assessment != '') AND EXTRACT(YEAR FROM mr.record_date) = 2023;

[User] Now, break down this count by the doctor who created the record. Show the doctor_id and the count.

[Assistant] SELECT mr.doctor_id, COUNT(*) FROM healthcare.medical_records mr WHERE (mr.assessment IS NOT NULL AND mr.assessment != '') AND EXTRACT(YEAR FROM mr.record_date) = 2023 GROUP BY mr.doctor_id;

[User] List the record ID, record date, patient ID, and chief complaint for medical records belonging to patients whose last name is 'Smith'. Also include the patient's last name in the results.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith';

[User] Refine this list to only show records where the record date is in 2024 and the chief complaint is not null. Sort by record_date in ascending order.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith' AND EXTRACT(YEAR FROM mr.record_date) = 2024 AND (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') ORDER BY mr.record_date ASC;

[User] List all pairs of record_id for the same patient that were created on the same day. Show the two record_ids, patient_id, and the date.

[Assistant]
SELECT
    mr1.patient_id,
    date_trunc('day', mr1.record_date) AS record_day,
    mr1.record_id AS record_id_1,
    mr2.record_id AS record_id_2
FROM healthcare.medical_records mr1
JOIN healthcare.medical_records mr2
  ON mr1.patient_id = mr2.patient_id
 AND date_trunc('day', mr1.record_date) = date_trunc('day', mr2.record_date)
 AND mr1.record_id < mr2.record_id;

[User] Only include pairs where both records have a heart rate over 100 in their vitals.

[Assistant]
SELECT
    mr1.patient_id,
    date_trunc('day', mr1.record_date) AS record_day,
    mr1.record_id AS record_id_1,
    mr2.record_id AS record_id_2
FROM healthcare.medical_records mr1
JOIN healthcare.medical_records mr2
  ON mr1.patient_id = mr2.patient_id
 AND date_trunc('day', mr1.record_date) = date_trunc('day', mr2.record_date)
 AND mr1.record_id < mr2.record_id
WHERE (mr1.vitals->>'HR')::int > 100
  AND (mr2.vitals->>'HR')::int > 100;

[User] I would like to see a list of all medical records where the chief complaint contains the word 'cough' along with the doctor's ID and the date of the record.

[Assistant] SELECT record_id, doctor_id, record_date, chief_complaint FROM healthcare.medical_records WHERE chief_complaint ILIKE '%cough%';

[User] Could you expand this to show only records where the temperature in the vitals field is above 37.5°C?

[Assistant] SELECT record_id, doctor_id, record_date, chief_complaint, vitals->>'temperature' AS temperature FROM healthcare.medical_records WHERE chief_complaint ILIKE '%cough%' AND (vitals->>'temperature')::float > 37.5;

[User] Now, restrict it further to only show records documented after January 1st, 2024.

[Assistant] SELECT record_id, doctor_id, record_date, chief_complaint, vitals->>'temperature' AS temperature FROM healthcare.medical_records WHERE chief_complaint ILIKE '%cough%' AND (vitals->>'temperature')::float > 37.5 AND record_date >= '2024-01-01';

[User] Find all medical records associated with an appointment, and show the record_id, appointment_id, and the record_date.

[Assistant]
SELECT record_id, appointment_id, record_date
FROM healthcare.medical_records
WHERE appointment_id IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )

[User] Give me the count of developers per country.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count
FROM gaming_technology.developers
GROUP BY country;

[User] Actually, include only countries with more than 5 developers.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count
FROM gaming_technology.developers
GROUP BY country
HAVING COUNT(*) > 5;

[User] Also calculate the average founded_year per country as avg_year.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count,
       AVG(founded_year) AS avg_year
FROM gaming_technology.developers
GROUP BY country
HAVING COUNT(*) > 5;

[User] Order the results by avg_year descending.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count,
       AVG(founded_year) AS avg_year
FROM gaming_technology.developers
GROUP BY country
HAVING COUNT(*) > 5
ORDER BY avg_year DESC;

[User] Could you list all pairs of developers in the same country but different companies? Return developer1, developer2, and country.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id;

[User] Now restrict pairs to only those in country 'USA' or 'Canada'.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada');

[User] Sort the pairs by developer1 name ascending.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada')
ORDER BY d1.name ASC;

[User] Find all pairs of developers in the same country but founded in different years. Show each developer's name, their founded_year, and the shared country.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country, d1.founded_year AS founded1, d2.founded_year AS founded2
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
  AND d1.founded_year <> d2.founded_year;

[User] Now show only those pairs where the difference in their founded_year is at least 10 years.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country, d1.founded_year AS founded1, d2.founded_year AS founded2, ABS(d1.founded_year - d2.founded_year) AS year_diff
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
WHERE ABS(d1.founded_year - d2.founded_year) >= 10;

[User] List all developer names and their countries.

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

[User] Filter the list to only include developers from countries that start with 'U'.

[Assistant] SELECT name, country FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] For these developers from countries starting with 'U', what are the minimum and maximum founded years?

[Assistant] SELECT MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] Also, include the average founded year and the total count of developers in this filtered group.

[Assistant] SELECT COUNT(*), AVG(founded_year), MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] Which countries have the highest number of developer companies founded after 2005? Please show country, the number of developers, and order by developer count descending.

[Assistant]
SELECT country, COUNT(*) AS developer_count
FROM gaming_technology.developers
WHERE founded_year > 2005
GROUP BY country
ORDER BY developer_count DESC;

[User] Exclude any rows where the country value is NULL or an empty string.

[Assistant]
SELECT country, COUNT(*) AS developer_count
FROM gaming_technology.developers
WHERE founded_year > 2005
  AND country IS NOT NULL
  AND country <> ''
GROUP BY country
ORDER BY developer_count DESC;

[User] Can you also show the earliest founded_year among all developers in each country?

[Assistant]
SELECT country, COUNT(*) AS developer_count, MIN(founded_year) AS earliest_founded_year
FROM gaming_technology.developers
WHERE founded_year > 2005
  AND country IS NOT NULL
  AND country <> ''
GROUP BY country
ORDER BY developer_count DESC;

[User] Show me the names and websites of all developers whose website contains '.com'.

[Assistant] SELECT name, website FROM gaming_technology.developers WHERE website LIKE '%.com%';

[User] Only include developers from 'USA'.

[Assistant] SELECT name, website FROM gaming_technology.developers WHERE website LIKE '%.com%' AND country = 'USA';

[User] Order the results by the developer's name in ascending order.

[Assistant] SELECT name, website FROM gaming_technology.developers WHERE website LIKE '%.com%' AND country = 'USA' ORDER BY name ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] Which token symbol has the highest price among all tokens held by CEXes on the Polygon chain?

[Assistant] SELECT token_symbol, MAX(price) AS max_price FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY max_price DESC LIMIT 1;

[User] Can you also show which exchange holds the largest balance of that token?

[Assistant] SELECT exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 1;

[User] Please include the snapshot_time of the record as well.

[Assistant] SELECT snapshot_time, exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 1;

[User] Instead of only the largest balance, can you list the top 3 addresses by usd_value for that token?

[Assistant] SELECT snapshot_time, exchange, address, balance, usd_value FROM cex_token_balance WHERE chain = 'Polygon' AND token_symbol = (SELECT token_symbol FROM cex_token_balance WHERE chain = 'Polygon' GROUP BY token_symbol ORDER BY MAX(price) DESC LIMIT 1) ORDER BY usd_value DESC LIMIT 3;

[User] For each exchange, compute the percentage change in total USD value of its holdings between snapshots '2023-01-01 00:00:00' and '2023-02-01 00:00:00'. Show exchange, chain, value_jan, value_feb, and pct_change.

[Assistant]
SELECT t1.exchange,
       t1.chain,
       t1.total_usd AS value_jan,
       t2.total_usd AS value_feb,
       ((t2.total_usd - t1.total_usd) / NULLIF(t1.total_usd,0)) * 100 AS pct_change
FROM (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-01-01 00:00:00'
  GROUP BY exchange, chain
) t1
JOIN (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-02-01 00:00:00'
  GROUP BY exchange, chain
) t2
  ON t1.exchange = t2.exchange AND t1.chain = t2.chain;

[User] Please modify the query to compare between '2023-01-01 00:00:00' and the latest available snapshot instead.

[Assistant]
WITH latest AS (
  SELECT MAX(snapshot_time) AS snap FROM cex_token_balance
),
jan AS (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = '2023-01-01 00:00:00'
  GROUP BY exchange, chain
),
feb AS (
  SELECT exchange, chain, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = (SELECT snap FROM latest)
  GROUP BY exchange, chain
)
SELECT j.exchange,
       j.chain,
       j.total_usd AS value_jan,
       f.total_usd AS value_latest,
       ((f.total_usd - j.total_usd) / NULLIF(j.total_usd,0)) * 100 AS pct_change
FROM jan j
JOIN feb f
  ON j.exchange = f.exchange AND j.chain = f.chain;

[User] List all CEX addresses on the BSC chain that hold more than $1 million USD value in total.

[Assistant] SELECT address, SUM(usd_value) AS total_usd_value FROM cex_token_balance WHERE chain = 'BSC' GROUP BY address HAVING SUM(usd_value) > 1000000;

[User] List each blockchain (chain) and the centralized exchange that holds the highest total USD value of tokens, as well as the exchange with the lowest total USD value of tokens. Show chain, max_exchange, max_value, min_exchange, and min_value.

[Assistant]
WITH totals AS (
  SELECT chain, exchange, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  GROUP BY chain, exchange
),
max_totals AS (
  SELECT chain, exchange AS max_exchange, total_usd AS max_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd DESC) AS rn
    FROM totals
  ) t
  WHERE rn = 1
),
min_totals AS (
  SELECT chain, exchange AS min_exchange, total_usd AS min_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd ASC) AS rn
    FROM totals
  ) t
  WHERE rn = 1
)
SELECT m.chain, m.max_exchange, m.max_value, n.min_exchange, n.min_value
FROM max_totals m
JOIN min_totals n USING (chain);

[User] Actually, restrict the analysis to the latest snapshot_time only.

[Assistant]
WITH latest AS (
  SELECT MAX(snapshot_time) AS snap
  FROM cex_token_balance
),
totals AS (
  SELECT chain, exchange, SUM(usd_value) AS total_usd
  FROM cex_token_balance
  WHERE snapshot_time = (SELECT snap FROM latest)
  GROUP BY chain, exchange
),
max_totals AS (
  SELECT chain, exchange AS max_exchange, total_usd AS max_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd DESC) AS rn
    FROM totals
  ) t WHERE rn = 1
),
min_totals AS (
  SELECT chain, exchange AS min_exchange, total_usd AS min_value
  FROM (
    SELECT chain, exchange, total_usd,
      ROW_NUMBER() OVER (PARTITION BY chain ORDER BY total_usd ASC) AS rn
    FROM totals
  ) t WHERE rn = 1
)
SELECT m.chain, m.max_exchange, m.max_value, n.min_exchange, n.min_value
FROM max_totals m
JOIN min_totals n USING (chain);

[User] For the latest snapshot time, list the total `usd_value` held by CEXes for each distinct `token_symbol` across all chains. Order the results by total value descending.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, sum(usd_value) as total_usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
GROUP BY token_symbol
ORDER BY total_usd_value DESC;

[User] Now, filter this list to only include tokens where the total `usd_value` across all CEX holdings is greater than $5,000,000.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, sum(usd_value) as total_usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
GROUP BY token_symbol
HAVING sum(usd_value) > 5000000.0
ORDER BY total_usd_value DESC;

[User] Find all tokens on the 'BSC' chain in the latest snapshot where the individual holding `usd_value` is greater than $1,000,000. Show their symbol, exchange, balance, and USD value.

[Assistant]
WITH latest_snapshot AS (
  SELECT max(snapshot_time) as max_time
  FROM cex_token_balance
)
SELECT token_symbol, exchange, balance, usd_value
FROM cex_token_balance ctb
JOIN latest_snapshot ls ON ctb.snapshot_time = ls.max_time
WHERE chain = 'BSC' AND usd_value > 1000000.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
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )

[User] Find transaction IDs in the utxos table that have both spent and unspent UTXOs associated with them. List these transaction IDs.

[Assistant] SELECT transaction_id FROM trading_platform.utxos GROUP BY transaction_id HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1;

[User] Okay, for those transaction IDs, show the total count of spent UTXOs and the total count of unspent UTXOs.

[Assistant] SELECT transaction_id, SUM(CASE WHEN spent = true THEN 1 ELSE 0 END) AS spent_count, SUM(CASE WHEN spent = false THEN 1 ELSE 0 END) AS unspent_count FROM trading_platform.utxos WHERE transaction_id IN ( SELECT transaction_id FROM trading_platform.utxos GROUP BY transaction_id HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY transaction_id;

[User] List all addresses from the utxos table that have at least one spent UTXO and at least one unspent UTXO.

[Assistant] SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1;

[User] For the addresses identified in the previous step, show the address and the total amount of their unspent UTXOs.

[Assistant] SELECT address, SUM(CASE WHEN spent = false THEN amount ELSE 0 END) AS total_unspent_amount FROM trading_platform.utxos WHERE address IN ( SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY address;

[User] Filter the previous result to show only addresses where the total unspent amount is greater than 1000.

[Assistant] SELECT address, SUM(CASE WHEN spent = false THEN amount ELSE 0 END) AS total_unspent_amount FROM trading_platform.utxos WHERE address IN ( SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY address HAVING SUM(CASE WHEN spent = false THEN amount ELSE 0 END) > 1000;

[User] For the addresses with a total unspent amount greater than 1000 (from the previous step), also include the total amount of their spent UTXOs, and order the results by the total unspent amount descending.

[Assistant] SELECT address, SUM(CASE WHEN spent = false THEN amount ELSE 0 END) AS total_unspent_amount, SUM(CASE WHEN spent = true THEN amount ELSE 0 END) AS total_spent_amount FROM trading_platform.utxos WHERE address IN ( SELECT address FROM trading_platform.utxos GROUP BY address HAVING MIN(spent::int) = 0 AND MAX(spent::int) = 1 ) GROUP BY address HAVING SUM(CASE WHEN spent = false THEN amount ELSE 0 END) > 1000 ORDER BY total_unspent_amount DESC;

[User] List all UTXO IDs, addresses, and amounts for unspent UTXOs with an amount between 200 and 800.

[Assistant] SELECT utxo_id, address, amount FROM trading_platform.utxos WHERE spent = false AND amount BETWEEN 200 AND 800;

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


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.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)

[User] For each trip, provide the trip_id, the total fuel quantity refueled, and the number of refueling events that occurred during the trip.

[Assistant]
SELECT trip_id, SUM(quantity) AS total_fuel_quantity, COUNT(*) AS refuel_event_count
FROM transportation.fuel_logs
WHERE trip_id IS NOT NULL
GROUP BY trip_id;

[User] For each fuel type, list the number of unique locations where fuel refueling occurred, and also show the total quantity refueled for that fuel type and location.

[Assistant]
SELECT fuel_type, location_id, COUNT(DISTINCT location_id) AS unique_location_count, SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY fuel_type, location_id;

[User] Show all fuel logs for vehicle_id 'VH123', including the timestamp, fuel type, quantity, and the location_id. Sort the list by timestamp descending.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] Can you also include the odometer reading and total cost for each fuel log in the result?

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] I only want to see records where the total_cost is above 100.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp DESC;

[User] Actually, please limit the results to just the 5 most recent logs.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp DESC
LIMIT 5;

[User] I need the total fuel cost per vehicle for each fuel type.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type;

[User] Filter this to only include records where the cost_per_unit is greater than 1.50.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type;

[User] Also, sort the result by the total cost in descending order.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC;

[User] Finally, limit the output to the top 5 entries.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC
LIMIT 5;

[User] For each vehicle, show the first and last fueling events including their timestamps and the quantities refueled.

[Assistant]
WITH first_last AS (
  SELECT
    vehicle_id,
    MIN(log_timestamp) AS first_time,
    MAX(log_timestamp) AS last_time
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT
  f1.vehicle_id,
  f1.log_timestamp AS first_refuel_time,
  f1.quantity AS first_quantity,
  f2.log_timestamp AS last_refuel_time,
  f2.quantity AS last_quantity
FROM first_last fl
JOIN transportation.fuel_logs f1
  ON fl.vehicle_id = f1.vehicle_id
  AND fl.first_time = f1.log_timestamp
JOIN transportation.fuel_logs f2
  ON fl.vehicle_id = f2.vehicle_id
  AND fl.last_time = f2.log_timestamp;

[User] I need a summary of fueling events grouped by fuel_type: count of events and total quantity.

[Assistant]
SELECT
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Actually, could you break it down by vehicle as well, so I can see for each vehicle and fuel_type the number of events and total quantity?

[Assistant]
SELECT
  vehicle_id,
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type;

[User] Only include those groups where total_quantity exceeds 100 units.

[Assistant]
SELECT
  vehicle_id,
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type
HAVING SUM(quantity) > 100;

[User] Sort the results by total_quantity descending and limit to top 5 rows.

[Assistant]
SELECT
  vehicle_id,
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type
HAVING SUM(quantity) > 100
ORDER BY total_quantity DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] Find all pairs of appointments that are scheduled for the same case and overlap in time. Show the IDs of the two overlapping appointments and the shared case ID.

[Assistant] SELECT t1.appointment_id AS appointment1_id, t2.appointment_id AS appointment2_id, t1.case_id FROM legal_services.appointments AS t1 JOIN legal_services.appointments AS t2 ON t1.case_id = t2.case_id AND t1.appointment_id != t2.appointment_id WHERE t1.start_time < t2.end_time AND t2.start_time < t1.end_time;

[User] How many appointments were created in the month of July 2024?

[Assistant]
SELECT COUNT(*) AS appointment_count
FROM legal_services.appointments
WHERE DATE_TRUNC('month', created_at) = DATE '2024-07-01';

[User] Give me a list of all appointments showing the subject and location, for appointments created after March 1st, 2024.

[Assistant] SELECT subject, location FROM legal_services.appointments WHERE created_at > '2024-03-01';

[User] Add the appointment_id and start_time to the output.

[Assistant] SELECT appointment_id, subject, location, start_time FROM legal_services.appointments WHERE created_at > '2024-03-01';

[User] Now, filter to only show appointments where the subject contains the word 'Consultation'.

[Assistant] SELECT appointment_id, subject, location, start_time FROM legal_services.appointments WHERE created_at > '2024-03-01' AND subject ILIKE '%Consultation%';

[User] Order the results by location alphabetically and then by start_time ascending.

[Assistant] SELECT appointment_id, subject, location, start_time FROM legal_services.appointments WHERE created_at > '2024-03-01' AND subject ILIKE '%Consultation%' ORDER BY location ASC, start_time ASC;

[User] Show me all appointments where the lawyer_id matches the client_id, and display the appointment_id, start_time, and status.

[Assistant] SELECT appointment_id, start_time, status FROM legal_services.appointments WHERE lawyer_id = client_id;

[User] Find appointments that are longer than 30 minutes.

[Assistant] SELECT * FROM legal_services.appointments WHERE end_time IS NOT NULL AND start_time IS NOT NULL AND end_time > start_time + INTERVAL '30 minutes'

[User] Show me all appointments that have both a non-null location and notes, along with their appointment_id, client_id, lawyer_id, and start_time.

[Assistant] SELECT appointment_id, client_id, lawyer_id, start_time FROM legal_services.appointments WHERE location IS NOT NULL AND notes IS NOT NULL;

[User] Can you only include those appointments where the status is 'Completed'?

[Assistant] SELECT appointment_id, client_id, lawyer_id, start_time FROM legal_services.appointments WHERE location IS NOT NULL AND notes IS NOT NULL AND status = 'Completed';

[User] Also, sort the results by start_time descending.

[Assistant] SELECT appointment_id, client_id, lawyer_id, start_time FROM legal_services.appointments WHERE location IS NOT NULL AND notes IS NOT NULL AND status = 'Completed' ORDER BY start_time 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.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )

[User] Show me pairs of trip IDs that used the same vehicle.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id;

[User] Now, filter this list to only include pairs where both trips have a 'Completed' status.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id
WHERE
  t1.status = 'Completed' AND t2.status = 'Completed';

[User] Show me the total number of passengers transported by each vehicle in the last week, along with the vehicle ID.

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id;

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

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers, AVG(passenger_count) AS avg_passengers_per_trip FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id;

[User] Now filter to only show vehicles that transported more than 100 passengers total.

[Assistant] SELECT vehicle_id, SUM(passenger_count) AS total_passengers, AVG(passenger_count) AS avg_passengers_per_trip FROM transportation.trips WHERE status = 'completed' AND actual_departure >= CURRENT_DATE - INTERVAL '7 days' GROUP BY vehicle_id HAVING SUM(passenger_count) > 100;

[User] What is the count of trips for each status?

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

[User] Only include statuses with more than 5 trips.

[Assistant]
SELECT
  status,
  COUNT(*) AS trip_count
FROM transportation.trips
GROUP BY
  status
HAVING
  COUNT(*) > 5;

[User] Find consecutive pairs of trips for each vehicle based on the scheduled departure time.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn;

[User] From these consecutive pairs, only show those where the destination of the first trip matches the origin of the second trip.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn
WHERE
  t1.destination_location_id = t2.origin_location_id;

[User] Also, only include pairs where the time difference between the scheduled departures is less than 24 hours.

[Assistant]
WITH RankedTrips AS (
  SELECT
    trip_id,
    vehicle_id,
    scheduled_departure,
    origin_location_id,
    destination_location_id,
    ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY scheduled_departure) as rn
  FROM transportation.trips
)
SELECT
  t1.trip_id AS first_trip_id,
  t2.trip_id AS second_trip_id,
  t1.vehicle_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.scheduled_departure AS second_scheduled_departure,
  t1.destination_location_id AS first_destination_location_id,
  t2.origin_location_id AS second_origin_location_id
FROM RankedTrips AS t1
JOIN RankedTrips AS t2
  ON t1.vehicle_id = t2.vehicle_id AND t1.rn + 1 = t2.rn
WHERE
  t1.destination_location_id = t2.origin_location_id
  AND t2.scheduled_departure < t1.scheduled_departure + INTERVAL '24 hour';

[User] For each vehicle, list the vehicle_id and the total number of trips it has performed.

[Assistant] SELECT vehicle_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY vehicle_id;

[User] Can you limit this to only vehicles that have more than 10 trips?

[Assistant] SELECT vehicle_id, COUNT(*) AS trip_count FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 10;

[User] In addition, for these vehicles, can you show the driver_id who has driven the highest number of trips for each vehicle?

[Assistant] SELECT vehicle_id, driver_id, trip_driver_count FROM (SELECT vehicle_id, driver_id, COUNT(*) AS trip_driver_count, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY COUNT(*) DESC) as rn FROM transportation.trips GROUP BY vehicle_id, driver_id) t WHERE rn = 1 AND vehicle_id IN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 10);

[User] List the booking ID, trip ID, and the booking status for all bookings.

[Assistant] SELECT booking_id, trip_id, status FROM transportation.bookings;

[User] For these bookings, please also include the scheduled departure time of the corresponding trip.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id;

[User] Only show bookings for trips with more than 50 passengers.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id WHERE T.passenger_count > 50;

[User] Order the results by scheduled departure time in descending order.

[Assistant] SELECT B.booking_id, B.trip_id, B.status, T.scheduled_departure FROM transportation.bookings AS B JOIN transportation.trips AS T ON B.trip_id = T.trip_id WHERE T.passenger_count > 50 ORDER BY T.scheduled_departure 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 healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Show each patient's policy number, the associated insurance plan ID, and any medications they have been prescribed, including the medication ID and prescription date.

[Assistant]
SELECT pi.patient_id, pi.policy_number, pi.plan_id, pr.medication_id, pr.prescription_date
FROM healthcare.patient_insurance pi
JOIN healthcare.prescriptions pr ON pi.patient_id = pr.patient_id;

[User] Only include prescriptions that were made after the insurance policy's effective date.

[Assistant]
SELECT pi.patient_id, pi.policy_number, pi.plan_id, pr.medication_id, pr.prescription_date
FROM healthcare.patient_insurance pi
JOIN healthcare.prescriptions pr ON pi.patient_id = pr.patient_id
WHERE pr.prescription_date >= pi.effective_date;

[User] Add the expiration date of the insurance policy and only show records where the prescription was made before the policy expired.

[Assistant]
SELECT pi.patient_id, pi.policy_number, pi.plan_id, pi.expiration_date, pr.medication_id, pr.prescription_date
FROM healthcare.patient_insurance pi
JOIN healthcare.prescriptions pr ON pi.patient_id = pr.patient_id
WHERE pr.prescription_date >= pi.effective_date
  AND (pi.expiration_date IS NULL OR pr.prescription_date < pi.expiration_date);

[User] How many unique medications have ever been prescribed to each patient? Show patient_id and medication_count.

[Assistant]
SELECT patient_id, COUNT(DISTINCT medication_id) AS medication_count
FROM healthcare.prescriptions
GROUP BY patient_id;

[User] Only show patients who have been prescribed at least 5 unique medications.

[Assistant]
SELECT patient_id, COUNT(DISTINCT medication_id) AS medication_count
FROM healthcare.prescriptions
GROUP BY patient_id
HAVING COUNT(DISTINCT medication_id) >= 5;

[User] List the full names of patients who have ever been prescribed a medication manufactured by 'Novartis'.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Novartis';

[User] Please also show the medication name for each result.

[Assistant]
SELECT DISTINCT p.first_name, p.last_name, m.medication_name
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Novartis';

[User] Show me a list of patients along with their latest prescription's medication name, prescription date, and the prescribing doctor's ID.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pr.medication_id, m.medication_name, pr.prescription_date, pr.doctor_id
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.prescription_date = (
    SELECT MAX(prescription_date)
    FROM healthcare.prescriptions pr2
    WHERE pr2.patient_id = p.patient_id
);

[User] Instead, only show results for patients whose latest prescription's end_date is in the future.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pr.medication_id, m.medication_name, pr.prescription_date, pr.doctor_id
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.prescription_date = (
    SELECT MAX(prescription_date)
    FROM healthcare.prescriptions pr2
    WHERE pr2.patient_id = p.patient_id
)
AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE);

[User] Also include the generic name of the medication in the results.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, pr.medication_id, m.medication_name, m.generic_name, pr.prescription_date, pr.doctor_id
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.prescription_date = (
    SELECT MAX(prescription_date)
    FROM healthcare.prescriptions pr2
    WHERE pr2.patient_id = p.patient_id
)
AND (pr.end_date IS NULL OR pr.end_date > CURRENT_DATE);

[User] I need to list all chronic diagnoses that have at least one prescription, including diagnosis_code, diagnosis_date, and medication_name.

[Assistant]
SELECT d.diagnosis_code, d.diagnosis_date, m.medication_name
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p ON d.patient_id = p.patient_id
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE d.is_chronic = TRUE;

[User] Actually, only include those prescriptions where quantity_dispensed > 50 and the diagnosis status is 'Active'.

[Assistant]
SELECT d.diagnosis_code, d.diagnosis_date, m.medication_name
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p ON d.patient_id = p.patient_id
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE d.is_chronic = TRUE
  AND d.status = 'Active'
  AND p.quantity_dispensed > 50;

[User] Show prescription_id, medication_name, and dosage for all prescriptions where the medication manufacturer is 'Pfizer'.

[Assistant]
SELECT p.prescription_id, m.medication_name, p.dosage
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE m.manufacturer = 'Pfizer';


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, 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] 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] 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] What is the total balance and the number of accounts for each currency, including only accounts opened in the last 2 years?

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency

[User] Please exclude currencies where the total balance is less than 100000.

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency HAVING SUM(balance)  >=  100000

[User] Can you also include the average interest rate for the remaining currencies, considering only accounts with 'ACTIVE' status?

[Assistant] SELECT currency ,  SUM(balance) AS total_balance ,  COUNT(*) AS account_count ,  AVG(CASE WHEN status  =  'ACTIVE' THEN interest_rate ELSE NULL END) AS avg_active_interest_rate FROM financial_services.accounts WHERE opened_date  >=  CURRENT_DATE - INTERVAL '2 year' GROUP BY currency HAVING SUM(balance)  >=  100000

[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

[User] Could you list all pairs of active accounts for the same customer, showing customer_id, account_a, and account_b?

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active';

[User] Please only include account pairs where both balances exceed 1000.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000;

[User] Also, filter to accounts opened after 2022-01-01.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000 AND a.opened_date > '2022-01-01' AND b.opened_date > '2022-01-01';

[User] Finally, order the output by customer_id and account_a.

[Assistant] SELECT a.customer_id, a.account_number AS account_a, b.account_number AS account_b FROM financial_services.accounts a JOIN financial_services.accounts b ON a.customer_id = b.customer_id AND a.account_id < b.account_id WHERE a.status = 'Active' AND b.status = 'Active' AND a.balance > 1000 AND b.balance > 1000 AND a.opened_date > '2022-01-01' AND b.opened_date > '2022-01-01' ORDER BY a.customer_id, a.account_number;

[User] Show the total and average balance for each account_type.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type;

[User] Exclude any account types where the total balance is zero or negative.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 0;

[User] Sort the output by average balance in descending order.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 0 ORDER BY avg_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 transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
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 )
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.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] For each maintenance log, list the vehicle's license plate, the name of the mechanic, and the service date, ordered by most recent service first.

[Assistant]
SELECT ml.log_id, v.license_plate, ml.mechanic_name, ml.service_date
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
ORDER BY ml.service_date DESC;

[User] Show all bookings for trips that are on routes of type 'Shuttle', including the booking ID, passenger's full name, and the route number.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_name, r.route_number
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
WHERE r.type = 'Shuttle';

[User] Add the booking status and fare to the result.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_name, r.route_number, b.status, b.fare
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
WHERE r.type = 'Shuttle';

[User] Only include bookings with status 'Confirmed'.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_name, r.route_number, b.status, b.fare
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
WHERE r.type = 'Shuttle' AND b.status = 'Confirmed';

[User] Order the results by booking_time descending.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_name, r.route_number, b.status, b.fare
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
WHERE r.type = 'Shuttle' AND b.status = 'Confirmed'
ORDER BY b.booking_time DESC;

[User] List all drivers along with the make and model of each vehicle they have been assigned to for trips.

[Assistant]
SELECT DISTINCT d.driver_id, d.first_name || ' ' || d.last_name AS driver_full_name, v.make, v.model
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id;

[User] Show all trips along with the vehicle's make and model, the driver full name, and the route distance in kilometers.

[Assistant]
SELECT t.trip_id, v.make, v.model, d.first_name || ' ' || d.last_name AS driver_full_name, r.distance_km
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.routes r ON t.route_id = r.route_id;

[User] List all fuel refueling events with the refueled vehicle's make and model, the fuel type used, and the fueling location ID.

[Assistant]
SELECT fl.fuel_log_id, fl.log_timestamp, v.make, v.model, fl.fuel_type, fl.quantity, fl.unit, fl.total_cost, fl.location_id
FROM transportation.fuel_logs fl
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_id;

[User] List every maintenance log for each vehicle, including the vehicle's license plate and the mechanic's name.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id;

[User] I want to see only the maintenance logs where the service cost exceeds 500.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500;

[User] Add the odometer reading and sort the results by service date descending.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost, ml.odometer_reading
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500
ORDER BY ml.service_date DESC;

[User] Sorry, actually, I also want to see the recommended next_service_due_date in the output.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost, ml.odometer_reading, ml.next_service_due_date
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500
ORDER BY ml.service_date DESC;


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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