[User] Can you help me get the total number of operational platforms across all stations?

[Assistant] db.platforms.countDocuments({ status: 'Operational' });

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
// db.createCollection('platforms')
// Optional: db.platforms.createIndex({ platform_id: 1 }, { unique: true })
// Optional: db.platforms.createIndex({ station_id: 1 })
{
  _id: ObjectId(),
  platform_id: "plat_123", // String (unique)
  station_id: "station_xyz", // String (references stations.station_id)
  platform_number: "1A", // String
  track_number: "T1", // String
  status: "Operational", // String ('Operational', 'Maintenance', 'Closed')
  length_meters: 250.50, // Decimal128 or Double
  accessible: true // Boolean
}
// db.createCollection('routes')
// Optional: db.routes.createIndex({ route_id: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_id: "route_ne_corr", // String (unique)
  route_name: "Northeast Corridor", // String
  description: "High-speed rail linking Boston and Washington D.C.", // String
  origin_station_id: "station_bos", // String (references stations.station_id)
  destination_station_id: "station_was", // String (references stations.station_id)
  is_active: true // Boolean
}
// db.createCollection('route_stations')
// Optional: db.route_stations.createIndex({ route_station_id: 1 }, { unique: true })
// Optional: db.route_stations.createIndex({ route_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_station_id: "rs_ne_1", // String (unique)
  route_id: "route_ne_corr", // String (references routes.route_id)
  station_id: "station_bos", // String (references stations.station_id)
  sequence_order: 1, // Int32
  distance_from_previous_km: null, // Decimal128 or Double (null for first stop)
  typical_stop_duration_minutes: null // Int32 (null for origin/destination or if no stop)
}
// --- OR --- Embed within the Route document:
// {
//   _id: ObjectId(), route_id: "route_ne_corr", ...,
//   stations: [
//     { station_id: "station_bos", sequence_order: 1, distance_from_previous_km: null, typical_stop_duration_minutes: null },
//     { station_id: "station_pvd", sequence_order: 2, distance_from_previous_km: 70.5, typical_stop_duration_minutes: 5 },
//     ...
//   ]
// }
// db.createCollection('schedules')
// Optional: db.schedules.createIndex({ schedule_id: 1 }, { unique: true })
// Optional: db.schedules.createIndex({ route_id: 1, departure_datetime: 1 })
{
  _id: ObjectId(),
  schedule_id: "sched_1122", // String (unique)
  train_id: "train_789", // String (references trains.train_id)
  route_id: "route_ne_corr", // String (references routes.route_id)
  departure_datetime: ISODate("2024-05-10T08:00:00-04:00"), // Date (with timezone)
  arrival_datetime: ISODate("2024-05-10T15:30:00-04:00"), // Date (with timezone)
  status: "Scheduled", // String ('Scheduled', 'On Time', 'Delayed', 'Cancelled', 'Arrived')
  notes: "Track work expected near Philadelphia" // String
}
// db.createCollection('schedule_stops')
// Optional: db.schedule_stops.createIndex({ stop_id: 1 }, { unique: true })
// Optional: db.schedule_stops.createIndex({ schedule_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  stop_id: "stop_sched1122_1", // String (unique)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  station_id: "station_bos", // String (references stations.station_id)
  platform_id: "plat_bos_3", // String (references platforms.platform_id, nullable)
  sequence_order: 1, // Int32
  scheduled_arrival_time: null, // Date
  scheduled_departure_time: ISODate("2024-05-10T08:00:00-04:00"), // Date
  actual_arrival_time: null, // Date
  actual_departure_time: ISODate("2024-05-10T08:01:00-04:00"), // Date
  status: "On Time" // String
}
// --- OR --- Embed within the Schedule document using an array 'stops'
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}


[User] For each Avalanche token tick, show me the creator from the `token_info_avalanche` table and the total number of activities recorded for that tick in the `token_activities` table.

[Assistant] SELECT ti.tick, ti.creator, COUNT(ta.tx_hash) AS total_activities FROM token_info_avalanche ti JOIN token_activities ta ON ti.tick = ta.tick GROUP BY ti.tick, ti.creator;

[User] Filter the results to only include tokens where the total number of activities is greater than 100.

[Assistant] SELECT ti.tick, ti.creator, COUNT(ta.tx_hash) AS total_activities FROM token_info_avalanche ti JOIN token_activities ta ON ti.tick = ta.tick GROUP BY ti.tick, ti.creator HAVING COUNT(ta.tx_hash) > 100;

