[User] List all patients who have been prescribed medications with dosage greater than 50mg, along with their medication details and prescribing doctor's name.

[Assistant] SELECT p.first_name, p.last_name, pr.dosage, pr.medication_id, pr.frequency, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id WHERE pr.dosage LIKE '%50mg%' OR pr.dosage LIKE '%>50%' OR CAST(SUBSTRING(pr.dosage FROM '[0-9]+') AS INTEGER) > 50;

[User] Actually, I need to see only prescriptions that were issued in the last 3 months.

[Assistant] SELECT p.first_name, p.last_name, pr.dosage, pr.medication_id, pr.frequency, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id WHERE (pr.dosage LIKE '%50mg%' OR pr.dosage LIKE '%>50%' OR CAST(SUBSTRING(pr.dosage FROM '[0-9]+') AS INTEGER) > 50) AND pr.prescription_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Can you also include the prescription start date and end date in the results?

[Assistant] SELECT p.first_name, p.last_name, pr.dosage, pr.medication_id, pr.frequency, pr.start_date, pr.end_date, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name FROM healthcare.patients p JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id JOIN healthcare.doctors d ON pr.doctor_id = d.doctor_id WHERE (pr.dosage LIKE '%50mg%' OR pr.dosage LIKE '%>50%' OR CAST(SUBSTRING(pr.dosage FROM '[0-9]+') AS INTEGER) > 50) AND pr.prescription_date >= CURRENT_DATE - INTERVAL '3 months';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )


[User] For each asset, I want to know how many orders have the status 'filled', showing the asset symbol.

[Assistant]
SELECT m.value AS asset_symbol,
       COUNT(*) AS filled_order_count
FROM trading_platform.orders o
JOIN trading_platform.metadata m
  ON o.asset_id = m.asset_id
 AND m.key = 'symbol'
WHERE o.status = 'filled'
GROUP BY m.value;

[User] Include assets that have zero filled orders, showing filled_order_count as 0.

[Assistant]
WITH asset_symbols AS (
  SELECT DISTINCT asset_id,
         value AS asset_symbol
  FROM trading_platform.metadata
  WHERE key = 'symbol'
)
SELECT a.asset_symbol,
       COALESCE(f.filled_order_count, 0) AS filled_order_count
FROM asset_symbols a
LEFT JOIN (
  SELECT asset_id,
         COUNT(*) AS filled_order_count
  FROM trading_platform.orders
  WHERE status = 'filled'
  GROUP BY asset_id
) f
  ON a.asset_id = f.asset_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.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)


[User] What is the performance review score for employee with ID 'EMP456' for the last quarter?

[Assistant] I'm sorry, but I can't assist with information about performance review scores as this data is not included in the employees table.

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.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(128) NOT NULL, skill_certifications text, hire_date date NOT NULL, assigned_line_id character varying(64), employment_status character varying(50) NOT NULL, supervisor_employee_id character varying(64), PRIMARY KEY (employee_id) )


[User] List all insurance products that have no active policies currently.

[Assistant] SELECT ip.product_id, ip.product_name, ip.product_type FROM insurance.insurance_products ip LEFT JOIN insurance.policies p ON ip.product_id = p.product_id AND p.status = 'Active' WHERE p.policy_id IS NULL AND ip.is_active = true;

[User] Now include only products that were created in the last year.

[Assistant] SELECT ip.product_id, ip.product_name, ip.product_type FROM insurance.insurance_products ip LEFT JOIN insurance.policies p ON ip.product_id = p.product_id AND p.status = 'Active' WHERE p.policy_id IS NULL AND ip.is_active = true AND ip.created_at >= CURRENT_DATE - INTERVAL '1 year';

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 character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), 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 DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] For each employee who has verified more than one document, list their employee ID, the first document they verified, and the next document they verified, along with both verification timestamps.

[Assistant]
SELECT
  d1.verified_by_employee_id AS employee_id,
  d1.document_id AS first_verified_document,
  d1.verification_timestamp AS first_verification_time,
  d2.document_id AS next_verified_document,
  d2.verification_timestamp AS next_verification_time
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.verified_by_employee_id = d2.verified_by_employee_id
  AND d2.verification_timestamp > d1.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';

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.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )


[User] For each chain, which centralized exchange holds the largest total USD value in their token balance as of the most recent snapshot?

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

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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp chain character varying(128) NOT NULL, -- the chain that the token resides address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX exchange character varying(512) NOT NULL, -- a centralized exchange name token_address character varying(128) NOT NULL, -- token contract address token_symbol character varying(512), --token symbol balance numeric(38,10), -- token balance usd_value numeric(38,14), -- value of the token held in USD price double precision, --price of the token in USD ,PRIMARY KEY (snapshot_time, exchange, address, chain, token_address) )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )


[User] List the full name of patients whose primary insurance plan is provided by 'BlueCross BlueShield', along with the plan name.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield';

[User] Only include policies that have not expired.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield' AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE);

[User] Also include the policy number and filter to policies effective after '2023-01-01'.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name, T2.policy_number FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield' AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND T2.effective_date > '2023-01-01';

[User] Finally, order the results by the patient's last name and then first name.

[Assistant] SELECT T1.first_name, T1.last_name, T3.plan_name, T2.policy_number FROM healthcare.patients AS T1 JOIN healthcare.patient_insurance AS T2 ON T1.patient_id = T2.patient_id JOIN healthcare.insurance_plans AS T3 ON T2.plan_id = T3.plan_id WHERE T2.is_primary = TRUE AND T3.insurance_provider = 'BlueCross BlueShield' AND (T2.expiration_date IS NULL OR T2.expiration_date > CURRENT_DATE) AND T2.effective_date > '2023-01-01' ORDER BY T1.last_name, T1.first_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] How many trips are there for each driver?

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

[User] Can you also show the total number of completed trips for each driver?

[Assistant] SELECT driver_id, COUNT(*) AS completed_trip_count FROM transportation.trips WHERE status = 'Completed' GROUP BY driver_id;

[User] Now, include both the total trips and completed trips for each driver in the same result.

[Assistant] SELECT driver_id, COUNT(*) AS total_trips, SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) AS completed_trips FROM transportation.trips GROUP BY driver_id;

[User] Sort the output by the number of completed trips in descending order.

[Assistant] SELECT driver_id, COUNT(*) AS total_trips, SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) AS completed_trips FROM transportation.trips GROUP BY driver_id ORDER BY completed_trips 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.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)
)


[User] Which NFTs minted in the past 14 days on Ethereum have a rarity_score above 70? For each, show contract address, token ID, name, and minter.

[Assistant]
SELECT contract_address, token_id, name, minter
FROM nft_metadata
WHERE blockchain = 'Ethereum'
  AND mint_time >= (extract(epoch from now()) - 14*24*60*60)
  AND rarity_score > 70;

[User] For these NFTs, can you also include the collection name and symbol by joining with the nft_collections table?

[Assistant]
SELECT nm.contract_address, nm.token_id, nm.name, nm.minter, nc.name AS collection_name, nc.symbol
FROM nft_metadata nm
JOIN nft_collections nc
  ON nm.blockchain = nc.blockchain AND nm.contract_address = nc.contract_address
WHERE nm.blockchain = 'Ethereum'
  AND nm.mint_time >= (extract(epoch from now()) - 14*24*60*60)
  AND nm.rarity_score > 70;

[User] Can you filter only those collections where the erc_type is 'ERC1155'?

[Assistant]
SELECT nm.contract_address, nm.token_id, nm.name, nm.minter, nc.name AS collection_name, nc.symbol
FROM nft_metadata nm
JOIN nft_collections nc
  ON nm.blockchain = nc.blockchain AND nm.contract_address = nc.contract_address
WHERE nm.blockchain = 'Ethereum'
  AND nm.mint_time >= (extract(epoch from now()) - 14*24*60*60)
  AND nm.rarity_score > 70
  AND nc.erc_type = 'ERC1155';

[User] Now, also include the owner for each NFT, and order the results by rarity_rank ascending.

[Assistant]
SELECT nm.contract_address, nm.token_id, nm.name, nm.minter, nm.owner, nc.name AS collection_name, nc.symbol
FROM nft_metadata nm
JOIN nft_collections nc
  ON nm.blockchain = nc.blockchain AND nm.contract_address = nc.contract_address
WHERE nm.blockchain = 'Ethereum'
  AND nm.mint_time >= (extract(epoch from now()) - 14*24*60*60)
  AND nm.rarity_score > 70
  AND nc.erc_type = 'ERC1155'
ORDER BY nm.rarity_rank ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
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 varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
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 varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    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 NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    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)
)
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_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)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )


[User] List all documents uploaded for cases handled in the 'District Court' jurisdiction, showing the document name, case number, and upload timestamp.

[Assistant]
SELECT d.document_name, cs.case_number, d.upload_timestamp
FROM legal_services.documents d
JOIN legal_services.cases cs ON d.case_id = cs.case_id
WHERE cs.court_jurisdiction = 'District Court';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_id)
)
CREATE TABLE legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
CREATE TABLE legal_services.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)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] For each achievement, show its name, the game_id it belongs to, and the number of distinct players who have played a session for that game.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id;

[User] Now, filter to only include achievements for games that have at least 50 players who have played a session.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] Please also include the number of times each achievement has been unlocked by unique players, labeled as unique_unlocks.

[Assistant]
SELECT a.name, a.game_id, COUNT(DISTINCT gs.player_id) AS players_with_sessions,
       (SELECT COUNT(DISTINCT gs2.player_id)
        FROM gaming_technology.game_sessions gs2
        WHERE gs2.game_id = a.game_id) AS unique_unlocks
FROM gaming_technology.achievements a
LEFT JOIN gaming_technology.game_sessions gs ON a.game_id = gs.game_id
GROUP BY a.achievement_id, a.name, a.game_id
HAVING COUNT(DISTINCT gs.player_id) >= 50;

[User] I think unique_unlocks should be the count of distinct players who have unlocked each specific achievement, not just played a session. Can you correct that?

[Assistant] -- With the provided tables, there is no direct record of players unlocking a specific achievement, unless unlocking is inferred elsewhere. If you have an achievement unlocks table, you could join it here. Otherwise, only possible to count sessions per game.

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.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] Which wallet addresses currently hold at least 2 different ERC721 NFTs on Ethereum? Show each wallet address and the count of distinct token_ids.

[Assistant]
SELECT nh.wallet_address, COUNT(DISTINCT nh.token_id) AS distinct_token_count
FROM nft_holders nh
WHERE nh.contract_type = 'ERC721'
  AND nh.amount > '0'
  AND nh.contract_address IN (
    SELECT contract_address FROM nft_collections WHERE blockchain = 'Ethereum'
  )
GROUP BY nh.wallet_address
HAVING COUNT(DISTINCT nh.token_id) >= 2;

[User] Can you also show the collection name for these NFTs by joining with nft_collections?

[Assistant]
SELECT nh.wallet_address, nh.contract_address, nc.name AS collection_name, COUNT(DISTINCT nh.token_id) AS distinct_token_count
FROM nft_holders nh
JOIN nft_collections nc ON nh.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum'
WHERE nh.contract_type = 'ERC721' AND nh.amount > '0'
GROUP BY nh.wallet_address, nh.contract_address, nc.name
HAVING COUNT(DISTINCT nh.token_id) >= 2;

[User] Only include wallets holding more than 5 NFTs from a given collection, and order the results by distinct_token_count descending.

[Assistant]
SELECT nh.wallet_address, nh.contract_address, nc.name AS collection_name, COUNT(DISTINCT nh.token_id) AS distinct_token_count
FROM nft_holders nh
JOIN nft_collections nc ON nh.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum'
WHERE nh.contract_type = 'ERC721' AND nh.amount > '0'
GROUP BY nh.wallet_address, nh.contract_address, nc.name
HAVING COUNT(DISTINCT nh.token_id) > 5
ORDER BY distinct_token_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 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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
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 varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
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 varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    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 NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    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)
)
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
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_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(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)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)


[User] List all pairs of contracts deployed on the same day by the same deployer. Show deployer_address, deployment date, and both contract IDs.

[Assistant]
SELECT
  c1.deployer_address,
  DATE(c1.deployed_at) AS deployment_date,
  c1.contract_id AS contract_id_1,
  c2.contract_id AS contract_id_2
FROM web3.contracts c1
JOIN web3.contracts c2
  ON c1.deployer_address = c2.deployer_address
  AND DATE(c1.deployed_at) = DATE(c2.deployed_at)
  AND c1.contract_id < c2.contract_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.contracts (
    contract_id character varying(64) NOT NULL,  -- unique identifier for the contract
    address character varying(128) NOT NULL, -- address of the deployed contract
    abi text NOT NULL, -- application binary interface of the contract
    bytecode text NOT NULL, -- bytecode of the contract
    deployer_address character varying(128) NOT NULL, -- address of the deployer
    deployed_at timestamp NOT NULL, -- time when the contract was deployed
    network_id character varying(64) NOT NULL, -- identifier of the network where the contract is deployed
    status character varying(32) NOT NULL, -- status of the contract (e.g., active, deprecated)
    PRIMARY KEY (contract_id)
)


