[User] Show me the number of game servers in each region and the average maximum number of players they can accommodate. Exclude any servers that are currently offline.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region;

[User] Please filter the results to only include regions that have more than 5 active servers.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Can you also include the total number of current players across all active servers in each of those regions?

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Order the final results by the total number of current players in descending order.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5 ORDER BY total_current_players DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
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 NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
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] For each chain, which centralized exchange holds the largest total USD value in their token balance as of the most recent snapshot?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
)
SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value
FROM cex_token_balance c
JOIN latest_snapshot l ON c.snapshot_time = l.max_time
GROUP BY c.chain, c.exchange
QUALIFY ROW_NUMBER() OVER(PARTITION BY c.chain ORDER BY SUM(c.usd_value) DESC) = 1;

[User] Could you also include the number of distinct tokens each exchange holds in those chains?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  GROUP BY c.chain, c.exchange
),
ranked_exchanges AS (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY chain ORDER BY total_usd_value DESC) AS rn
  FROM exchange_totals
)
SELECT chain, exchange, total_usd_value, token_count
FROM ranked_exchanges
WHERE rn = 1;

[User] I got an error with the QUALIFY clause. Can you rewrite the query using a derived table or CTE instead?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  GROUP BY c.chain, c.exchange
),
max_values AS (
  SELECT chain, MAX(total_usd_value) AS max_usd_value
  FROM exchange_totals
  GROUP BY chain
)
SELECT e.chain, e.exchange, e.total_usd_value, e.token_count
FROM exchange_totals e
JOIN max_values m ON e.chain = m.chain AND e.total_usd_value = m.max_usd_value;

[User] Now, only show exchanges where their usd_value is above $5,000,000.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  GROUP BY c.chain, c.exchange
),
max_values AS (
  SELECT chain, MAX(total_usd_value) AS max_usd_value
  FROM exchange_totals
  GROUP BY chain
)
SELECT e.chain, e.exchange, e.total_usd_value, e.token_count
FROM exchange_totals e
JOIN max_values m ON e.chain = m.chain AND e.total_usd_value = m.max_usd_value
WHERE e.total_usd_value > 5000000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative.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) )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )


[User] For each user, list all pairs of read and unread notifications, showing the recipient_user_id, the unread notification_id and type, and the read notification_id and type.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL;

[User] Actually, only include pairs where the unread notification_type is 'message'.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL
  AND n_unread.notification_type = 'message';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )


[User] Show all tokens on the Ethereum chain in token_dexpool_info that had a price increase in the last 6 hours, along with their 24h trading volume and smart money ROI.

[Assistant]
SELECT td.token_symbol,
       td.price_change_percentage_6h,
       td.volume_24h,
       smtp.roi
FROM token_dexpool_info AS td
JOIN smart_money_token_performance AS smtp
  ON td.token_symbol = smtp.token_symbol
 AND td.chain = smtp.chain
WHERE td.chain = 'Ethereum'
  AND td.price_change_percentage_6h > 0;

[User] I only want tokens with liquidity over 1,000,000 and ROI above 1. Show the price_change_24h as well.

[Assistant]
SELECT td.token_symbol,
       td.price_change_percentage_6h,
       td.price_change_percentage_24h,
       td.volume_24h,
       td.liquidity,
       smtp.roi
FROM token_dexpool_info AS td
JOIN smart_money_token_performance AS smtp
  ON td.token_symbol = smtp.token_symbol
 AND td.chain = smtp.chain
WHERE td.chain = 'Ethereum'
  AND td.price_change_percentage_6h > 0
  AND td.liquidity > 1000000
  AND smtp.roi > 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
CREATE TABLE token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )


[User] Show me the total quantity of fuel consumed and the total cost for each vehicle that has fuel log entries, including the vehicle's make and model.