[User] Order the results by the total number of activities descending and limit to the top 5 tokens.

[Assistant] SELECT ti.tick, ti.creator, COUNT(ta.tx_hash) AS total_activities FROM token_info_avalanche ti JOIN token_activities ta ON ti.tick = ta.tick GROUP BY ti.tick, ti.creator HAVING COUNT(ta.tx_hash) > 100 ORDER BY total_activities 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 erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
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 token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(20) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL, -- Address originating the inscription (matches from_address in transactions table)
    minted decimal(38,0) NOT NULL, -- Sum of minted amount
    holders decimal(38,0) NOT NULL, -- Count of holders
    txs decimal(38,0) NOT NULL, -- Count of transactions
    updated_timestamp timestamp(3) NOT NULL, -- Timestamp of update
    completed_timestamp timestamp(3) NOT NULL, -- Timestamp of minted completed
    id varchar(255) NOT NULL  -- id fields for the functionType  in contract asc20
)


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

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

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,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, 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 int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )


[User] Find tokens that have a positive price change percentage over the last 1 hour, 6 hours, and 24 hours. Display their symbol and chain.

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0;

[User] Only show results for chains where the average trend rank is better than 5 (lower value indicates higher popularity).

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5);

[User] Order the results by the 24-hour price change percentage in descending order.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC;

[User] Limit the result to the top 20 tokens.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC LIMIT 20;

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 token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )


[User] List all payments, showing the payment amount, currency, and the guest's full name who made the payment.

[Assistant] SELECT p.payment_id, p.amount, p.currency_code, g.first_name, g.last_name FROM hospitality_technology.payments AS p JOIN hospitality_technology.guests AS g ON p.guest_id = g.guest_id;

[User] Also include the property name associated with the reservation for each payment.

[Assistant] SELECT p.payment_id, p.amount, p.currency_code, g.first_name, g.last_name, prop.property_name FROM hospitality_technology.payments AS p JOIN hospitality_technology.guests AS g ON p.guest_id = g.guest_id JOIN hospitality_technology.reservations AS res ON p.reservation_id = res.reservation_id JOIN hospitality_technology.properties AS prop ON res.property_id = prop.property_id;

[User] Filter this list to only include payments made for reservations at properties with a star rating of 5.

[Assistant] SELECT p.payment_id, p.amount, p.currency_code, g.first_name, g.last_name, prop.property_name FROM hospitality_technology.payments AS p JOIN hospitality_technology.guests AS g ON p.guest_id = g.guest_id JOIN hospitality_technology.reservations AS res ON p.reservation_id = res.reservation_id JOIN hospitality_technology.properties AS prop ON res.property_id = prop.property_id WHERE prop.star_rating = 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 hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
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)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.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.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 text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
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,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)


[User] Find the service locations that are not accessible and located in the state of 'California'. List their name, address, and city.

[Assistant] SELECT location_name ,  address ,  city FROM government_services.service_locations WHERE is_accessible = false AND state = 'California'

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.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] Show me all trips that were completed with vehicles manufactured after 2020, including the vehicle make and model.

[Assistant] SELECT t.trip_id, v.make, v.model FROM transportation.trips t JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id WHERE t.status = 'Completed' AND v.year > 2020;

[User] Now include the driver's first and last name for these trips, and filter to only show trips with passenger counts greater than 5.

[Assistant] SELECT t.trip_id, v.make, v.model, d.first_name, d.last_name FROM transportation.trips t JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id JOIN transportation.drivers d ON t.driver_id = d.driver_id WHERE t.status = 'Completed' AND v.year > 2020 AND t.passenger_count > 5;

[User] Can you order these results by the vehicle make in ascending order and then by passenger count in descending order?

[Assistant] SELECT t.trip_id, v.make, v.model, d.first_name, d.last_name, t.passenger_count FROM transportation.trips t JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id JOIN transportation.drivers d ON t.driver_id = d.driver_id WHERE t.status = 'Completed' AND v.year > 2020 AND t.passenger_count > 5 ORDER BY v.make ASC, t.passenger_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 transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.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.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_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.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


[User] Count the number of law firms founded in each decade. Show the decade (e.g., 1990s, 2000s) and the count.

[Assistant] SELECT CONCAT(FLOOR(EXTRACT(YEAR FROM founded_date) / 10) * 10, 's') AS decade, COUNT(*) AS firm_count FROM law_firms WHERE founded_date IS NOT NULL GROUP BY decade ORDER BY decade;

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.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )


[User] I'd like a report showing for each sector the average close_price and maximum volume from market_data for the previous quarter.

[Assistant]
SELECT s.sector, AVG(md.close_price) AS avg_close_price, MAX(md.volume) AS max_volume
FROM financial_services.market_data md
JOIN financial_services.securities s ON md.security_id = s.security_id
WHERE md.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND md.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY s.sector;

[User] Actually, only include records where source = 'Reuters'.

[Assistant]
SELECT s.sector, AVG(md.close_price) AS avg_close_price, MAX(md.volume) AS max_volume
FROM financial_services.market_data md
JOIN financial_services.securities s ON md.security_id = s.security_id
WHERE md.source = 'Reuters'
  AND md.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND md.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY s.sector;

[User] The SQL runs but it complains about ambiguous column references. Could you alias the tables properly and ensure the join is clear?

[Assistant]
SELECT sec.sector, AVG(mdk.close_price) AS avg_close_price, MAX(mdk.volume) AS max_volume
FROM financial_services.market_data AS mdk
JOIN financial_services.securities AS sec
  ON mdk.security_id = sec.security_id
WHERE mdk.source = 'Reuters'
  AND mdk.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND mdk.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY sec.sector;

[User] Additionally, please only consider data points where volume is greater than 1000000.

[Assistant]
SELECT sec.sector, AVG(mdk.close_price) AS avg_close_price, MAX(mdk.volume) AS max_volume
FROM financial_services.market_data AS mdk
JOIN financial_services.securities AS sec
  ON mdk.security_id = sec.security_id
WHERE mdk.source = 'Reuters'
  AND mdk.volume > 1000000
  AND mdk.data_timestamp >= date_trunc('quarter', CURRENT_DATE) - INTERVAL '3 months'
  AND mdk.data_timestamp < date_trunc('quarter', CURRENT_DATE)
GROUP BY sec.sector;

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.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )


[User] What are the maintenance costs for a specific aircraft model like the Airbus A320?

[Assistant] I'm sorry, but I don't have access to data regarding maintenance costs for specific aircraft models such as the Airbus A320. The information in the database is limited to details like model name, manufacturer, passenger capacity, and technical specifications. For maintenance cost information, you may need to consult with the manufacturer or a maintenance service provider.

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, model_name character varying(128) NOT NULL, manufacturer character varying(128) NOT NULL, passenger_capacity integer, max_range_km integer, engine_type character varying(100), wingspan_m numeric(6,2), status character varying(50) NOT NULL, first_flight_date date, PRIMARY KEY (model_id) )


[User] List all vehicles and their last maintenance service date along with the odometer reading, including only those that have not had a fuel refill in the past 30 days.

[Assistant]
SELECT m.vehicle_id,
       m.last_service_date,
       m.last_odometer
FROM (
  SELECT l.vehicle_id,
         MAX(l.service_date) AS last_service_date,
         (SELECT odometer_reading
          FROM transportation.maintenance_logs
          WHERE vehicle_id = l.vehicle_id
          ORDER BY service_date DESC
          LIMIT 1) AS last_odometer
  FROM transportation.maintenance_logs l
  GROUP BY l.vehicle_id
) AS m
LEFT JOIN (
  SELECT fl.vehicle_id,
         MAX(fl.log_timestamp) AS last_fuel_date
  FROM transportation.fuel_logs fl
  GROUP BY fl.vehicle_id
) AS f ON m.vehicle_id = f.vehicle_id
WHERE COALESCE(f.last_fuel_date, '1900-01-01'::timestamp) < NOW() - 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.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )


[User] I want to list each public post along with its content, the author's username, and the total number of comments it has received. Order the results by comment count descending.

[Assistant]
SELECT p.post_id,
       u.username,
       p.content,
       COUNT(c.comment_id) AS comment_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
WHERE p.visibility = 'public'
GROUP BY p.post_id, u.username, p.content
ORDER BY comment_count DESC;

[User] Actually, can you filter this to only include posts created after '2024-01-01' that have at least 5 comments?