[User] Show me claim IDs, incident dates, and file names for all 'Accident Report' claim documents.

[Assistant]
SELECT cd.claim_id, cl.incident_date, cd.file_name
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type = 'Accident Report';

[User] Include both 'Accident Report' and 'Theft Report' document types.

[Assistant]
SELECT cd.claim_id, cl.incident_date, cd.file_name
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type IN ('Accident Report','Theft Report');

[User] Instead of listing each file, show the number of these documents per claim.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type IN ('Accident Report','Theft Report')
GROUP BY cd.claim_id;

[User] Also restrict to claims reported in 2024 and order by document_count descending.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims cl ON cd.claim_id = cl.claim_id
WHERE cd.document_type IN ('Accident Report','Theft Report')
  AND EXTRACT(YEAR FROM cl.reported_date) = 2024
GROUP BY cd.claim_id
ORDER BY document_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, 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 PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Get name pairs of achievements for each game where one is hidden and the other is visible.

[Assistant]
SELECT a.achievement_id AS hidden_achievement_id, a.name AS hidden_name, b.achievement_id AS visible_achievement_id, b.name AS visible_name
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = true
  AND b.hidden = false;

[User] Include the game_id at the start of each row and order the results by game_id.

[Assistant]
SELECT a.game_id, a.achievement_id AS hidden_achievement_id, a.name AS hidden_name, b.achievement_id AS visible_achievement_id, b.name AS visible_name
FROM gaming_technology.achievements a
JOIN gaming_technology.achievements b
  ON a.game_id = b.game_id
  AND a.hidden = true
  AND b.hidden = false
ORDER BY a.game_id ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )


[User] Show me the name and type for all the locations.

[Assistant] SELECT name, type FROM transportation.locations

[User] Now, filter this list to only include locations whose type is either 'Distribution Center' or 'Warehouse'.

[Assistant] SELECT name, type FROM transportation.locations WHERE type IN ('Distribution Center', 'Warehouse')

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


[User] Show all appointments with subject containing 'Review' and their corresponding case_id.

[Assistant]
SELECT appointment_id, subject, case_id
FROM legal_services.appointments
WHERE subject ILIKE '%Review%';

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 )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )


[User] How many events were emitted on each date? List the date and the count of events.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at);

[User] Actually, only include dates where more than 10 events were emitted.

[Assistant]
SELECT DATE(emitted_at) AS emit_date,
       COUNT(*) AS event_count
FROM web3.events
GROUP BY DATE(emitted_at)
HAVING COUNT(*) > 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 web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )


[User] Show me the top 5 ERC20 tokens with the highest total supply, along with their names and contract addresses, but only include tokens with decimals equal to 18.

[Assistant] SELECT name, contract_address, total_supply FROM token_metas WHERE is_erc20 = 1 AND decimals = 18 ORDER BY CAST(total_supply AS decimal) DESC LIMIT 5;

[User] Can you join this with the token_prices table to include the current price of each token?

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, tp.price FROM token_metas tm JOIN token_prices tp ON tm.contract_address = tp.address WHERE tm.is_erc20 = 1 AND tm.decimals = 18 ORDER BY CAST(tm.total_supply AS decimal) DESC LIMIT 5;

[User] Now filter these results to only show tokens where the price is greater than $0.1.

[Assistant] SELECT tm.name, tm.contract_address, tm.total_supply, tp.price FROM token_metas tm JOIN token_prices tp ON tm.contract_address = tp.address WHERE tm.is_erc20 = 1 AND tm.decimals = 18 AND tp.price > 0.1 ORDER BY CAST(tm.total_supply AS decimal) 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 token_metas ( block_timestamp timestamp(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
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 NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
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 varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
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 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 erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE 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 varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_info_bitcoin (
    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(255) 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)
)
CREATE TABLE token_activities_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)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)
CREATE TABLE token_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)


[User] Show the usernames of users who have used any hashtag in their posts, along with the tag name.

[Assistant] SELECT DISTINCT T1.username, T4.tag_name FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id JOIN hashtags AS T4 ON T3.hashtag_id = T4.hashtag_id;