[Assistant] SELECT T1.vehicle_id, T2.make, T2.model, SUM(T1.quantity) AS total_fuel_quantity, SUM(T1.total_cost) AS total_fuel_cost FROM transportation.fuel_logs AS T1 JOIN transportation.vehicles AS T2 ON T1.vehicle_id = T2.vehicle_id GROUP BY T1.vehicle_id, T2.make, T2.model;

[User] From that list, only include vehicles where the total fuel cost exceeds 5000.

[Assistant] SELECT T1.vehicle_id, T2.make, T2.model, SUM(T1.quantity) AS total_fuel_quantity, SUM(T1.total_cost) AS total_fuel_cost FROM transportation.fuel_logs AS T1 JOIN transportation.vehicles AS T2 ON T1.vehicle_id = T2.vehicle_id GROUP BY T1.vehicle_id, T2.make, T2.model HAVING SUM(T1.total_cost) > 5000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )


[User] List all events and any token transfers that occurred in the same transaction, showing event_id, event_name, transfer_id, and token_symbol.

[Assistant]
SELECT
  e.event_id,
  e.event_name,
  tt.transfer_id,
  tk.token_symbol
FROM web3.events e
LEFT JOIN web3.token_transfers tt
  ON e.transaction_id = tt.transaction_id
LEFT JOIN web3.tokens tk
  ON tt.token_id = tk.token_id
ORDER BY e.transaction_id, e.log_index;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
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)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] I want to identify pairs of games developed by the same developer but available on different platforms. Include the titles and platforms of both games.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS game1_title,
       g1.platform AS platform1,
       g2.game_id AS game2_id,
       g2.title AS game2_title,
       g2.platform AS platform2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
  AND g1.platform <> g2.platform;

[User] Also, filter to pairs where both games were released after 2021.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS game1_title,
       g1.platform AS platform1,
       g2.game_id AS game2_id,
       g2.title AS game2_title,
       g2.platform AS platform2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.developer_id = g2.developer_id
  AND g1.game_id < g2.game_id
  AND g1.platform <> g2.platform
WHERE g1.release_date > '2021-12-31'
  AND g2.release_date > '2021-12-31';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)


[User] Show the plan name and insurance provider for all insurance plans along with the total number of unique patients enrolled in each plan.

[Assistant]
SELECT ip.plan_name, ip.insurance_provider, COUNT(DISTINCT pi.patient_id) AS enrolled_patient_count
FROM healthcare.insurance_plans ip
JOIN healthcare.patients_insurance pi ON ip.plan_id = pi.plan_id
GROUP BY ip.plan_name, ip.insurance_provider;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] What are the personal contact details of the staff member associated with staff_id 'STAFF789' who worked on a specific maintenance record?

[Assistant] I'm sorry, but I can't provide personal contact details of staff members as this information is not stored in the maintenance_records table and is outside the scope of the available data.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id text, asset_id text, asset_type text, maintenance_type text, staff_id text, start_datetime timestamp, end_datetime timestamp, description text, cost numeric, status text )


[User] Show me all active agents who have handled claims with police reports, along with the count of such claims per agent.

[Assistant] SELECT a.agent_id, a.first_name, a.last_name, COUNT(c.claim_id) AS police_report_claim_count FROM insurance.agents a JOIN insurance.claims c ON a.agent_id = c.claim_handler_id WHERE a.status = 'active' AND c.police_report_number IS NOT NULL GROUP BY a.agent_id, a.first_name, a.last_name;

[User] Now filter this to only show agents who have handled more than 5 police report claims.

[Assistant] SELECT a.agent_id, a.first_name, a.last_name, COUNT(c.claim_id) AS police_report_claim_count FROM insurance.agents a JOIN insurance.claims c ON a.agent_id = c.claim_handler_id WHERE a.status = 'active' AND c.police_report_number IS NOT NULL GROUP BY a.agent_id, a.first_name, a.last_name HAVING COUNT(c.claim_id) > 5;

[User] I also want to see their agency names and sort the results by the count of claims in descending order.