[Assistant]
SELECT p.post_id,
       u.username,
       p.content,
       COUNT(c.comment_id) AS comment_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
WHERE p.visibility = 'public'
  AND p.created_at > '2024-01-01'
GROUP BY p.post_id, u.username, p.content
HAVING COUNT(c.comment_id) >= 5
ORDER BY comment_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 social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )


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

[Assistant] SELECT status, count(*) FROM government_services.appointments GROUP BY status;

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.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] Show me all pairs of time entries that are associated with the same invoice, including their entry IDs, lawyer IDs, and the shared invoice ID.

[Assistant]
SELECT te1.entry_id AS entry1_id,
       te2.entry_id AS entry2_id,
       te1.lawyer_id,
       te1.invoice_id
FROM legal_services.time_entries te1
JOIN legal_services.time_entries te2
  ON te1.invoice_id = te2.invoice_id
 AND te1.entry_id < te2.entry_id
WHERE te1.invoice_id IS NOT NULL;

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.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)


[User] For each player, show their player_id and the number of unique games they have played sessions on.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Also show the total number of sessions they have played.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Only include players who have played on more than 2 unique games.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.game_sessions
GROUP BY player_id
HAVING COUNT(DISTINCT game_id) > 2;

[User] For each result, include the player's username as well.

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT gs.game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT gs.game_id) > 2;

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, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )


[User] Find all pairs of achievement unlocks and item acquisitions by the same player where the item was acquired after the achievement was unlocked. List player_id, achievement_id, unlocked_at, item_id, and acquired_at.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at;

[User] Only include pairs where the item acquisition happened within 24 hours after the achievement unlock.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at AND pi.acquired_at <= pa.unlocked_at + INTERVAL '24 hours';

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.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )


[User] Calculate the total billable hours spent by each lawyer for entries in March 2024.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2024-03-01' AND '2024-03-31'
GROUP BY lawyer_id;


[User] Count the number of logs for each action type.

[Assistant]
SELECT action,
       COUNT(*) AS count
FROM trading_platform.logs
GROUP BY action;

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.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )


[User] For each premium payment, list all previous payments made by the same customer. Show customer_id, previous_payment_id, previous_payment_date, current_payment_id, current_payment_date, and amount difference.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS previous_payment_id,
       p1.payment_date AS previous_payment_date,
       p2.payment_id AS current_payment_id,
       p2.payment_date AS current_payment_date,
       p2.amount_paid - p1.amount_paid AS amount_diff
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
  AND p1.payment_date < p2.payment_date;

[User] Actually, only include pairs where the current payment date is in 2024.

[Assistant]
SELECT p1.customer_id,
       p1.payment_id AS previous_payment_id,
       p1.payment_date AS previous_payment_date,
       p2.payment_id AS current_payment_id,
       p2.payment_date AS current_payment_date,
       p2.amount_paid - p1.amount_paid AS amount_diff
FROM insurance.premium_payments p1
JOIN insurance.premium_payments p2
  ON p1.customer_id = p2.customer_id
  AND p1.payment_date < p2.payment_date
WHERE p2.payment_date BETWEEN '2024-01-01' AND '2024-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 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 )


[User] For each user, show their user ID and the count of unique wallet addresses they own.

[Assistant] SELECT user_id, COUNT(DISTINCT address) FROM wallets GROUP BY user_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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )


[User] For each employee, show their first name, last name, and the total payment amount for applications they have been assigned to process.

[Assistant]
SELECT e.first_name, e.last_name, SUM(p.amount) AS total_payment_amount
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
JOIN government_services.payments p ON a.application_id = p.application_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Only consider payments with status 'Succeeded' and made after January 1, 2024.

[Assistant]
SELECT e.first_name, e.last_name, SUM(p.amount) AS total_payment_amount
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
JOIN government_services.payments p ON a.application_id = p.application_id
WHERE p.status = 'Succeeded'
  AND p.payment_timestamp > '2024-01-01'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] I got an error: missing column 'amount' in select list.

[Assistant]
SELECT e.first_name, e.last_name, COALESCE(SUM(p.amount), 0) AS total_payment_amount
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
LEFT JOIN government_services.payments p ON a.application_id = p.application_id AND p.status = 'Succeeded' AND p.payment_timestamp > '2024-01-01'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Instead of total payment, show the average payment amount per application for each employee.