[User] Only include users who have used hashtags more than 3 times across all their posts.

[Assistant] SELECT T1.username, COUNT(T3.hashtag_id) AS hashtag_usage_count FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id GROUP BY T1.username HAVING COUNT(T3.hashtag_id) > 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, 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 bool )


[User] List the appointment ID, start time, and the case number for all appointments that are linked to a case.

[Assistant] SELECT T1.appointment_id, T1.start_time, T2.case_number FROM legal_services.appointments AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id

[User] Refine this to only show appointments with status 'completed' associated with cases with status 'Closed'.

[Assistant] SELECT T1.appointment_id, T1.start_time, T2.case_number FROM legal_services.appointments AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'completed' AND T2.status = 'Closed'

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 )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )


[User] List the number of bookings for each day.

[Assistant]
SELECT DATE(booking_time) AS booking_date, COUNT(*) AS booking_count
FROM transportation.bookings
GROUP BY DATE(booking_time);

[User] Now only include days where booking_count > 10.

[Assistant]
SELECT DATE(booking_time) AS booking_date, COUNT(*) AS booking_count
FROM transportation.bookings
GROUP BY DATE(booking_time)
HAVING COUNT(*) > 10;

[User] Also include the total fare collected for those days.

[Assistant]
SELECT DATE(booking_time) AS booking_date,
       COUNT(*) AS booking_count,
       SUM(fare) AS total_fare
FROM transportation.bookings
GROUP BY DATE(booking_time)
HAVING COUNT(*) > 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 transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] I need to find pairs of players who share the same email domain. For each pair, return player1_id, player2_id, and the shared domain.

[Assistant]
SELECT p1.player_id AS player1_id,
       p2.player_id AS player2_id,
       LOWER(SPLIT_PART(p1.email, '@', 2)) AS domain
FROM gaming_technology.players p1
JOIN gaming_technology.players p2
  ON LOWER(SPLIT_PART(p1.email, '@', 2)) = LOWER(SPLIT_PART(p2.email, '@', 2));

[User] Actually, I only want each combination once, so ensure player1_id is always less than player2_id.

[Assistant]
SELECT p1.player_id AS player1_id,
       p2.player_id AS player2_id,
       LOWER(SPLIT_PART(p1.email, '@', 2)) AS domain
FROM gaming_technology.players p1
JOIN gaming_technology.players p2
  ON LOWER(SPLIT_PART(p1.email, '@', 2)) = LOWER(SPLIT_PART(p2.email, '@', 2))
WHERE p1.player_id < p2.player_id;

[User] Also exclude any domain that appears only once among all players.

[Assistant]
SELECT p1.player_id AS player1_id,
       p2.player_id AS player2_id,
       d.domain
FROM (
  SELECT LOWER(SPLIT_PART(email, '@', 2)) AS domain
  FROM gaming_technology.players
  GROUP BY domain
  HAVING COUNT(*) > 1
) d
JOIN gaming_technology.players p1
  ON LOWER(SPLIT_PART(p1.email, '@', 2)) = d.domain
JOIN gaming_technology.players p2
  ON LOWER(SPLIT_PART(p2.email, '@', 2)) = d.domain
WHERE p1.player_id < p2.player_id;

[User] Finally, order the results by domain ascending and then by player1_id.

[Assistant]
SELECT p1.player_id AS player1_id,
       p2.player_id AS player2_id,
       d.domain
FROM (
  SELECT LOWER(SPLIT_PART(email, '@', 2)) AS domain
  FROM gaming_technology.players
  GROUP BY domain
  HAVING COUNT(*) > 1
) d
JOIN gaming_technology.players p1
  ON LOWER(SPLIT_PART(p1.email, '@', 2)) = d.domain
JOIN gaming_technology.players p2
  ON LOWER(SPLIT_PART(p2.email, '@', 2)) = d.domain
WHERE p1.player_id < p2.player_id
ORDER BY d.domain ASC, p1.player_id ASC;

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


[User] What is the total transaction amount for each transaction_type in the last 30 days?