[Assistant] SELECT a.agent_id, a.first_name, a.last_name, a.agency_name, COUNT(c.claim_id) AS police_report_claim_count FROM insurance.agents a JOIN insurance.claims c ON a.agent_id = c.claim_handler_id WHERE a.status = 'active' AND c.police_report_number IS NOT NULL GROUP BY a.agent_id, a.first_name, a.last_name, a.agency_name HAVING COUNT(c.claim_id) > 5 ORDER BY police_report_claim_count DESC;

[User] Finally, include only agents whose commission rate is above 0.08.

[Assistant] SELECT a.agent_id, a.first_name, a.last_name, a.agency_name, a.commission_rate, COUNT(c.claim_id) AS police_report_claim_count FROM insurance.agents a JOIN insurance.claims c ON a.agent_id = c.claim_handler_id WHERE a.status = 'active' AND c.police_report_number IS NOT NULL AND a.commission_rate > 0.08 GROUP BY a.agent_id, a.first_name, a.last_name, a.agency_name, a.commission_rate HAVING COUNT(c.claim_id) > 5 ORDER BY police_report_claim_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Show me wallet addresses that hold more than 1000 of any ERC1155 token, along with the token ID and contract address.

[Assistant] SELECT wallet_address, token_id, contract_address FROM erc20_balances WHERE CAST(amount AS decimal) > 1000;

[User] I think there's an error in your query - it should be using the nft_metadata table for ERC1155 tokens. Also, can you include the token name from the nft_metadata table?

[Assistant] SELECT nm.owner as wallet_address, nm.token_id, nm.contract_address, nm.name FROM nft_metadata nm WHERE nm.erc_type = 'ERC1155' AND CAST(nm.amount AS decimal) > 1000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE nft_collections ( blockchain.text, contract_address.text, name.text, symbol.text, deploy_block_number.bigint, deploy_block_time.bigint, erc_type.text, owner.text, traits.text, description.text, slug.text, media_info.text, image_url.text, banner_image_url.text, updated_at.bigint, banner.text, token_count.bigint, floor_price.text, floor_price_symbol.text, floor_price_contract.text, pk.integer )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] List the names of service locations and categories of active services offered by the same agency.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE;

[User] Please exclude service locations that are not accessible.

[Assistant]
SELECT sl.location_name, s.category
FROM government_services.service_locations AS sl
JOIN government_services.services AS s
  ON sl.agency_id = s.agency_id
WHERE s.is_active = TRUE
  AND sl.is_accessible = TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)


[User] Show me all reservations with more than 2 adults, along with their property names and room types.

[Assistant] SELECT r.reservation_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2;

[User] Now, include only reservations with a total amount over $500 and order them by check-in date.

[Assistant] SELECT r.reservation_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 ORDER BY r.check_in_date;

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

[Assistant] SELECT r.reservation_id, r.guest_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 ORDER BY r.check_in_date;

[User] Actually, I need to see only reservations from properties with a star rating of 4.0 or higher.

[Assistant] SELECT r.reservation_id, r.guest_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount, p.star_rating FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 AND p.star_rating >= 4.0 ORDER BY r.check_in_date;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] List all rooms that are currently in 'Maintenance' status, including their room numbers and current conditions.

[Assistant] SELECT room_number, current_condition FROM hospitality_technology.rooms WHERE status = 'Maintenance';

[User] Now, filter these results to only include rooms on floors 1 through 3.

[Assistant] SELECT room_number, current_condition FROM hospitality_technology.rooms WHERE status = 'Maintenance' AND floor BETWEEN 1 AND 3;

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

[Assistant] SELECT property_id, room_number, current_condition FROM hospitality_technology.rooms WHERE status = 'Maintenance' AND floor BETWEEN 1 AND 3;

[User] Actually, I need to see the results ordered by property_id first, then by room_number.

[Assistant] SELECT property_id, room_number, current_condition FROM hospitality_technology.rooms WHERE status = 'Maintenance' AND floor BETWEEN 1 AND 3 ORDER BY property_id, room_number;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)


[User] Identify all instances where a vehicle's odometer_reading increased by more than 500 miles between two consecutive fuel log entries.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       a.log_timestamp                       AS previous_time,
       b.log_timestamp                       AS next_time,
       b.odometer_reading - a.odometer_reading AS mile_increase
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500;

[User] Now restrict these increases to those where the time difference between entries is less than 7 days.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       a.log_timestamp                       AS previous_time,
       b.log_timestamp                       AS next_time,
       b.odometer_reading - a.odometer_reading AS mile_increase,
       EXTRACT(epoch FROM (b.log_timestamp - a.log_timestamp))/3600 AS hours_diff
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500
  AND b.log_timestamp - a.log_timestamp < INTERVAL '7 days';

[User] Also include both the mile increase and the time difference in hours in the final output columns.

[Assistant]
SELECT a.vehicle_id,
       a.fuel_log_id                         AS previous_log_id,
       b.fuel_log_id                         AS next_log_id,
       b.odometer_reading - a.odometer_reading AS mile_increase,
       EXTRACT(epoch FROM (b.log_timestamp - a.log_timestamp))/3600 AS hours_difference
FROM transportation.fuel_logs a
JOIN transportation.fuel_logs b
  ON a.vehicle_id = b.vehicle_id
 AND b.log_timestamp = (
      SELECT MIN(log_timestamp)
      FROM transportation.fuel_logs
      WHERE vehicle_id = a.vehicle_id
        AND log_timestamp > a.log_timestamp
    )
WHERE b.odometer_reading - a.odometer_reading > 500
  AND b.log_timestamp - a.log_timestamp < INTERVAL '7 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )


[User] Provide a report of each user with their username and the count of all log entries from the last 30 days.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS log_count
FROM trading_platform.users u
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY u.user_id, u.username;

[User] Actually, show only logs where the action includes the word 'trade'.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS log_count
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username;

[User] Also include the earliest log date for each user in that period.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) AS log_count,
       MIN(l.logged_at) AS first_log_date
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username;

[User] Finally, sort the results by log_count descending and limit to the top 5 users.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) AS log_count,
       MIN(l.logged_at) AS first_log_date
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username
ORDER BY log_count DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)


[User] 我想查看所有检查记录中检查员的ID和检查结果，同时统计每个检查员的检查次数。

[Assistant]
db.inspections.aggregate([
  {
    $group: {
      _id: '$inspector_employee_id',
      total_inspections: { $count: {} },
      results: { $push: '$result' }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      total_inspections: 1,
      results: 1,
      _id: 0
    }
  }
]);

[User] 如果我想只统计检查结果为'Fail'的次数，应该怎么改？

[Assistant]
db.inspections.aggregate([
  {
    $match: {
      result: 'Fail'
    }
  },
  {
    $group: {
      _id: '$inspector_employee_id',
      failed_inspections: { $count: {} }
    }
  },
  {
    $project: {
      inspector_employee_id: '$_id',
      failed_inspections: 1,
      _id: 0
    }
  }
]);

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'inspections'. Document structure: { _id: <ObjectId (or inspection_id)>, inspection_id: String, build_id: String (reference), component_id: String (reference, optional), step_id: String (reference, optional), inspection_type: String, inspector_employee_id: String (reference), inspection_timestamp: ISODate, result: String, remarks: String }. Required: inspection_id, build_id, inspection_type, inspector_employee_id, inspection_timestamp, result. Indexes on build_id, component_id, step_id, inspector_employee_id, result.


[User] List all pairs of locations that are in the same city. Include their names and the city they are in.

[Assistant]
SELECT
  l1.name AS location1_name,
  l2.name AS location2_name,
  l1.city
FROM transportation.locations AS l1
JOIN transportation.locations AS l2
  ON l1.city = l2.city AND l1.location_id < l2.location_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )


[User] For each vehicle that has both maintenance and fuel log records, show the vehicle_id, make, model, count of maintenance_logs as maintenance_count, and count of fuel_logs as fuel_count.

[Assistant]
SELECT v.vehicle_id, v.make, v.model,
       COUNT(DISTINCT m.log_id) AS maintenance_count,
       COUNT(DISTINCT f.fuel_log_id) AS fuel_count
FROM transportation.vehicles v
JOIN transportation.maintenance_logs m ON v.vehicle_id = m.vehicle_id
JOIN transportation.fuel_logs f ON v.vehicle_id = f.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model;

[User] Now include only vehicles with at least 2 maintenance logs and at least 3 fuel logs.

[Assistant]
SELECT v.vehicle_id, v.make, v.model,
       COUNT(DISTINCT m.log_id) AS maintenance_count,
       COUNT(DISTINCT f.fuel_log_id) AS fuel_count
FROM transportation.vehicles v
JOIN transportation.maintenance_logs m ON v.vehicle_id = m.vehicle_id
JOIN transportation.fuel_logs f ON v.vehicle_id = f.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model
HAVING COUNT(DISTINCT m.log_id) >= 2
   AND COUNT(DISTINCT f.fuel_log_id) >= 3;

[User] Also include the maximum odometer_reading from maintenance_logs and the total_cost of all fuel_logs for these vehicles.

[Assistant]
SELECT v.vehicle_id, v.make, v.model,
       COUNT(DISTINCT m.log_id) AS maintenance_count,
       COUNT(DISTINCT f.fuel_log_id) AS fuel_count,
       MAX(m.odometer_reading) AS max_odometer,
       SUM(f.total_cost) AS total_fuel_cost
FROM transportation.vehicles v
JOIN transportation.maintenance_logs m ON v.vehicle_id = m.vehicle_id
JOIN transportation.fuel_logs f ON v.vehicle_id = f.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model
HAVING COUNT(DISTINCT m.log_id) >= 2
   AND COUNT(DISTINCT f.fuel_log_id) >= 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)
CREATE TABLE transportation.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] For each vehicle, find the vehicle in the same depot that was acquired immediately before it. Display the current vehicle_id, acquisition_date, previous vehicle_id, and its acquisition_date.

[Assistant] SELECT v.vehicle_id, v.acquisition_date, prev.vehicle_id AS previous_vehicle_id, prev.acquisition_date AS previous_acquisition_date FROM transportation.vehicles v JOIN transportation.vehicles prev ON v.depot_id = prev.depot_id AND prev.acquisition_date = (SELECT MAX(acquisition_date) FROM transportation.vehicles WHERE depot_id = v.depot_id AND acquisition_date < v.acquisition_date);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )


[User] List all claims that were reported more than 30 days after the incident date.

[Assistant] SELECT claim_id, policy_id, customer_id, incident_date, reported_date FROM insurance.claims WHERE DATEDIFF(reported_date, incident_date) > 30;

[User] Now show only claims that are still pending (status = 'pending').

[Assistant] SELECT claim_id, policy_id, customer_id, incident_date, reported_date FROM insurance.claims WHERE DATEDIFF(reported_date, incident_date) > 30 AND status = 'pending';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )


[User] Find all documents of type 'Correspondence' uploaded in 2023. Show the document name, upload timestamp, and the name of the case it belongs to.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023;

[User] Now, only show the documents for cases handled by lawyer with ID 'lawyer_001'.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023 AND T2.lead_lawyer_id = 'lawyer_001';

[User] Additionally, include the first and last name of the lawyer who actually uploaded the document, and sort the results by upload timestamp descending.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name, T3.first_name, T3.last_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id JOIN legal_services.lawyers AS T3 ON T1.uploaded_by_lawyer_id = T3.lawyer_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023 AND T2.lead_lawyer_id = 'lawyer_001' ORDER BY T1.upload_timestamp DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] For projects that have completed more than one fundraising round, calculate the average investment value across all their recorded rounds. Display the project name and this average value.

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1;

[User] Can you modify this to only show projects where the average investment value is greater than 10 million USD and order the results by average investment value descending?

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 AND AVG(investment_value) > 10000000 ORDER BY average_investment DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 )


[User] List all pairs of loans for the same account where the first loan's principal_amount is greater than the second loan's principal_amount. For each pair, show account_id, loan_id as loan_a and loan_id as loan_b.

[Assistant]
SELECT l1.account_id, l1.loan_id AS loan_a, l2.loan_id AS loan_b
FROM financial_services.loans l1
JOIN financial_services.loans l2
  ON l1.account_id = l2.account_id
  AND l1.principal_amount > l2.principal_amount;

[User] Actually, I only want pairs where loan_a has status 'Active' and loan_b has status 'Closed'.

[Assistant]
SELECT l1.account_id, l1.loan_id AS loan_a, l2.loan_id AS loan_b
FROM financial_services.loans l1
JOIN financial_services.loans l2
  ON l1.account_id = l2.account_id
  AND l1.principal_amount > l2.principal_amount
WHERE l1.status = 'Active'
  AND l2.status = 'Closed';

[User] Also, only include pairs where both loans were originated within 90 days of each other.

[Assistant]
SELECT l1.account_id, l1.loan_id AS loan_a, l2.loan_id AS loan_b
FROM financial_services.loans l1
JOIN financial_services.loans l2
  ON l1.account_id = l2.account_id
  AND l1.principal_amount > l2.principal_amount
WHERE l1.status = 'Active'
  AND l2.status = 'Closed'
  AND ABS(EXTRACT(DAY FROM (l1.origination_date - l2.origination_date))) <= 90;

[User] Finally, order the results by account_id ascending and principal_amount of loan_a descending.

[Assistant]
SELECT l1.account_id, l1.loan_id AS loan_a, l2.loan_id AS loan_b
FROM financial_services.loans l1
JOIN financial_services.loans l2
  ON l1.account_id = l2.account_id
  AND l1.principal_amount > l2.principal_amount
WHERE l1.status = 'Active'
  AND l2.status = 'Closed'
  AND ABS(EXTRACT(DAY FROM (l1.origination_date - l2.origination_date))) <= 90
ORDER BY l1.account_id ASC, l1.principal_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id text PRIMARY KEY, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months int, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )


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

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )


[User] Show the diagnosis codes, descriptions, and their corresponding insurance plan names for all chronic diagnoses.

[Assistant]
SELECT d.diagnosis_code, d.description, ip.plan_name
FROM healthcare.diagnoses d
JOIN healthcare.insurance_plans ip ON d.diagnosis_code = ip.plan_id
WHERE d.is_chronic = TRUE;

[User] Only include those diagnoses which have status 'Active'.

[Assistant]
SELECT d.diagnosis_code, d.description, ip.plan_name
FROM healthcare.diagnoses d
JOIN healthcare.insurance_plans ip ON d.diagnosis_code = ip.plan_id
WHERE d.is_chronic = TRUE AND d.status = 'Active';

[User] Instead, only show diagnoses made after January 1, 2022.

[Assistant]
SELECT d.diagnosis_code, d.description, ip.plan_name
FROM healthcare.diagnoses d
JOIN healthcare.insurance_plans ip ON d.diagnosis_code = ip.plan_id
WHERE d.is_chronic = TRUE AND d.diagnosis_date > '2022-01-01';

[User] I am seeing missing results for some diagnoses that I know are chronic and active. Can you check if the join condition is correct?

[Assistant]
SELECT d.diagnosis_code, d.description
FROM healthcare.diagnoses d
WHERE d.is_chronic = TRUE AND d.status = 'Active' AND d.diagnosis_date > '2022-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )


[User] What is the current market price of a Boeing 737 MAX aircraft?

[Assistant] I'm sorry, but I don't have access to the current market price of aircraft models. The data I have is limited to technical specifications and general information about aircraft models such as passenger capacity, range, and status. For pricing information, you may need to consult with manufacturers or industry reports.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models (
    model_id character varying(64) NOT NULL,  -- unique identifier for the aircraft model
    model_name character varying(128) NOT NULL, -- commercial name of the model (e.g., 737 MAX, A320neo)
    manufacturer character varying(128) NOT NULL, -- manufacturer name (e.g., Boeing, Airbus)
    passenger_capacity integer, -- typical passenger capacity
    max_range_km integer, -- maximum flight range in kilometers
    engine_type character varying(100), -- type of engines used
    wingspan_m numeric(6,2), -- wingspan in meters
    status character varying(50) NOT NULL, -- e.g., 'In Production', 'Development', 'Discontinued'
    first_flight_date date, -- date of the model's first flight
    PRIMARY KEY (model_id)
)


[User] Show me all events emitted by contracts where the event name contains 'Approval', along with the contract ID and transaction ID, sorted by emitted timestamp in descending order.

[Assistant] SELECT event_id, contract_id, event_name, transaction_id, emitted_at FROM web3.events WHERE event_name LIKE '%Approval%' ORDER BY emitted_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)


[User] Show employees hired before 2020 along with their manager's full name.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01';

[User] Only include employees whose manager's job title is 'Branch Manager'.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01' AND m.job_title = 'Branch Manager';

[User] Also, only show employees who are 'Active'.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01' AND m.job_title = 'Branch Manager' AND e.status = 'Active';

[User] Include the employee's job title and order the results by hire date ascending.

[Assistant] SELECT e.first_name, e.last_name, e.job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.hire_date < '2020-01-01' AND m.job_title = 'Branch Manager' AND e.status = 'Active' ORDER BY e.hire_date ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] For each guest, calculate their total spending on delivered service orders and the total number of those orders.

[Assistant]
SELECT g.guest_id,
       g.first_name || ' ' || g.last_name AS full_name,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.guests g
JOIN hospitality_technology.service_orders so
  ON g.guest_id = so.guest_id
WHERE so.status = 'delivered'
GROUP BY g.guest_id, full_name;

[User] I need the breakdown by month for the current year. Show guest ID, month, total spent, and total orders.

[Assistant]
SELECT so.guest_id,
       DATE_TRUNC('month', so.delivery_timestamp) AS month,
       SUM(so.total_price) AS total_spent,
       COUNT(*) AS total_orders
FROM hospitality_technology.service_orders so
WHERE so.status = 'delivered'
  AND so.delivery_timestamp >= '2024-01-01'
  AND so.delivery_timestamp < '2025-01-01'
GROUP BY so.guest_id, month
ORDER BY month;

[User] Also include the guest’s email and only show months where total spent is greater than 500.

[Assistant]
SELECT sub.guest_id,
       g.email,
       sub.month,
       sub.total_spent,
       sub.total_orders
FROM (
  SELECT so.guest_id,
         DATE_TRUNC('month', so.delivery_timestamp) AS month,
         SUM(so.total_price) AS total_spent,
         COUNT(*) AS total_orders
  FROM hospitality_technology.service_orders so
  WHERE so.status = 'delivered'
    AND so.delivery_timestamp >= '2024-01-01'
    AND so.delivery_timestamp < '2025-01-01'
  GROUP BY so.guest_id, month
) sub
JOIN hospitality_technology.guests g
  ON sub.guest_id = g.guest_id
WHERE sub.total_spent > 500
ORDER BY sub.month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Show a list of all wallet addresses along with the user_id who owns them, sorted by the wallet creation time.

[Assistant] SELECT user_id, address FROM web3.wallets ORDER BY created_at;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)