[Assistant]
SELECT e.first_name, e.last_name, AVG(sub.app_payment_amount) AS avg_payment_per_application
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
LEFT JOIN (
    SELECT application_id, SUM(amount) AS app_payment_amount
    FROM government_services.payments
    WHERE status = 'Succeeded' AND payment_timestamp > '2024-01-01'
    GROUP BY application_id
) sub ON a.application_id = sub.application_id
GROUP BY e.employee_id, e.first_name, e.last_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 government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Show the names of all agencies and the names of their associated service locations.

[Assistant] SELECT T1.agency_name ,  T2.location_name FROM government_services.agencies AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id  =  T2.agency_id

[User] Only include locations in the state of 'Texas' and agencies established after 2020.

[Assistant] SELECT T1.agency_name ,  T2.location_name FROM government_services.agencies AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id  =  T2.agency_id WHERE T2.state  =  'Texas' AND T1.established_date  >  '2020-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 government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text, 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 text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] I need to find pairs of servers that host the same game but are deployed in different regions. Can you write a SQL statement for that?

[Assistant]
SELECT s1.game_id, s1.region AS region1, s2.region AS region2, s1.server_name AS server1, s2.server_name AS server2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id
WHERE s1.region <> s2.region;

[User] Also include each server's current_players and max_players in the output.

[Assistant]
SELECT s1.game_id, s1.region AS region1, s2.region AS region2, s1.server_name AS server1, s2.server_name AS server2, s1.current_players AS current1, s1.max_players AS max1, s2.current_players AS current2, s2.max_players AS max2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id
WHERE s1.region <> s2.region;

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


[User] 我想查询所有使用特定材料ID的组件信息，包括组件名称、零件编号和供应商ID，同时还需要获取该材料的名称和规格。

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id';

[User] 如果我想只显示重量大于10公斤的组件，应该怎么修改查询语句？

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10;

[User] 能不能再加上一个条件，只显示关键性等级为'High'的组件？

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10 AND c.criticality_level = 'High';

[User] 最后，请按组件名称的字母顺序对结果进行排序。

[Assistant]
SELECT c.component_id, c.component_name, c.part_number, c.supplier_id, m.material_name, m.specification
FROM manufacturing.components c
JOIN manufacturing.materials m ON c.material_id = m.material_id
WHERE c.material_id = 'specific_material_id' AND c.weight_kg > 10 AND c.criticality_level = 'High'
ORDER BY c.component_name ASC;

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.components (
    component_id character varying(64) NOT NULL, -- unique identifier for the component
    part_number character varying(100) NOT NULL UNIQUE, -- manufacturer-specific part number
    component_name character varying(255) NOT NULL, -- descriptive name (e.g., Landing Gear Strut, Wing Spar)
    description text, -- detailed description
    material_id character varying(64), -- FK linking to the material used
    supplier_id character varying(64), -- FK linking to the supplier
    weight_kg numeric(10,3), -- weight of the component in kg
    cost_usd numeric(12,2), -- cost of the component in USD
    criticality_level character varying(20), -- e.g., 'High', 'Medium', 'Low'
    PRIMARY KEY (component_id)
)
CREATE TABLE manufacturing.materials (
    material_id character varying(64) NOT NULL,  -- unique identifier for the material
    material_name character varying(128) NOT NULL, -- common name (e.g., Titanium Alloy Grade 5, Carbon Fiber Prepreg)
    specification character varying(255), -- specification standard (e.g., AMS 4928)
    description text, -- detailed description of properties
    density_kg_m3 numeric(10, 4), -- density in kg per cubic meter
    tensile_strength_mpa integer, -- tensile strength in Megapascals
    PRIMARY KEY (material_id)
)
CREATE TABLE manufacturing.assembly_lines (
    line_id character varying(64) NOT NULL, -- unique identifier for the assembly line
    line_name character varying(128) NOT NULL, -- name of the line (e.g., Fuselage Assembly Line 1)
    location_building character varying(100), -- building where the line is located
    location_area character varying(100), -- specific area within the building
    aircraft_model_id character varying(64), -- FK to the primary aircraft model built on this line
    capacity_units_per_month integer, -- theoretical maximum output per month
    status character varying(50) NOT NULL, -- e.g., 'Active', 'Maintenance', 'Idle'
    PRIMARY KEY (line_id)
)
CREATE TABLE manufacturing.component_inventory (
    inventory_record_id character varying(64) NOT NULL, -- unique ID for this inventory record/batch
    component_id character varying(64) NOT NULL, -- FK to the component
    quantity integer NOT NULL, -- number of units of this component in stock for this batch
    location_warehouse character varying(100), -- warehouse identifier
    location_bin character varying(100), -- specific bin or shelf location
    received_date timestamp NOT NULL, -- when this batch was received
    expiry_date date, -- expiry date if applicable (e.g., for sealants, adhesives)
    batch_number character varying(100), -- supplier batch number
    last_updated timestamp NOT NULL, -- timestamp of the last update to this record
    PRIMARY KEY (inventory_record_id)
)


[User] Show me all customers (customer_id, first_name, last_name) who have made trades in the last 30 days, along with the total trade amount for each customer, sorted by total trade amount in descending order.

[Assistant] SELECT c.customer_id, c.first_name, c.last_name, SUM(t.total_amount) AS total_trade_amount FROM financial_services.customers c JOIN financial_services.accounts a ON c.customer_id = a.customer_id JOIN financial_services.trades t ON a.account_id = t.account_id WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY c.customer_id, c.first_name, c.last_name ORDER BY total_trade_amount DESC;

[User] Now modify the query to only include trades executed on the 'NYSE' venue and include the trade count for each customer.

[Assistant] SELECT c.customer_id, c.first_name, c.last_name, SUM(t.total_amount) AS total_trade_amount, COUNT(t.trade_id) AS trade_count FROM financial_services.customers c JOIN financial_services.accounts a ON c.customer_id = a.customer_id JOIN financial_services.trades t ON a.account_id = t.account_id WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days' AND t.execution_venue = 'NYSE' GROUP BY c.customer_id, c.first_name, c.last_name ORDER BY total_trade_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.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- hashed social security number (or national ID)
    address text NOT NULL, -- customer's primary address
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL,
    email character varying(128) UNIQUE, -- customer's email address
    phone_number character varying(32),
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of customer record creation
    status character varying(32) NOT NULL, -- e.g., Active, Inactive, Pending Verification
    risk_profile character varying(50), -- e.g., Low, Medium, High
    PRIMARY KEY (customer_id)
)
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades (
    trade_id character varying(64) NOT NULL, -- unique identifier for the trade
    account_id character varying(64) NOT NULL, -- investment account executing the trade
    security_id character varying(64) NOT NULL, -- security being traded
    order_id character varying(64), -- related order ID if applicable
    trade_type character varying(10) NOT NULL, -- 'Buy' or 'Sell'
    quantity numeric(19, 8) NOT NULL, -- number of units traded
    price_per_unit numeric(19, 8) NOT NULL, -- price per unit of the security
    total_amount numeric(19, 4) NOT NULL, -- total value of the trade (quantity * price)
    commission numeric(10, 4), -- commission fee charged for the trade
    trade_timestamp timestamp NOT NULL, -- exact time the trade was executed
    settlement_date date, -- date the trade settles
    status character varying(32) NOT NULL, -- e.g., Executed, Settled, Cancelled
    execution_venue character varying(100), -- where the trade was executed
    PRIMARY KEY (trade_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
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] 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, r.room_type_id, r.num_adults FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_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, r.room_type_id, r.num_adults, r.total_amount, r.check_in_date FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_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, r.room_type_id, r.num_adults, r.total_amount, r.check_in_date FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_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, r.room_type_id, r.num_adults, r.total_amount, r.check_in_date FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_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.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, 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.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )


[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[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' ORDER BY date_opened ASC LIMIT 10;

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] Show the prescription_id, quantity_dispensed, and start_date for all prescriptions where refills_allowed equals 0.

[Assistant]
SELECT prescription_id, quantity_dispensed, start_date
FROM healthcare.prescriptions
WHERE refills_allowed = 0;

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.medications ( medication_id.text, medication_name.text, generic_name.text, manufacturer.text, ndc_code.text, description.text )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )


[User] Which SUI coins have a supply greater than 10,000 and include their symbol and name?

[Assistant] SELECT scm.symbol, scm.name, sc.coin_type, SUM(CAST(sc.balance AS DECIMAL)) AS total_supply FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS DECIMAL) > 10000 GROUP BY scm.symbol, scm.name, sc.coin_type;

[User] Now, also show the total number of unique owners for each coin.

[Assistant] SELECT scm.symbol, scm.name, sc.coin_type, SUM(CAST(sc.balance AS DECIMAL)) AS total_supply, COUNT(DISTINCT sc.owner) AS unique_owners FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS DECIMAL) > 10000 GROUP BY scm.symbol, scm.name, sc.coin_type;

[User] Only include coins where the unique owner count is at least 5.

[Assistant] SELECT scm.symbol, scm.name, sc.coin_type, SUM(CAST(sc.balance AS DECIMAL)) AS total_supply, COUNT(DISTINCT sc.owner) AS unique_owners FROM sui_coins sc JOIN sui_coins_metadata scm ON sc.coin_type = scm.coin_type WHERE CAST(sc.balance AS DECIMAL) > 10000 GROUP BY scm.symbol, scm.name, sc.coin_type HAVING COUNT(DISTINCT sc.owner) >= 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 token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE nft_holders ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.text )
CREATE TABLE nft_holder_historical ( block_number.bigint, contract_address.text, wallet_address.text, token_id.text, contract_type.text, amount.text, pk.integer )
CREATE TABLE sui_coins ( object_id.text, status.text, coin_type.text, balance.text, owner.text )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_metadata ( blockchain.text, contract_address.text, token_id.text, contract_name.text, erc_type.text, amount.bigint, minter.text, owner.text, mint_block_number.bigint, mint_time.bigint, mint_transaction_hash.text, mint_price.text, token_uri.text, metadata.text, name.text, image_uri.text, traits.text, updated_at.bigint, status.text, rarity_score.real, rarity_rank.integer, unique_attribute_count.integer, pk.integer )
CREATE TABLE 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_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address.text, table_id.text, key_bytes.text, key0.text, key1.text, static_data.text, encoded_lengths.text, dynamic_data.text, is_deleted.boolean, block_number.bigint, log_index.bigint )
CREATE TABLE token_balances_bitcoin ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.text, amount.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_activities_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_avalanche ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info_avalanche ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text, minted.decimal, holders.decimal, txs.decimal, updated_timestamp.timestamp, completed_timestamp.timestamp, id.text )


[User] For each chain, find the narrative category that has the highest total market_cap and display the chain, narrative, and that total market_cap.

[Assistant]
SELECT chain,
       narrative,
       total_cap
FROM (
  SELECT chain,
         narrative,
         SUM(market_cap) AS total_cap,
         RANK() OVER (PARTITION BY chain ORDER BY SUM(market_cap) DESC) AS rnk
  FROM token_basic_info
  GROUP BY chain, narrative
) t
WHERE rnk = 1;

[User] I received an error about window functions. Can you rewrite the query without using window functions?

[Assistant]
WITH agg AS (
  SELECT chain,
         narrative,
         SUM(market_cap) AS total_cap
  FROM token_basic_info
  GROUP BY chain, narrative
),
max_cap AS (
  SELECT chain,
         MAX(total_cap) AS max_cap
  FROM agg
  GROUP BY chain
)
SELECT a.chain,
       a.narrative,
       a.total_cap
FROM agg a
JOIN max_cap m
  ON a.chain = m.chain
 AND a.total_cap = m.max_cap;

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


[User] I want to find all pairs of invoices belonging to the same client. Show me the client_id, the invoice_number for the earlier invoice and the invoice_number for the later invoice.

[Assistant]
SELECT i1.client_id,
       i1.invoice_number AS earlier_invoice,
       i2.invoice_number AS later_invoice
FROM legal_services.invoices i1
JOIN legal_services.invoices i2
  ON i1.client_id = i2.client_id
 AND i1.issue_date < i2.issue_date;

[User] Actually, only include pairs where the difference between the two issue dates is no more than 7 days.

[Assistant]
SELECT i1.client_id,
       i1.invoice_number AS earlier_invoice,
       i2.invoice_number AS later_invoice
FROM legal_services.invoices i1
JOIN legal_services.invoices i2
  ON i1.client_id = i2.client_id
 AND i1.issue_date < i2.issue_date
 AND i2.issue_date - i1.issue_date <= INTERVAL '7 days';

[User] Also, only keep pairs where both invoices are unpaid (amount_paid < total_amount).

[Assistant]
SELECT i1.client_id,
       i1.invoice_number AS earlier_invoice,
       i2.invoice_number AS later_invoice
FROM legal_services.invoices i1
JOIN legal_services.invoices i2
  ON i1.client_id = i2.client_id
 AND i1.issue_date < i2.issue_date
 AND i2.issue_date - i1.issue_date <= INTERVAL '7 days'
WHERE i1.amount_paid < i1.total_amount
  AND i2.amount_paid < i2.total_amount;

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.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )


[User] Show the name of beneficiaries and the policy number for policies that are of product type 'life'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.policy_number FROM insurance.policy_beneficiaries AS T1 JOIN insurance.policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'life';

[User] Can you also include the beneficiary's percentage share and only show results for active policies?

[Assistant] SELECT T1.first_name, T1.last_name, T1.percentage_share, T2.policy_number FROM insurance.policy_beneficiaries AS T1 JOIN insurance.policies AS T2 ON T1.policy_id = T2.policy_id JOIN insurance.insurance_products AS T3 ON T2.product_id = T3.product_id WHERE T3.product_type = 'life' AND T2.status = 'active';

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.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
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.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.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] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 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 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 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 text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
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 )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )


[User] List the first and last names, email, and loyalty program ID of all passengers who joined after January 1, 2024.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01';

[User] Include only those passengers who are enrolled in any loyalty program (loyalty_program_id is not null), and order the results by last name.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01' AND loyalty_program_id IS NOT NULL
ORDER BY last_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 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.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )


[User] How many hashtags are associated with each post? Return post_id and alias it as hashtag_count, but only show posts with more than one hashtag.

[Assistant]
SELECT post_id, COUNT(*) AS hashtag_count
FROM social_media.post_hashtags
GROUP BY post_id
HAVING COUNT(*) > 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 social_media.post_hashtags ( post_hashtag_id.text, post_id.text, hashtag_id.text )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )


[User] List all token transfers, showing the transfer ID, value, and the symbol of the token transferred.

[Assistant] SELECT T1.transfer_id, T1.value, T2.token_symbol FROM web3.token_transfers AS T1 JOIN web3.tokens AS T2 ON T1.token_id = T2.token_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 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 )


[User] List all transaction IDs that contain at least one UTXO marked as spent.

[Assistant] SELECT DISTINCT transaction_id FROM utxos WHERE spent = TRUE;

[User] Now, for those transaction IDs, also include the total count of spent UTXOs they contain.

[Assistant] SELECT transaction_id, COUNT(*) FROM utxos WHERE spent = TRUE GROUP BY transaction_id;

[User] Actually, I only want transaction IDs that have exactly one spent UTXO. Show the ID and the count (which should be 1).

[Assistant] SELECT transaction_id, COUNT(*) FROM utxos WHERE spent = TRUE GROUP BY transaction_id HAVING COUNT(*) = 1;

[User] Instead of listing them, just tell me how many transaction IDs meet that criteria (have exactly one spent UTXO).

[Assistant] SELECT COUNT(*) FROM (SELECT transaction_id FROM utxos WHERE spent = TRUE GROUP BY transaction_id HAVING COUNT(*) = 1) AS subquery;

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


[User] Show me all agents and their managers' full names. For each agent, include agent_id, agent's first and last name, and their manager's first and last name.

[Assistant]
SELECT a.agent_id, a.first_name AS agent_first_name, a.last_name AS agent_last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id;

[User] Add the agency name and license state of each agent as well.

[Assistant]
SELECT a.agent_id, a.first_name AS agent_first_name, a.last_name AS agent_last_name, a.agency_name, a.license_state, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id;

[User] Actually, only show agents whose managers are currently active.

[Assistant]
SELECT a.agent_id, a.first_name AS agent_first_name, a.last_name AS agent_last_name, a.agency_name, a.license_state, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE m.status = 'active';

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


[User] What is the total commission earned from all trades executed in the 'NYSE' venue by employees in the 'Trading' department?

[Assistant] SELECT SUM(t.commission) AS total_commission FROM financial_services.trades t JOIN financial_services.employees e ON t.account_id = e.employee_id WHERE t.execution_venue = 'NYSE' AND e.department = 'Trading';

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.trades ( trade_id.text, account_id.text, security_id.text, order_id.text, trade_type.text, quantity.numeric, price_per_unit.numeric, total_amount.numeric, commission.numeric, trade_timestamp.timestamp, settlement_date.date, status.text, execution_venue.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )