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 character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )

[User] Which cities are listed as primary_address for citizens who have a verified account? Can you show the city names and the number of verified citizens in each city?

[Assistant] SELECT SPLIT_PART(primary_address, ',', 1) AS city, COUNT(*) AS verified_citizen_count FROM government_services.citizens WHERE is_verified = true GROUP BY city;

[User] Actually, could you only include cities with more than 10 verified citizens? And order them by the number of verified citizens in descending order.

[Assistant] SELECT SPLIT_PART(primary_address, ',', 1) AS city, COUNT(*) AS verified_citizen_count FROM government_services.citizens WHERE is_verified = true GROUP BY city HAVING COUNT(*) > 10 ORDER BY verified_citizen_count DESC;

[User] Provide a list of all email addresses used by citizens whose national ID number starts with 'X'.

[Assistant] SELECT contact_email FROM government_services.citizens WHERE national_id_number LIKE 'X%';

[User] Can you list the number of citizens registered each month in 2024? Please show the month and the citizen count.

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] Now, can you also show the number of verified citizens for each month?

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] I see some months with zero verified citizens, but they still show up. Can you exclude months with zero verified citizens from the result?

[Assistant] SELECT registration_month, citizen_count, verified_citizen_count FROM (SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month) sub WHERE verified_citizen_count > 0 ORDER BY registration_month;

[User] List the first name and last name of citizens who have scheduled appointments at accessible service locations, along with the scheduled start time of the appointment and the location name.

[Assistant] SELECT c.first_name, c.last_name, a.scheduled_start_time, sl.location_name FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id JOIN government_services.service_locations AS sl ON a.location_id = sl.location_id WHERE sl.is_accessible = TRUE;

[User] Only include appointments scheduled in the year 2024.

[Assistant] SELECT c.first_name, c.last_name, a.scheduled_start_time, sl.location_name FROM government_services.citizens AS c JOIN government_services.appointments AS a ON c.citizen_id = a.citizen_id JOIN government_services.service_locations AS sl ON a.location_id = sl.location_id WHERE sl.is_accessible = TRUE AND EXTRACT(YEAR FROM a.scheduled_start_time) = 2024;

[User] List pairs of verified citizens who share the same primary address city. Show the city, the full name of the first citizen, and the full name of the second citizen.

[Assistant] SELECT SPLIT_PART(c1.primary_address, ', ', 2) AS city, c1.first_name || ' ' || c1.last_name AS citizen1_full_name, c2.first_name || ' ' || c2.last_name AS citizen2_full_name FROM government_services.citizens AS c1 JOIN government_services.citizens AS c2 ON SPLIT_PART(c1.primary_address, ', ', 2) = SPLIT_PART(c2.primary_address, ', ', 2) AND c1.citizen_id < c2.citizen_id WHERE c1.is_verified = TRUE AND c2.is_verified = TRUE;

[User] List pairs of citizens who share the same gender but registered in different years. Show each citizen’s full name and their registration year.

[Assistant]
SELECT c1.first_name || ' ' || c1.last_name AS name1,
       c2.first_name || ' ' || c2.last_name AS name2,
       EXTRACT(YEAR FROM c1.registration_date) AS year1,
       EXTRACT(YEAR FROM c2.registration_date) AS year2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND c1.citizen_id < c2.citizen_id
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date);

[User] Actually, include only those pairs where both citizens are verified.

[Assistant]
SELECT c1.first_name || ' ' || c1.last_name AS name1,
       c2.first_name || ' ' || c2.last_name AS name2,
       EXTRACT(YEAR FROM c1.registration_date) AS year1,
       EXTRACT(YEAR FROM c2.registration_date) AS year2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND c1.citizen_id < c2.citizen_id
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)
WHERE c1.is_verified = TRUE
  AND c2.is_verified = TRUE;

[User] Provide a count of citizens registered per calendar year.

[Assistant] SELECT CAST(EXTRACT(YEAR FROM registration_date) AS INTEGER) AS registration_year, COUNT(*) AS citizen_count FROM government_services.citizens GROUP BY 1 ORDER BY 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] I want to get the number of servers and the average current players for each game, including the game title.

[Assistant]
SELECT g.title,
       COUNT(s.server_id) AS server_count,
       AVG(s.current_players) AS avg_current_players
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title;

[User] Actually, only include games that have more than 3 servers.

[Assistant]
SELECT g.title,
       COUNT(s.server_id) AS server_count,
       AVG(s.current_players) AS avg_current_players
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
GROUP BY g.title
HAVING COUNT(s.server_id) > 3;

[User] Also show the developer name for each game and only include developers founded after the year 2000.

[Assistant]
SELECT g.title,
       d.name AS developer_name,
       COUNT(s.server_id) AS server_count,
       AVG(s.current_players) AS avg_current_players
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE d.founded_year > 2000
GROUP BY g.title, d.name
HAVING COUNT(s.server_id) > 3;

[User] Finally, sort the results by average current players in descending order.

[Assistant]
SELECT g.title,
       d.name AS developer_name,
       COUNT(s.server_id) AS server_count,
       AVG(s.current_players) AS avg_current_players
FROM gaming_technology.games g
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE d.founded_year > 2000
GROUP BY g.title, d.name
HAVING COUNT(s.server_id) > 3
ORDER BY avg_current_players DESC;

[User] Could you list each game title along with the total number of players currently connected across all its servers?

[Assistant] SELECT g.title, SUM(s.current_players) AS total_current_players FROM gaming_technology.games g JOIN gaming_technology.servers s ON g.game_id = s.game_id GROUP BY g.title;

[User] Show me the items in player inventory for player ID 'abcdefgh-1234-5678-abcd-efghijklmnop'. List the item name and quantity.

[Assistant] SELECT ii.item_name, pi.quantity FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items ii ON pi.item_id = ii.item_id WHERE pi.player_id = 'abcdefgh-1234-5678-abcd-efghijklmnop';

[User] Could you also include the title of the game that each item belongs to?

[Assistant] SELECT g.title, ii.item_name, pi.quantity FROM gaming_technology.player_inventory pi JOIN gaming_technology.in_game_items ii ON pi.item_id = ii.item_id JOIN gaming_technology.games g ON ii.game_id = g.game_id WHERE pi.player_id = 'abcdefgh-1234-5678-abcd-efghijklmnop';

[User] List the usernames and registration dates for all players from 'Canada'.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE country_code = 'Canada';

[User] Now, only show players from Canada who registered after January 1st, 2023.

[Assistant] SELECT username, registration_date FROM gaming_technology.players WHERE country_code = 'Canada' AND registration_date > '2023-01-01';

[User] Which servers are currently 'online' and located in the 'us-west-2' region, and what is the title of the game each server is hosting?

[Assistant]
SELECT s.server_id, s.server_name, s.region, g.title AS game_title
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status = 'online' AND s.region = 'us-west-2';

[User] Can you also include each server's current_players count and the game's genre in the result?

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, g.title AS game_title, g.genre
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status = 'online' AND s.region = 'us-west-2';

[User] List all item names and quantities a player with username 'DragonRider' owns, and include the game titles for those items.

[Assistant]
SELECT i.item_name, pi.quantity, g.title AS game_title
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE p.username = 'DragonRider';

[User] Can you also include the rarity of each item in the output?

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

[User] Please restrict to only items of rarity 'Epic' or 'Legendary'.

[Assistant]
SELECT i.item_name, pi.quantity, i.rarity, g.title AS game_title
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE p.username = 'DragonRider' AND i.rarity IN ('Epic', 'Legendary');

[User] Now, sort the results first by rarity descending, then by quantity descending.

[Assistant]
SELECT i.item_name, pi.quantity, i.rarity, g.title AS game_title
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE p.username = 'DragonRider' AND i.rarity IN ('Epic', 'Legendary')
ORDER BY CASE i.rarity WHEN 'Legendary' THEN 2 WHEN 'Epic' THEN 1 ELSE 0 END DESC, pi.quantity DESC;

[User] Show me all players who have more than 20 items in their inventory.

[Assistant]
SELECT p.player_id, p.username, SUM(pi.quantity) AS total_items
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
GROUP BY p.player_id, p.username
HAVING SUM(pi.quantity) > 20;

[User] Also show the number of unique item types each player has in their inventory.

[Assistant]
SELECT p.player_id, p.username, SUM(pi.quantity) AS total_items, COUNT(DISTINCT i.item_type) AS unique_item_types
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
GROUP BY p.player_id, p.username
HAVING SUM(pi.quantity) > 20;

[User] Can you filter to only show players with at least 3 different item types?

[Assistant]
SELECT p.player_id, p.username, SUM(pi.quantity) AS total_items, COUNT(DISTINCT i.item_type) AS unique_item_types
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
GROUP BY p.player_id, p.username
HAVING SUM(pi.quantity) > 20 AND COUNT(DISTINCT i.item_type) >= 3;

[User] Now sort the results by total_items in descending order.

[Assistant]
SELECT p.player_id, p.username, SUM(pi.quantity) AS total_items, COUNT(DISTINCT i.item_type) AS unique_item_types
FROM gaming_technology.players p
JOIN gaming_technology.player_inventory pi ON p.player_id = pi.player_id
JOIN gaming_technology.in_game_items i ON pi.item_id = i.item_id
GROUP BY p.player_id, p.username
HAVING SUM(pi.quantity) > 20 AND COUNT(DISTINCT i.item_type) >= 3
ORDER BY total_items 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.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
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.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Show all diagnoses recorded by doctor with ID 'doc789'. Include the diagnosis ID, patient ID, description, and diagnosis date.

[Assistant] SELECT diagnosis_id, patient_id, description, diagnosis_date FROM healthcare.diagnoses WHERE doctor_id = 'doc789';

[User] Also include the patient's full name (first and last name) for each of these diagnoses.

[Assistant] SELECT d.diagnosis_id, d.patient_id, p.first_name AS patient_first_name, p.last_name AS patient_last_name, d.description, d.diagnosis_date FROM healthcare.diagnoses d JOIN healthcare.patients p ON d.patient_id = p.patient_id WHERE d.doctor_id = 'doc789';

[User] List all insurance plans, showing their ID, name, provider, and plan type.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans;

[User] Filter the list to only show plans provided by 'BlueCross BlueShield' and with a plan type of 'EPO'.

[Assistant] SELECT plan_id, plan_name, insurance_provider, plan_type FROM healthcare.insurance_plans WHERE insurance_provider = 'BlueCross BlueShield' AND plan_type = 'EPO';

[User] List distinct patient IDs who have received a diagnosis from a doctor with 'Cardiology' specialty.

[Assistant] SELECT DISTINCT T1.patient_id FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id WHERE T2.specialty = 'Cardiology';

[User] For these patients, also show their primary insurance policy number.

[Assistant] SELECT DISTINCT T1.patient_id, T3.policy_number FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id JOIN healthcare.patient_insurance AS T3 ON T1.patient_id = T3.patient_id WHERE T2.specialty = 'Cardiology' AND T3.is_primary = true;

[User] Only include patients whose 'Cardiology' diagnosis was made in the last year.

[Assistant] SELECT DISTINCT T1.patient_id, T3.policy_number FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id JOIN healthcare.patient_insurance AS T3 ON T1.patient_id = T3.patient_id WHERE T2.specialty = 'Cardiology' AND T3.is_primary = true AND T1.diagnosis_date >= date('now', '-1 year');

[User] List the subscriber names from patient insurance entries where the group number is not provided (is null).

[Assistant] SELECT subscriber_name FROM healthcare.patient_insurance WHERE group_number IS NULL;

[User] From that list, only show subscribers whose name starts with 'J'.

[Assistant] SELECT subscriber_name FROM healthcare.patient_insurance WHERE group_number IS NULL AND subscriber_name LIKE 'J%';

[User] I want to see a list of all patients, including their full name and date of birth, along with every doctor they have been diagnosed by and that doctor's specialty.

[Assistant] SELECT p.patient_id, p.first_name || ' ' || p.last_name AS patient_full_name, p.date_of_birth, d.doctor_id, d.first_name || ' ' || d.last_name AS doctor_full_name, d.specialty FROM healthcare.patients p JOIN healthcare.diagnoses dg ON p.patient_id = dg.patient_id JOIN healthcare.doctors d ON dg.doctor_id = d.doctor_id;

[User] Actually, I only want to include diagnoses that have a status of 'Resolved'.

[Assistant] SELECT p.patient_id, p.first_name || ' ' || p.last_name AS patient_full_name, p.date_of_birth, d.doctor_id, d.first_name || ' ' || d.last_name AS doctor_full_name, d.specialty FROM healthcare.patients p JOIN healthcare.diagnoses dg ON p.patient_id = dg.patient_id JOIN healthcare.doctors d ON dg.doctor_id = d.doctor_id WHERE dg.status = 'Resolved';

[User] Could you also include the diagnosis code and the corresponding diagnosis date in the output, and sort results by diagnosis_date descending?

[Assistant] SELECT p.patient_id, p.first_name || ' ' || p.last_name AS patient_full_name, p.date_of_birth, d.doctor_id, d.first_name || ' ' || d.last_name AS doctor_full_name, d.specialty, dg.diagnosis_code, dg.diagnosis_date FROM healthcare.patients p JOIN healthcare.diagnoses dg ON p.patient_id = dg.patient_id JOIN healthcare.doctors d ON dg.doctor_id = d.doctor_id WHERE dg.status = 'Resolved' ORDER BY dg.diagnosis_date DESC;

[User] Show me the first name, last name, and date of birth for all patients who are male.

[Assistant] SELECT first_name, last_name, date_of_birth FROM healthcare.patients WHERE gender = 'Male';

[User] Please also include their phone number, and sort the results by last name in ascending order.

[Assistant] SELECT first_name, last_name, date_of_birth, phone_number FROM healthcare.patients WHERE gender = 'Male' ORDER BY last_name ASC;

[User] List every diagnosis description paired with every insurance plan's website.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2;

[User] Only include chronic diagnoses and plans whose website ends with '.org'.

[Assistant] SELECT T1.description, T2.website FROM healthcare.diagnoses AS T1 CROSS JOIN healthcare.insurance_plans AS T2 WHERE T1.is_chronic = true AND T2.website LIKE '%.org';


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.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)

[User] Count how many tokens exist for each contract_address.

[Assistant]
SELECT contract_address,
       COUNT(*) AS token_count
FROM web3.tokens
GROUP BY contract_address;

[User] Now only include contract_address values that have more than 2 tokens.

[Assistant]
SELECT contract_address,
       COUNT(*) AS token_count
FROM web3.tokens
GROUP BY contract_address
HAVING COUNT(*) > 2;

[User] Show the distribution of total supply for tokens, grouped into ranges like < 1 million, 1 million to 1 billion, and > 1 billion. Count how many tokens fall into each range.

[Assistant] SELECT CASE WHEN total_supply < 1000000 THEN '< 1 million' WHEN total_supply >= 1000000 AND total_supply <= 1000000000 THEN '1 million to 1 billion' WHEN total_supply > 1000000000 THEN '> 1 billion' ELSE 'Other' END AS supply_range, COUNT(*) AS token_count FROM web3.tokens GROUP BY supply_range ORDER BY CASE WHEN supply_range = '< 1 million' THEN 1 WHEN supply_range = '1 million to 1 billion' THEN 2 WHEN supply_range = '> 1 billion' THEN 3 ELSE 4 END;

[User] Instead of the count, can you show the average total supply for tokens in each range?

[Assistant] SELECT CASE WHEN total_supply < 1000000 THEN '< 1 million' WHEN total_supply >= 1000000 AND total_supply <= 1000000000 THEN '1 million to 1 billion' WHEN total_supply > 1000000000 THEN '> 1 billion' ELSE 'Other' END AS supply_range, AVG(total_supply) AS average_total_supply FROM web3.tokens GROUP BY supply_range ORDER BY CASE WHEN supply_range = '< 1 million' THEN 1 WHEN supply_range = '1 million to 1 billion' THEN 2 WHEN supply_range = '> 1 billion' THEN 3 ELSE 4 END;

[User] Find all pairs of tokens that have the same token name but different contract addresses, showing both token IDs, the shared token name, and each contract address.

[Assistant]
SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.token_name, t1.contract_address AS contract_address_1, t2.contract_address AS contract_address_2
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.token_name = t2.token_name
  AND t1.contract_address <> t2.contract_address
  AND t1.token_id < t2.token_id;

[User] For each token, show its token_id, decimals, and the average total_supply of all tokens with the same decimals.

[Assistant]
SELECT t.token_id,
       t.decimals,
       avg_data.avg_total_supply
FROM web3.tokens t
JOIN (
  SELECT decimals,
         AVG(total_supply) AS avg_total_supply
  FROM web3.tokens
  GROUP BY decimals
) AS avg_data
  ON t.decimals = avg_data.decimals;

[User] List all pairs of tokens that are deployed on the same contract address and have the same number of decimals. Show both token IDs, the shared contract_address, and the decimals value.

[Assistant]
SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.contract_address, t1.decimals
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.contract_address = t2.contract_address
  AND t1.decimals = t2.decimals
  AND t1.token_id < t2.token_id;

[User] Show all token symbols along with the names of any other tokens on the same contract address.

[Assistant]
SELECT t1.token_symbol, t2.token_name AS other_token_name, t1.contract_address
FROM web3.tokens t1
JOIN web3.tokens t2
  ON t1.contract_address = t2.contract_address
  AND t1.token_id <> t2.token_id;

[User] List the token symbol and name for all tokens whose associated contract address has emitted at least one event. Also include the contract address.

[Assistant] SELECT T.token_symbol, T.token_name, T.contract_address FROM web3.tokens AS T JOIN contracts AS C ON T.contract_address = C.address JOIN events AS E ON C.contract_id = E.contract_id GROUP BY T.token_symbol, T.token_name, T.contract_address;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the full name of employees and the names of the agencies they work for, but only for employees who are currently employed.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS employee_full_name, a.agency_name
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
WHERE e.termination_date IS NULL;

[User] Show the payment ID, amount, and payment method for all payments made in USD with an amount greater than 50.

[Assistant]
SELECT payment_id, amount, payment_method
FROM government_services.payments
WHERE currency = 'USD' AND amount > 50;

[User] For each service, show the service name and the total number of applications submitted for it.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS total_applications
FROM government_services.services s
LEFT JOIN government_services.applications a ON s.service_id = a.service_id
GROUP BY s.service_name;

[User] Which agencies have at least one service with a standard fee equal to zero? Show the agency name and the service name.

[Assistant]
SELECT a.agency_name, s.service_name
FROM government_services.agencies a
JOIN government_services.services s ON a.agency_id = s.agency_id
WHERE s.standard_fee = 0;

[User] List all job titles of employees who work in the 'Finance' department.

[Assistant]
SELECT DISTINCT job_title
FROM government_services.employees
WHERE department = 'Finance';

[User] Get the name of each agency and the count of accessible service locations it operates in. Only include agencies that have more than two accessible locations.

[Assistant]
SELECT a.agency_name, COUNT(sl.location_id) AS accessible_locations
FROM government_services.agencies a
JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.is_accessible = TRUE
GROUP BY a.agency_name
HAVING COUNT(sl.location_id) > 2;

[User] Modify the query so that it counts distinct cities instead of locations.

[Assistant]
SELECT a.agency_name, COUNT(DISTINCT sl.city) AS accessible_cities
FROM government_services.agencies a
JOIN government_services.service_locations sl ON a.agency_id = sl.agency_id
WHERE sl.is_accessible = TRUE
GROUP BY a.agency_name
HAVING COUNT(DISTINCT sl.city) > 2;

[User] For each application that has pending documents, list the application's reference_number and the corresponding service_name. Only include documents with verification_status = 'Pending'.

[Assistant]
SELECT DISTINCT a.reference_number, s.service_name
FROM government_services.applications a
JOIN government_services.documents d ON a.application_id = d.application_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE d.verification_status = 'Pending';


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.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
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 )
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

[User] Show me for each loan_type, the total number of loans and the average principal_amount, along with the average account balance for the accounts associated with those loans.

[Assistant]
SELECT l.loan_type, COUNT(l.loan_id) AS loan_count, AVG(l.principal_amount) AS avg_principal_amount, AVG(a.balance) AS avg_account_balance
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY l.loan_type;

[User] Can you only include loan types with more than 3 loans?

[Assistant]
SELECT l.loan_type, COUNT(l.loan_id) AS loan_count, AVG(l.principal_amount) AS avg_principal_amount, AVG(a.balance) AS avg_account_balance
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY l.loan_type
HAVING COUNT(l.loan_id) > 3;

[User] And sort the result by avg_principal_amount in descending order.

[Assistant]
SELECT l.loan_type, COUNT(l.loan_id) AS loan_count, AVG(l.principal_amount) AS avg_principal_amount, AVG(a.balance) AS avg_account_balance
FROM financial_services.loans l
JOIN financial_services.accounts a ON l.account_id = a.account_id
GROUP BY l.loan_type
HAVING COUNT(l.loan_id) > 3
ORDER BY avg_principal_amount DESC;

[User] Show me the average high price and average low price for each security sector using market data.

[Assistant] SELECT T1.sector, AVG(T2.high_price) AS average_high_price, AVG(T2.low_price) AS average_low_price FROM financial_services.securities AS T1 JOIN financial_services.market_data AS T2 ON T1.security_id = T2.security_id WHERE T1.sector IS NOT NULL GROUP BY T1.sector

[User] Restrict the data to market data points from 2023.

[Assistant] SELECT T1.sector, AVG(T2.high_price) AS average_high_price, AVG(T2.low_price) AS average_low_price FROM financial_services.securities AS T1 JOIN financial_services.market_data AS T2 ON T1.security_id = T2.security_id WHERE T1.sector IS NOT NULL AND EXTRACT(YEAR FROM T2.data_timestamp) = 2023 GROUP BY T1.sector

[User] Show me the total number of customers and their average age grouped by city.

[Assistant] SELECT city, COUNT(customer_id) AS total_customers, AVG(EXTRACT(YEAR FROM NOW()) - EXTRACT(YEAR FROM date_of_birth)) AS average_age FROM financial_services.customers WHERE city IS NOT NULL GROUP BY city

[User] Only include customers with status 'Active'.

[Assistant] SELECT city, COUNT(customer_id) AS total_customers, AVG(EXTRACT(YEAR FROM NOW()) - EXTRACT(YEAR FROM date_of_birth)) AS average_age FROM financial_services.customers WHERE city IS NOT NULL AND status = 'Active' GROUP BY city

[User] List all trades for a given security, showing ticker_symbol, trade_id, account_id, trade_type, and total_amount.

[Assistant]
SELECT s.ticker_symbol, t.trade_id, t.account_id, t.trade_type, t.total_amount
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id;

[User] Only include trades executed on the 'NASDAQ' exchange.

[Assistant]
SELECT s.ticker_symbol, t.trade_id, t.account_id, t.trade_type, t.total_amount
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE s.exchange = 'NASDAQ';

[User] Also, filter to only show trades with total_amount above 2000.

[Assistant]
SELECT s.ticker_symbol, t.trade_id, t.account_id, t.trade_type, t.total_amount
FROM financial_services.trades t
JOIN financial_services.securities s ON t.security_id = s.security_id
WHERE s.exchange = 'NASDAQ' AND t.total_amount > 2000;

[User] Can you show me, for each account type, the total transaction amount and the number of transactions, including the customer full name for each account type?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
GROUP BY a.account_type, customer_name;

[User] Actually, could you only include accounts where the balance is greater than 5000?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE a.balance > 5000
GROUP BY a.account_type, customer_name;

[User] Can you also filter transactions to only include those with status 'SUCCESSFUL'?

[Assistant]
SELECT a.account_type, c.first_name || ' ' || c.last_name AS customer_name, SUM(t.amount) AS total_transaction_amount, COUNT(t.transaction_id) AS transaction_count
FROM financial_services.accounts a
JOIN financial_services.customers c ON a.customer_id = c.customer_id
JOIN financial_services.transactions t ON a.account_id = t.account_id
WHERE a.balance > 5000 AND t.status = 'SUCCESSFUL'
GROUP BY a.account_type, customer_name;

[User] List all employees and the branch they work at, along with their job title and department.

[Assistant]
SELECT employee_id, first_name || ' ' || last_name AS full_name, job_title, department, branch_id
FROM financial_services.employees;

[User] Add the full name of each employee's manager to the result. If there is no manager, show NULL.

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS full_name, e.job_title, e.department, e.branch_id, m.first_name || ' ' || m.last_name AS manager_full_name
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Only include employees who are currently active, and sort the list by department, then by full_name.

[Assistant]
SELECT e.employee_id, e.first_name || ' ' || e.last_name AS full_name, e.job_title, e.department, e.branch_id, m.first_name || ' ' || m.last_name AS manager_full_name
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.status = 'Active'
ORDER BY e.department, full_name;

[User] For each customer, could you list their full name, email, and the combined balance of all their accounts? Please also show the number of accounts they hold.

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, c.email, SUM(a.balance) AS total_balance, COUNT(a.account_id) AS account_count
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name, c.email;

[User] Thanks! Now, can you show only customers with at least two accounts in different currencies, and display the number of distinct currencies as well?

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, c.email, SUM(a.balance) AS total_balance, COUNT(a.account_id) AS account_count, COUNT(DISTINCT a.currency) AS currency_count
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name, c.email
HAVING COUNT(a.account_id) >= 2 AND COUNT(DISTINCT a.currency) >= 2;

[User] Could you also filter to only include customers whose total combined account balance is over 10,000 and show their risk_profile?

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, c.email, SUM(a.balance) AS total_balance, COUNT(a.account_id) AS account_count, COUNT(DISTINCT a.currency) AS currency_count, c.risk_profile
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name, c.email, c.risk_profile
HAVING COUNT(a.account_id) >= 2 AND COUNT(DISTINCT a.currency) >= 2 AND SUM(a.balance) > 10000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )

[User] Show me the top 5 projects by valuation that completed fundraising rounds in the last 3 months, along with their narrative information if available.

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY pfr.valuation DESC LIMIT 5;

[User] Can you also include the 24-hour trading volume for these projects' narratives and filter to only include projects with valuation over $50 million?

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank, ni.volume_24h FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND pfr.valuation > 50000000 ORDER BY pfr.valuation DESC LIMIT 5;

[User] Which projects that raised funds in 2023 have an associated token, and what are their fundraising amounts, token symbols, and token market caps?

[Assistant] SELECT T1.project_name, T1.investment_value, T2.token_symbol, T2.market_cap FROM project_fundraising_record AS T1 LEFT JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE T1.investment_date LIKE '%2023%' AND T2.token_symbol IS NOT NULL

[User] Instead of just 2023, show projects that raised funds in 2022 or 2023.

[Assistant] SELECT T1.project_name, T1.investment_value, T2.token_symbol, T2.market_cap FROM project_fundraising_record AS T1 LEFT JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE (T1.investment_date LIKE '%2022%' OR T1.investment_date LIKE '%2023%') AND T2.token_symbol IS NOT NULL

[User] Also include the fundraising round name and the token's 24-hour volume.

[Assistant] SELECT T1.project_name, T1.rounds_name, T1.investment_value, T2.token_symbol, T2.market_cap, T2.total_volume FROM project_fundraising_record AS T1 LEFT JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE (T1.investment_date LIKE '%2022%' OR T1.investment_date LIKE '%2023%') AND T2.token_symbol IS NOT NULL

[User] Filter the results to only show projects where the token's market cap is above $50,000,000.

[Assistant] SELECT T1.project_name, T1.rounds_name, T1.investment_value, T2.token_symbol, T2.market_cap, T2.total_volume FROM project_fundraising_record AS T1 INNER JOIN token_basic_info AS T2 ON T1.project_name = T2.token_name WHERE (T1.investment_date LIKE '%2022%' OR T1.investment_date LIKE '%2023%') AND T2.market_cap > 50000000

[User] Which tokens have a current price above $20 and belong to the 'DeFi' narrative?

[Assistant]
SELECT token_symbol, token_name, chain, price
FROM token_basic_info
WHERE price > 20 AND narrative = 'DeFi';

[User] Add only those with a market cap above $500 million and order by market cap descending.

[Assistant]
SELECT token_symbol, token_name, chain, price, market_cap
FROM token_basic_info
WHERE price > 20
  AND narrative = 'DeFi'
  AND market_cap > 500000000
ORDER BY market_cap DESC;

[User] Could you list projects that have completed more than one fundraising round, showing the project name and the number of rounds?

[Assistant] SELECT project_name, COUNT(*) AS round_count FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 ORDER BY round_count DESC;

[User] For these projects with multiple rounds, can you show the earliest and latest investment date and the corresponding investment value for each project?

[Assistant] WITH ProjectRounds AS ( SELECT project_id, project_name, investment_value, investment_date, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date ASC) as rn_earliest, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date DESC) as rn_latest FROM project_fundraising_record ) SELECT pr_earliest.project_name, pr_earliest.investment_date AS earliest_date, pr_earliest.investment_value AS earliest_investment, pr_latest.investment_date AS latest_date, pr_latest.investment_value AS latest_investment FROM ProjectRounds pr_earliest JOIN ProjectRounds pr_latest ON pr_earliest.project_id = pr_latest.project_id WHERE pr_earliest.rn_earliest = 1 AND pr_latest.rn_latest = 1 AND pr_earliest.project_id IN ( SELECT project_id FROM project_fundraising_record GROUP BY project_id HAVING COUNT(*) > 1 ) ORDER BY pr_latest.investment_date DESC;

[User] Now, for those projects that also have a matching token, link the latest investment value to the token's current price and its smart money ROI. Match project name to token symbol or name case-insensitively.

[Assistant] WITH ProjectLatestRound AS ( SELECT project_id, project_name, investment_value, investment_date, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date DESC) as rn FROM project_fundraising_record WHERE project_id IN ( SELECT project_id FROM project_fundraising_record GROUP BY project_id HAVING COUNT(*) > 1 ) ) SELECT plr.project_name, plr.investment_value AS latest_investment, tbi.token_symbol, tbi.price AS current_token_price, smp.roi AS smart_money_roi FROM ProjectLatestRound plr JOIN token_basic_info tbi ON LOWER(tbi.token_symbol) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_symbol) || '%' OR LOWER(tbi.token_name) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_name) || '%' LEFT JOIN smart_money_token_performance smp ON tbi.token_symbol = smp.token_symbol WHERE plr.rn = 1;

[User] Filter the results to only include projects where the latest investment value is greater than $1,000,000 AND the token's smart money ROI is positive (greater than 0). Order the results by smart money ROI descending and show the top 10.

[Assistant] WITH ProjectLatestRound AS ( SELECT project_id, project_name, investment_value, investment_date, ROW_NUMBER() OVER(PARTITION BY project_id ORDER BY investment_date DESC) as rn FROM project_fundraising_record WHERE project_id IN ( SELECT project_id FROM project_fundraising_record GROUP BY project_id HAVING COUNT(*) > 1 ) ) SELECT plr.project_name, plr.investment_value AS latest_investment, tbi.token_symbol, tbi.price AS current_token_price, smp.roi AS smart_money_roi FROM ProjectLatestRound plr JOIN token_basic_info tbi ON LOWER(tbi.token_symbol) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_symbol) || '%' OR LOWER(tbi.token_name) LIKE '%' || LOWER(plr.project_name) || '%' OR LOWER(plr.project_name) LIKE '%' || LOWER(tbi.token_name) || '%' JOIN smart_money_token_performance smp ON tbi.token_symbol = smp.token_symbol WHERE plr.rn = 1 AND plr.investment_value > 1000000 AND smp.roi > 0 ORDER BY smp.roi DESC LIMIT 10;

[User] Show me the average smart money ROI and the total PNL for each narrative category, based on the `smart_money_token_performance` and `token_basic_info` tables.

[Assistant] SELECT tbi.narrative, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol GROUP BY tbi.narrative ORDER BY average_roi DESC;

[User] Filter the results to only include narratives with an average ROI greater than 1 (100%) and a total PNL greater than 0. Order by total PNL descending.

[Assistant] SELECT tbi.narrative, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol GROUP BY tbi.narrative HAVING AVG(smp.roi) > 1 AND SUM(smp.pnl) > 0 ORDER BY total_pnl DESC;

[User] Break down these results by chain as well. Show narrative, chain, average ROI, and total PNL for narratives with average ROI > 1 and total PNL > 0 on each chain.

[Assistant] SELECT tbi.narrative, smp.chain, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol AND smp.chain = tbi.chain GROUP BY tbi.narrative, smp.chain HAVING AVG(smp.roi) > 1 AND SUM(smp.pnl) > 0 ORDER BY total_pnl DESC;

[User] Now, only show results where the total PNL is greater than $50,000 AND the number of unique tokens contributing to this PNL for that narrative and chain is at least 3. Include the count of unique tokens. Order by total PNL descending and limit to the top 10.

[Assistant] SELECT tbi.narrative, smp.chain, AVG(smp.roi) AS average_roi, SUM(smp.pnl) AS total_pnl, COUNT(DISTINCT smp.token_symbol) AS unique_token_count FROM smart_money_token_performance smp JOIN token_basic_info tbi ON smp.token_symbol = tbi.token_symbol AND smp.chain = tbi.chain GROUP BY tbi.narrative, smp.chain HAVING AVG(smp.roi) > 1 AND SUM(smp.pnl) > 50000 AND COUNT(DISTINCT smp.token_symbol) >= 3 ORDER BY total_pnl DESC LIMIT 10;

[User] List tokens in DEX pools with a 24-hour trading volume greater than $500,000 and a price less than $1. Show their symbol, chain, volume, and price.

[Assistant] SELECT token_symbol, chain, volume_24h, price FROM token_dexpool_info WHERE volume_24h > 500000 AND price < 1

[User] Which fundraising projects in 2023 have an associated token, and what are their investment amounts, chain, and token narratives?

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023%';

[User] Could you also include the token's symbol and current price in the results?

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative, t.token_symbol, t.price
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
WHERE p.investment_date LIKE '2023%';

[User] Some matches may be missed. Can you use a more flexible join, such as where the token name contains the project name or vice versa (case-insensitive)?

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative, t.token_symbol, t.price
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
     OR LOWER(p.project_name) LIKE CONCAT('%', LOWER(t.token_name), '%')
     OR LOWER(t.token_name) LIKE CONCAT('%', LOWER(p.project_name), '%')
WHERE p.investment_date LIKE '2023%';

[User] Add a filter to only include projects where the investment amount is greater than $2,000,000, and order by investment_value descending.

[Assistant]
SELECT p.project_name, p.investment_value, t.chain, t.narrative, t.token_symbol, t.price
FROM project_fundraising_record p
JOIN token_basic_info t
  ON LOWER(p.project_name) = LOWER(t.token_name)
     OR LOWER(p.project_name) LIKE CONCAT('%', LOWER(t.token_name), '%')
     OR LOWER(t.token_name) LIKE CONCAT('%', LOWER(p.project_name), '%')
WHERE p.investment_date LIKE '2023%'
  AND p.investment_value > 2000000
ORDER BY p.investment_value DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )

[User] Find documents that have the same document_name but are associated with different cases. Show the document name and the two different case IDs.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id;

[User] Actually, only show pairs where at least one of the documents is of document_type 'Contract'.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract');

[User] Also, only include pairs where both documents were uploaded in the year 2024.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract') AND YEAR(d1.upload_timestamp) = 2024 AND YEAR(d2.upload_timestamp) = 2024;

[User] List document names, types, and upload timestamps for documents uploaded after '2024-01-01'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01'

[User] Filter the results to only include documents of type 'Contract'.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract'

[User] Only show documents with version 3.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' AND version  =  3

[User] Remove the version filter, add the document description, and order by upload timestamp.

[Assistant] SELECT document_name ,  document_type ,  upload_timestamp ,  description FROM legal_services.documents WHERE upload_timestamp  >  '2024-01-01' AND document_type  =  'Contract' ORDER BY upload_timestamp

[User] List the document name, upload timestamp, and the full name of the lawyer who uploaded it, for all documents associated with case number 'CASE123'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123'

[User] Only include documents of type 'Pleading'.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading'

[User] Also show the version and restrict results to documents with version greater than 1.

[Assistant] SELECT T1.document_name ,  T1.upload_timestamp ,  T1.version ,  T2.full_name FROM legal_services.documents AS T1 JOIN legal_services.lawyers AS T2 ON T1.uploaded_by_lawyer_id  =  T2.lawyer_id WHERE T1.case_id  =  'CASE123' AND T1.document_type  =  'Pleading' AND T1.version  >  1

[User] Find pairs of documents within the same case that were uploaded on the same day but by different lawyers. Show the case_id, upload_date, document_id and uploader_id for both documents in the pair.

[Assistant] SELECT d1.case_id, DATE(d1.upload_timestamp) AS upload_date, d1.document_id AS document1_id, d1.uploaded_by_lawyer_id AS lawyer1_id, d2.document_id AS document2_id, d2.uploaded_by_lawyer_id AS lawyer2_id FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.case_id = d2.case_id AND DATE(d1.upload_timestamp) = DATE(d2.upload_timestamp) AND d1.uploaded_by_lawyer_id <> d2.uploaded_by_lawyer_id WHERE d1.document_id < d2.document_id;

[User] List the case number, case name, and the full name of the client for cases that have uploaded documents.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] Also include the full name of the lead lawyer for these cases.

[Assistant] SELECT T1.case_number ,  T1.case_name ,  T2.full_name AS client_name ,  T4.full_name AS lawyer_name FROM legal_services.cases AS T1 JOIN legal_services.clients AS T2 ON T1.client_id  =  T2.client_id JOIN legal_services.lawyers AS T4 ON T1.lead_lawyer_id  =  T4.lawyer_id WHERE EXISTS ( SELECT 1 FROM legal_services.documents AS T3 WHERE T3.case_id  =  T1.case_id )

[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Find pairs of documents in the same case where one document is of type 'Contract' and the other is of type 'Evidence'. Return the case_id, the contract document_name as contract_name, and the evidence document_name as evidence_name.

[Assistant]
SELECT c.case_id,
       c.document_name AS contract_name,
       e.document_name AS evidence_name
FROM legal_services.documents c
JOIN legal_services.documents e
  ON c.case_id = e.case_id
WHERE c.document_type = 'Contract'
  AND e.document_type = 'Evidence';


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 character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] For each passenger, compute the count of bookings and average fare for bookings made in February 2024.

[Assistant]
SELECT p.passenger_id, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.passenger_id;

[User] I need to see the passengers' first and last names instead of IDs and only include those with an average fare greater than 75.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75;

[User] Also, order the results by booking_count descending and limit the output to the top 5 passengers.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75
ORDER BY booking_count DESC
LIMIT 5;

[User] Retrieve the first and last names of passengers along with the total sum of fares they've paid for bookings with status 'Completed', ordered by the sum descending.

[Assistant]
SELECT p.first_name, p.last_name, SUM(b.fare) AS total_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.first_name, p.last_name
ORDER BY total_fare DESC;

[User] Now, modify the query to include only those passengers who have made more than three completed bookings.

[Assistant]
SELECT p.first_name, p.last_name, SUM(b.fare) AS total_fare, COUNT(b.booking_id) AS booking_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 3
ORDER BY total_fare DESC;

[User] List all bookings, including the passenger ID, booking ID, booking time, and the name of the origin and destination locations for the trip.

[Assistant] SELECT b.passenger_id, b.booking_id, b.booking_time, o.name AS origin_location_name, d.name AS destination_location_name FROM transportation.bookings b JOIN transportation.trips t ON b.trip_id = t.trip_id JOIN transportation.locations o ON t.origin_location_id = o.location_id JOIN transportation.locations d ON t.destination_location_id = d.location_id;

[User] List all drivers.

[Assistant] SELECT driver_id, first_name, last_name FROM transportation.drivers;

[User] Can you also include their hire date and status?

[Assistant] SELECT driver_id, first_name, last_name, hire_date, status FROM transportation.drivers;

[User] Show only drivers hired after 2020-01-01.

[Assistant] SELECT driver_id, first_name, last_name, hire_date, status FROM transportation.drivers WHERE hire_date > '2020-01-01';

[User] Order them by hire date descending and limit to 10.

[Assistant] SELECT driver_id, first_name, last_name, hire_date, status FROM transportation.drivers WHERE hire_date > '2020-01-01' ORDER BY hire_date DESC LIMIT 10;

[User] List all trips including the name of the origin location and the name of the destination location.

[Assistant] SELECT t.trip_id, origin.name AS origin_location_name, destination.name AS destination_location_name FROM transportation.trips t JOIN transportation.locations origin ON t.origin_location_id = origin.location_id JOIN transportation.locations destination ON t.destination_location_id = destination.location_id;

[User] Show me all diesel vehicles with a capacity greater than 20, including their make, model, and year.

[Assistant] SELECT vehicle_id, make, model, year, capacity FROM transportation.vehicles WHERE fuel_type = 'diesel' AND capacity > 20;

[User] Now join this with the drivers table to show which drivers are assigned to these vehicles (assuming driver_id is stored in vehicles table).

[Assistant] SELECT v.vehicle_id, v.make, v.model, v.year, v.capacity, d.driver_id, d.first_name, d.last_name FROM transportation.vehicles v JOIN transportation.drivers d ON v.driver_id = d.driver_id WHERE v.fuel_type = 'diesel' AND v.capacity > 20;

[User] Actually, I need to see only active drivers and order the results by vehicle year in descending order.

[Assistant] SELECT v.vehicle_id, v.make, v.model, v.year, v.capacity, d.driver_id, d.first_name, d.last_name FROM transportation.vehicles v JOIN transportation.drivers d ON v.driver_id = d.driver_id WHERE v.fuel_type = 'diesel' AND v.capacity > 20 AND d.status = 'active' ORDER BY v.year DESC;

[User] List all maintenance logs for vehicles that are currently active, showing the vehicle ID and service type.

[Assistant] SELECT m.vehicle_id, m.service_type FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active';

[User] I also need to see the service date and cost for these logs, but only for services performed in the last 6 months.

[Assistant] SELECT m.vehicle_id, m.service_type, m.service_date, m.cost FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active' AND m.service_date >= CURRENT_DATE - INTERVAL '6 months';

[User] Can you filter this to only show 'Oil Change' services that cost more than $100?

[Assistant] SELECT m.vehicle_id, m.service_type, m.service_date, m.cost FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active' AND m.service_date >= CURRENT_DATE - INTERVAL '6 months' AND m.service_type = 'Oil Change' AND m.cost > 100;

[User] Actually, I need to see the vehicle make and model as well, and order the results by service date with the most recent first.

[Assistant] SELECT m.vehicle_id, v.make, v.model, m.service_type, m.service_date, m.cost FROM transportation.maintenance_logs m JOIN transportation.vehicles v ON m.vehicle_id = v.vehicle_id WHERE v.status = 'Active' AND m.service_date >= CURRENT_DATE - INTERVAL '6 months' AND m.service_type = 'Oil Change' AND m.cost > 100 ORDER BY m.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 narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
  "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] List the top 5 exchanges with the highest total USD value of tokens held on the 'Ethereum' chain for the latest snapshot time.

[Assistant] SELECT exchange, SUM(usd_value) AS TotalUSDValue FROM cex_token_balance WHERE chain = 'Ethereum' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance WHERE chain = 'Ethereum') GROUP BY exchange ORDER BY TotalUSDValue DESC LIMIT 5

[User] Could you also show the number of distinct tokens held by each of these top exchanges?

[Assistant] SELECT exchange, SUM(usd_value) AS TotalUSDValue, COUNT(DISTINCT token_symbol) AS DistinctTokenCount FROM cex_token_balance WHERE chain = 'Ethereum' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance WHERE chain = 'Ethereum') GROUP BY exchange ORDER BY TotalUSDValue DESC LIMIT 5

[User] For narratives listed in `narrative_info`, find the total USD value held by CEXes for tokens that are among their top 3 listed coins. Show the narrative and the total CEX USD value.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative

[User] Could you also include the number of distinct tokens contributing to this value for each narrative?

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, COUNT(DISTINCT T1.token_symbol) AS DistinctTokenCount FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative

[User] Now, only show narratives where the total CEX USD value is greater than $100,000.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, COUNT(DISTINCT T1.token_symbol) AS DistinctTokenCount FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative HAVING SUM(T1.usd_value) > 100000

[User] Order the results by total CEX USD value in descending order and show the top 5 narratives.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, COUNT(DISTINCT T1.token_symbol) AS DistinctTokenCount FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' GROUP BY T2.narrative HAVING SUM(T1.usd_value) > 100000 ORDER BY TotalCexUSDValue DESC LIMIT 5

[User] For the 'AI' and 'Gaming' narratives, what is the total USD value held by CEXes for tokens listed in their top 3 coins?

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') GROUP BY T2.narrative

[User] Also show the average price of these tokens in CEX holdings for each narrative.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, AVG(T1.price) AS AverageTokenPrice FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') GROUP BY T2.narrative

[User] Can you filter the results to only include tokens where the USD value in the CEX holding record is greater than $1000?

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, AVG(T1.price) AS AverageTokenPrice FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') AND T1.usd_value > 1000 GROUP BY T2.narrative

[User] Order the results by total USD value descending and show both narratives.

[Assistant] SELECT T2.narrative, SUM(T1.usd_value) AS TotalCexUSDValue, AVG(T1.price) AS AverageTokenPrice FROM cex_token_balance AS T1 JOIN narrative_info AS T2 ON T2.top_3_coins LIKE '%' || T1.token_symbol || '%' WHERE T2.narrative IN ('AI', 'Gaming') AND T1.usd_value > 1000 GROUP BY T2.narrative ORDER BY TotalCexUSDValue DESC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)

[User] Show me a list of all partners who were hired in 2021.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31';

[User] Include their professional email addresses as well.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       email,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31';

[User] Exclude any partners who haven't provided a phone number.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       email,
       phone,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31'
  AND phone IS NOT NULL;

[User] Finally, order the result by hire_date in descending order.

[Assistant]
SELECT lawyer_id,
       first_name,
       last_name,
       email,
       phone,
       hire_date
FROM legal_services.lawyers
WHERE is_partner = true
  AND hire_date BETWEEN '2021-01-01' AND '2021-12-31'
  AND phone IS NOT NULL
ORDER BY hire_date DESC;

[User] Show me the names of law firms founded after 2010, along with the full name of their managing partner.

[Assistant] SELECT f.firm_name, l.first_name, l.last_name FROM legal_services.law_firms AS f JOIN legal_services.lawyers AS l ON f.managing_partner_id = l.lawyer_id WHERE f.founded_date > '2010-12-31';

[User] List the first name, last name, email, and the name of the law firm for all lawyers.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T1.email ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id  =  T2.firm_id

[User] List the first name, last name, specialization, and the name of the law firm for all lawyers hired before January 1, 2020.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T1.specialization ,  T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id  =  T2.firm_id WHERE T1.hire_date < '2020-01-01'

[User] List each lawyer's full name with the full name of the partner at the same firm.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true;

[User] Actually, I only want those lawyers whose specialization includes 'Corporate Law'. Could you update the query?

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%';

[User] Also only show those who were hired after 2020-01-01.

[Assistant]
SELECT l.lawyer_id,
       CONCAT(l.first_name, ' ', l.last_name) AS lawyer_name,
       CONCAT(p.first_name, ' ', p.last_name) AS partner_name
FROM legal_services.lawyers l
JOIN legal_services.lawyers p
  ON l.firm_id = p.firm_id
 AND p.is_partner = true
WHERE l.specialization ILIKE '%Corporate Law%'
  AND l.hire_date > '2020-01-01';

[User] List all partners who have provided a phone number, showing their full name and email.

[Assistant] SELECT first_name, last_name, email FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL;

[User] Okay, now only include those partners hired between 2020-01-01 and 2022-12-31.

[Assistant] SELECT first_name, last_name, email FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31';

[User] Can you also add their specialization to the output?

[Assistant] SELECT first_name, last_name, email, specialization FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31';

[User] Finally, order the results by specialization in ascending order, then by last name.

[Assistant] SELECT first_name, last_name, email, specialization FROM legal_services.lawyers WHERE is_partner = TRUE AND phone IS NOT NULL AND hire_date BETWEEN '2020-01-01' AND '2022-12-31' ORDER BY specialization ASC, last_name ASC;

[User] How many lawyers who are partners were hired in each year? Show the hire year and the count.

[Assistant] SELECT strftime('%Y', hire_date) AS hire_year ,  count(lawyer_id) FROM legal_services.lawyers WHERE is_partner  =  true GROUP BY hire_year


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.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )

[User] Count the number of transactions for each status.

[Assistant]
SELECT status, COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY status;

[User] Actually, only include statuses with more than 1000 transactions.

[Assistant]
SELECT status, COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY status
HAVING COUNT(*) > 1000;

[User] For each transaction, find the next transaction initiated by the same sender. List the original transaction_id, the next transaction_id, the sender address, and the time difference in hours between them.

[Assistant]
SELECT t1.transaction_id AS original_tx,
       t2.transaction_id AS next_tx,
       t1.from_address,
       EXTRACT(EPOCH FROM (t2.timestamp - t1.timestamp)) / 3600 AS hours_diff
FROM transactions t1
JOIN transactions t2
  ON t1.from_address = t2.from_address
 AND t2.timestamp = (
       SELECT MIN(timestamp)
       FROM transactions t3
       WHERE t3.from_address = t1.from_address
         AND t3.timestamp > t1.timestamp
   );

[User] List all failed transactions where the gas_used is greater than 100,000, including the transaction_id and timestamp.

[Assistant] SELECT transaction_id, timestamp FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000;

[User] Actually, I also need to see the from_address and the value of these transactions.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000;

[User] There's a typo in your SQL, it should be '100000' not '100,000'. Also, sort the results by timestamp in descending order.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 ORDER BY timestamp DESC;

[User] Now filter to only show transactions from the last 30 days.

[Assistant] SELECT transaction_id, timestamp, from_address, value FROM web3.transactions WHERE status = 'failed' AND gas_used > 100000 AND timestamp >= NOW() - INTERVAL '30 days' ORDER BY timestamp DESC;

[User] For each transaction, find the next transaction by the same sender. Show the original transaction_id as current_tx, the next transaction_id as next_tx, from_address, and the time difference in minutes between them.

[Assistant]
SELECT t1.transaction_id AS current_tx,
       t2.transaction_id AS next_tx,
       t1.from_address,
       EXTRACT(EPOCH FROM (t2.timestamp - t1.timestamp)) / 60 AS diff_minutes
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
  AND t2.timestamp = (
    SELECT MIN(t3.timestamp)
    FROM web3.transactions t3
    WHERE t3.from_address = t1.from_address
      AND t3.timestamp > t1.timestamp
  );

[User] List all pairs of transactions within the same block where the from_address of one transaction is the to_address of another transaction. Show both transaction_ids, the block_number, from_address, and to_address.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.block_number, t1.from_address, t1.to_address
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.block_number = t2.block_number
  AND t1.from_address = t2.to_address
  AND t1.to_address = t2.from_address;

[User] Show all transactions where the transaction value is greater than the average value of all transactions, including transaction_id, from_address, to_address, value, and timestamp.

[Assistant]
SELECT transaction_id, from_address, to_address, value, timestamp
FROM web3.transactions
WHERE value > (SELECT AVG(value) FROM web3.transactions);

[User] For each block, compute the total number of transactions and the average gas_price.

[Assistant] SELECT block_number, COUNT(*) AS total_txs, AVG(gas_price) AS avg_gas_price FROM web3.transactions GROUP BY block_number;

[User] Actually, only include blocks with more than 100 transactions.

[Assistant] SELECT block_number, COUNT(*) AS total_txs, AVG(gas_price) AS avg_gas_price FROM web3.transactions GROUP BY block_number HAVING COUNT(*) > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)

[User] Find all properties in California (state_province = 'California') that have a phone number and email address listed.

[Assistant] SELECT property_name, city, phone_number, email_address FROM hospitality_technology.properties WHERE state_province = 'California' AND phone_number IS NOT NULL AND email_address IS NOT NULL;

[User] Now, join this with another query to show only properties that are also Hotels and have a star rating between 3.5 and 4.5.

[Assistant] SELECT p.property_name, p.city, p.phone_number, p.email_address, p.star_rating FROM hospitality_technology.properties p WHERE p.state_province = 'California' AND p.phone_number IS NOT NULL AND p.email_address IS NOT NULL AND p.property_type = 'Hotel' AND p.star_rating BETWEEN 3.5 AND 4.5;

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

[Assistant] SELECT p.property_name, p.city, p.postal_code, p.phone_number, p.email_address, p.star_rating FROM hospitality_technology.properties p WHERE p.state_province = 'California' AND p.phone_number IS NOT NULL AND p.email_address IS NOT NULL AND p.property_type = 'Hotel' AND p.star_rating BETWEEN 3.5 AND 4.5;

[User] Perfect! Now, order the results by city name in alphabetical order.

[Assistant] SELECT p.property_name, p.city, p.postal_code, p.phone_number, p.email_address, p.star_rating FROM hospitality_technology.properties p WHERE p.state_province = 'California' AND p.phone_number IS NOT NULL AND p.email_address IS NOT NULL AND p.property_type = 'Hotel' AND p.star_rating BETWEEN 3.5 AND 4.5 ORDER BY p.city ASC;

[User] Retrieve the total revenue and order count for each department for services in July 2023. Show department, revenue, and order_count.

[Assistant]
SELECT s.department,
       SUM(o.total_price) AS revenue,
       COUNT(o.order_id) AS order_count
FROM hospitality_technology.services s
JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
WHERE o.order_timestamp >= '2023-07-01'
  AND o.order_timestamp < '2023-08-01'
GROUP BY s.department;

[User] Actually, I want to see only departments with revenue over 5000, and sort the results by revenue descending.

[Assistant]
SELECT s.department,
       SUM(o.total_price) AS revenue,
       COUNT(o.order_id) AS order_count
FROM hospitality_technology.services s
JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
WHERE o.order_timestamp >= '2023-07-01'
  AND o.order_timestamp < '2023-08-01'
GROUP BY s.department
HAVING SUM(o.total_price) > 5000
ORDER BY revenue DESC;

[User] Also include the name of the highest priced service in each of these departments and alias it as top_service.

[Assistant]
SELECT dept_stats.department,
       dept_stats.revenue,
       dept_stats.order_count,
       (
         SELECT s2.service_name
         FROM hospitality_technology.services s2
         WHERE s2.department = dept_stats.department
         ORDER BY s2.price DESC
         LIMIT 1
       ) AS top_service
FROM (
  SELECT s.department,
         SUM(o.total_price) AS revenue,
         COUNT(o.order_id) AS order_count
  FROM hospitality_technology.services s
  JOIN hospitality_technology.service_orders o ON s.service_id = o.service_id
  WHERE o.order_timestamp >= '2023-07-01'
    AND o.order_timestamp < '2023-08-01'
  GROUP BY s.department
  HAVING SUM(o.total_price) > 5000
) AS dept_stats
ORDER BY dept_stats.revenue DESC;

[User] Show me each room type with its property name and the number of rooms of that type which are currently 'Occupied'.

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

[User] Only return room types where at least 2 rooms are 'Occupied'.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS occupied_room_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
JOIN hospitality_technology.rooms r ON r.room_type_id = rt.room_type_id
WHERE r.status = 'Occupied'
GROUP BY rt.type_name, p.property_name
HAVING COUNT(r.room_id) >= 2;

[User] Also, sort the results by occupied_room_count in descending order and only include room types at properties in the USA.

[Assistant]
SELECT rt.type_name, p.property_name, COUNT(r.room_id) AS occupied_room_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
JOIN hospitality_technology.rooms r ON r.room_type_id = rt.room_type_id
WHERE r.status = 'Occupied' AND p.country_code = 'USA'
GROUP BY rt.type_name, p.property_name
HAVING COUNT(r.room_id) >= 2
ORDER BY occupied_room_count DESC;

[User] For each reservation, can you show the guest's full name, the property name, and the room number?

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, rm.room_number
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.rooms rm ON r.room_id = rm.room_id;

[User] Also include the check-in and check-out dates for each reservation, and sort the results by check-in date.

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, rm.room_number, r.check_in_date, r.check_out_date
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.rooms rm ON r.room_id = rm.room_id
ORDER BY r.check_in_date;

[User] List all public reviews from the past 30 days with the property name and overall rating.

[Assistant]
SELECT r.review_id, p.property_name, r.rating_overall, r.review_date
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.properties AS p
  ON r.property_id = p.property_id
WHERE r.is_public = TRUE
  AND r.review_date >= CURRENT_DATE - INTERVAL '30 days';

[User] For each reservation, show the reservation ID and the total number of payments made for that reservation.

[Assistant]
SELECT
  r.reservation_id,
  COUNT(p.payment_id) AS payment_count
FROM hospitality_technology.reservations AS r
JOIN hospitality_technology.payments AS p
  ON r.reservation_id = p.reservation_id
GROUP BY
  r.reservation_id;

[User] Only include reservations that have at least 2 payments and show the total amount paid across all payments for each.

[Assistant]
SELECT
  r.reservation_id,
  COUNT(p.payment_id) AS payment_count,
  SUM(p.amount) AS total_amount_paid
FROM hospitality_technology.reservations AS r
JOIN hospitality_technology.payments AS p
  ON r.reservation_id = p.reservation_id
GROUP BY
  r.reservation_id
HAVING
  COUNT(p.payment_id) >= 2;

[User] Actually, show me the reservation ID, property ID, and check-in date for all reservations that have not received any payments.

[Assistant]
SELECT
  r.reservation_id,
  r.property_id,
  r.check_in_date
FROM hospitality_technology.reservations AS r
LEFT JOIN hospitality_technology.payments AS p
  ON r.reservation_id = p.reservation_id
WHERE
  p.payment_id IS NULL;

[User] Provide a list of properties and the total number of reservations made at each property.

[Assistant] SELECT p.property_name, COUNT(r.reservation_id) AS total_reservations FROM hospitality_technology.properties p JOIN hospitality_technology.reservations r ON p.property_id = r.property_id GROUP BY p.property_name;

[User] Now, filter this list to only include properties with a star rating of 4 or higher.

[Assistant] SELECT p.property_name, COUNT(r.reservation_id) AS total_reservations FROM hospitality_technology.properties p JOIN hospitality_technology.reservations r ON p.property_id = r.property_id WHERE p.star_rating >= 4 GROUP BY p.property_name;

[User] Only show those properties that have more than 100 reservations and order them by the number of reservations in descending order.

[Assistant] SELECT p.property_name, COUNT(r.reservation_id) AS total_reservations FROM hospitality_technology.properties p JOIN hospitality_technology.reservations r ON p.property_id = r.property_id WHERE p.star_rating >= 4 GROUP BY p.property_name HAVING COUNT(r.reservation_id) > 100 ORDER BY total_reservations DESC;