[Assistant] SELECT transaction_type, SUM(amount) AS total_amount FROM financial_services.transactions WHERE transaction_date >= CURRENT_DATE - INTERVAL '30 days' GROUP BY transaction_type;

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, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address text NOT NULL, 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, phone_number character varying(32), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, status character varying(32) NOT NULL, risk_profile character varying(50), PRIMARY KEY (customer_id) )
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
CREATE TABLE financial_services.transactions ( transaction_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, related_account_id character varying(64), transaction_type character varying(50) NOT NULL, amount numeric(19, 4) NOT NULL, currency character varying(3) NOT NULL, transaction_date timestamp NOT NULL, effective_date date NOT NULL, description text, status character varying(32) NOT NULL, reference_number character varying(128), PRIMARY KEY (transaction_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id) )
CREATE TABLE financial_services.securities ( security_id character varying(64) NOT NULL, ticker_symbol character varying(20) NOT NULL UNIQUE, isin_code character varying(12) UNIQUE, cusip_code character varying(9) UNIQUE, security_name text NOT NULL, security_type character varying(50) NOT NULL, exchange character varying(50), currency character varying(3) NOT NULL, issuer_name character varying(255), sector character varying(100), last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (security_id) )
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )


[User] 特定の職種の従業員情報を取得したいです。従業員ID、名前、職種、雇用日を表示してください。

[Assistant]
db.employees.find(
    { job_title: '<specific_job_title>' },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用日が2020年1月1日以降の従業員だけに絞り込むことはできますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') }
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用ステータスが「Active」の従業員だけをさらに条件に加えられますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] スキル認定情報も結果に含めてください。

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, skill_certifications: 1, _id: 0 }
).sort({ hire_date: -1 })

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.


[User] Retrieve each agency’s name along with the count of accessible service locations it has in California.

[Assistant]
SELECT
  a.agency_name,
  COUNT(l.location_id) AS accessible_location_count
FROM government_services.agencies a
JOIN government_services.service_locations l
  ON a.agency_id = l.agency_id
WHERE l.is_accessible = TRUE
  AND l.state = 'California'
GROUP BY a.agency_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.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, 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.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, 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.service_locations ( location_id text PRIMARY KEY, 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 PRIMARY KEY, 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 PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Show me the average transaction amount per block, along with the block_id and the count of transactions in each block.

[Assistant] SELECT block_id, AVG(amount) as avg_amount, COUNT(*) as transaction_count FROM blockchain.transactions WHERE block_id IS NOT NULL GROUP BY block_id;

[User] Now filter this to only show blocks that have more than 5 transactions and an average amount greater than 500.

[Assistant] SELECT block_id, AVG(amount) as avg_amount, COUNT(*) as transaction_count FROM blockchain.transactions WHERE block_id IS NOT NULL GROUP BY block_id HAVING COUNT(*) > 5 AND AVG(amount) > 500;

[User] Can you also include the earliest and latest transaction timestamps for each of these blocks?

[Assistant] SELECT block_id, AVG(amount) as avg_amount, COUNT(*) as transaction_count, MIN(timestamp) as earliest_tx, MAX(timestamp) as latest_tx FROM blockchain.transactions WHERE block_id IS NOT NULL GROUP BY block_id HAVING COUNT(*) > 5 AND AVG(amount) > 500;

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 blockchain.transactions ( transaction_id text PRIMARY KEY, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )


[User] Display each product alongside the most recently updated product of the same type. Return original_id, original_updated_at, recent_id, recent_updated_at, and product_type.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products GROUP BY product_type) m ON p.product_type = m.product_type JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated;

[User] Actually, exclude entries where original or recent updated_at is null.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products WHERE updated_at IS NOT NULL GROUP BY product_type) m ON p.product_type = m.product_type AND p.updated_at IS NOT NULL JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated;

[User] Also, only include product types that have more than 2 products.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products WHERE updated_at IS NOT NULL GROUP BY product_type) m ON p.product_type = m.product_type AND p.updated_at IS NOT NULL JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated WHERE p.product_type IN (SELECT product_type FROM insurance.insurance_products GROUP BY product_type HAVING COUNT(*) > 2);

[User] Finally, sort the results by recent_updated_at descending.

[Assistant] SELECT p.product_id AS original_id, p.updated_at AS original_updated_at, r.product_id AS recent_id, r.updated_at AS recent_updated_at, p.product_type FROM insurance.insurance_products p JOIN (SELECT product_type, MAX(updated_at) AS max_updated FROM insurance.insurance_products WHERE updated_at IS NOT NULL GROUP BY product_type) m ON p.product_type = m.product_type AND p.updated_at IS NOT NULL JOIN insurance.insurance_products r ON r.product_type = p.product_type AND r.updated_at = m.max_updated WHERE p.product_type IN (SELECT product_type FROM insurance.insurance_products GROUP BY product_type HAVING COUNT(*) > 2) ORDER BY recent_updated_at DESC;

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


[User] List all patients who do not have an email address on file, showing their patient_id, first_name, last_name, and phone_number.

[Assistant]
SELECT patient_id,
       first_name,
       last_name,
       phone_number
FROM healthcare.patients
WHERE email IS 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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )


[User] List the full names of customers along with the count of their active policies, but only include those customers with at least 3 active policies.

[Assistant]
SELECT c.first_name, c.last_name, COUNT(p.policy_id) AS active_policy_count
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.status = 'Active'
GROUP BY c.first_name, c.last_name
HAVING COUNT(p.policy_id) >= 3;


[User] I need the average close_price per sector for the last month.

[Assistant]
SELECT s.sector, AVG(m.close_price) AS avg_close_price
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Can you also include the maximum volume per sector?

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
GROUP BY s.sector;

[User] Now I only want data from source 'Reuters'.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector;

[User] Finally, only include sectors with total volume over 1000000 and order by avg_close_price descending.

[Assistant]
SELECT s.sector,
       AVG(m.close_price)    AS avg_close_price,
       MAX(m.volume)         AS max_volume
FROM financial_services.market_data m
JOIN financial_services.securities s ON m.security_id = s.security_id
WHERE m.data_timestamp >= date_trunc('month', current_date) - interval '1 month'
  AND m.data_timestamp < date_trunc('month', current_date)
  AND m.source = 'Reuters'
GROUP BY s.sector
HAVING SUM(m.volume) > 1000000
ORDER BY avg_close_price 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.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 is the fuel consumption rate of train number T1234?

[Assistant] I'm sorry, but I don't have information on the fuel consumption rate of train number T1234. The data available in the system only includes details such as train ID, model, manufacturer, year manufactured, capacity, status, and maintenance dates.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id character varying(64) NOT NULL, train_number character varying(32) NOT NULL, model character varying(128), manufacturer character varying(128), year_manufactured integer, capacity integer NOT NULL, status character varying(32) NOT NULL DEFAULT 'Active', last_maintenance_date date, next_maintenance_date date, PRIMARY KEY (train_id), UNIQUE (train_number) )


[User] Find all users who have deployed contracts, along with their email addresses and the count of contracts they've deployed, sorted by contract count in descending order.

[Assistant] SELECT u.username, u.email, COUNT(c.contract_id) AS contract_count FROM web3.users u JOIN web3.contracts c ON u.user_id = c.deployer_address GROUP BY u.username, u.email ORDER BY contract_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 web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] Show me a list of all cases and include the case number, case name, and the court jurisdiction for each case, as well as the lead lawyer's ID and the case status.

[Assistant] SELECT case_number, case_name, court_jurisdiction, lead_lawyer_id, status FROM legal_services.cases;

[User] Can you only show cases where the court_jurisdiction is not null and the status is either 'Pending' or 'Open'?

[Assistant] SELECT case_number, case_name, court_jurisdiction, lead_lawyer_id, status FROM legal_services.cases WHERE court_jurisdiction IS NOT NULL AND status IN ('Pending', 'Open');

[User] Great, now please order the list by date_opened in ascending order.

[Assistant] SELECT case_number, case_name, court_jurisdiction, lead_lawyer_id, status FROM legal_services.cases WHERE court_jurisdiction IS NOT NULL AND status IN ('Pending', 'Open') ORDER BY date_opened ASC;

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


[User] How many service locations do we have in each state?

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state;

[User] Only show states where there are at least 3 locations.

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Can you also show the number of accessible locations in each of those states?

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Order the results by accessible location count in descending order.

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3 ORDER BY accessible_location_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 government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)


[User] Provide a count of loans grouped by their status.

[Assistant] SELECT status, COUNT(*) FROM financial_services.loans GROUP BY status

[User] Additionally, show the total current principal balance for each status.

[Assistant] SELECT status, COUNT(*), SUM(current_principal_balance) FROM financial_services.loans GROUP BY status

[User] Only include statuses where the loan count is greater than 5.

[Assistant] SELECT status, COUNT(*), SUM(current_principal_balance) FROM financial_services.loans GROUP BY status HAVING COUNT(*) > 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 financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )