System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.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 )
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
##Table Structure
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.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] Could you list pairs of services that belong to different agencies but share the same category? Provide the service names and their agency_ids.

[Assistant]
SELECT s1.service_name AS service_name_1, s1.agency_id AS agency_id_1, s2.service_name AS service_name_2, s2.agency_id AS agency_id_2
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.agency_id <> s2.agency_id;

[User] Actually, show only those pairs where both services are active.

[Assistant]
SELECT s1.service_name AS service_name_1, s1.agency_id AS agency_id_1, s2.service_name AS service_name_2, s2.agency_id AS agency_id_2
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.agency_id <> s2.agency_id
WHERE s1.is_active = TRUE
  AND s2.is_active = TRUE;

[User] List all smoking rooms, showing the property name, room number, and room type name.

[Assistant] SELECT T1.property_name, T2.room_number, T3.type_name FROM hospitality_technology.properties AS T1 JOIN hospitality_technology.rooms AS T2 ON T1.property_id = T2.property_id JOIN hospitality_technology.room_types AS T3 ON T2.room_type_id = T3.room_type_id WHERE T2.is_smoking = true

[User] List transactions where the description includes another transaction's reference_number, showing both transaction IDs and the referenced reference_number.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%';

[User] Only include cases where the referenced transaction has status 'COMPLETED'.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%'
WHERE t2.status = 'COMPLETED';

[User] Finally, order the output by the source transaction date ascending.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%'
WHERE t2.status = 'COMPLETED'
ORDER BY t1.transaction_date ASC;

[User] I want to compare servers within the same region. List pairs of servers where one has fewer current_players than the other. Include each server's name, region, and their current_players counts.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.region,
       s1.current_players AS players1,
       s2.current_players AS players2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
 AND s1.current_players < s2.current_players;

[User] Actually, limit the comparison to servers hosting the same game_id as well.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.region,
       s1.current_players AS players1,
       s2.current_players AS players2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
 AND s1.game_id = s2.game_id
 AND s1.current_players < s2.current_players;

[User] For each application, show the application ID, the full name of the assigned employee, and the number of payments made for that application.

[Assistant]
SELECT a.application_id, CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name, COUNT(p.payment_id) AS payment_count
FROM government_services.applications a
LEFT JOIN government_services.payments p ON a.application_id = p.application_id
LEFT JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
GROUP BY a.application_id, e.first_name, e.last_name;

[User] List the product_id, product_name, and base_premium for all products that are currently inactive.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE is_active = false;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
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.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE web3.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)
)
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )

[User] List all hashtags that have been used on posts created in the last 90 days. Show the tag_name and the date it was first used on a post within this period.

[Assistant] SELECT h.tag_name, MIN(p.created_at) AS first_use_date_in_period FROM social_media.posts AS p JOIN social_media.post_hashtags AS ph ON p.post_id = ph.post_id JOIN social_media.hashtags AS h ON ph.hashtag_id = h.hashtag_id WHERE p.created_at >= NOW() - INTERVAL '90 days' GROUP BY h.hashtag_id, h.tag_name;

[User] List all peers with their IP addresses who have not been seen in the last 7 days.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen < NOW() - INTERVAL '7 days';

[User] List the username and email of users whose first wallet creation date is the same day as their user registration date.

[Assistant] SELECT u.username, u.email FROM web3.users u JOIN (SELECT user_id, MIN(created_at) as first_wallet_created_at FROM web3.wallets GROUP BY user_id) w ON u.user_id = w.user_id WHERE DATE(u.created_at) = DATE(w.first_wallet_created_at);

[User] Find all cases that were closed in the year 2022, showing their case name, case number, and date closed.

[Assistant] SELECT case_name, case_number, date_closed FROM legal_services.cases WHERE date_closed >= '2022-01-01' AND date_closed < '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
##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) )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
##Table Structure
CREATE TABLE blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.smart_contracts ( contract_id text, creator_address text, code text, timestamp timestamp )
##Table Structure
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 )
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )
CREATE TABLE blockchain.users ( user_id.text, username.text, email.text, password_hash.text )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, 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 )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
##Table Structure
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
##Table Structure
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )

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

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

[User] For each event, display its event_id, the event_id of the previous event in the same transaction (if any), and the log_index of both events.

[Assistant]
SELECT curr.event_id   AS current_event_id,
       prev.event_id   AS previous_event_id,
       curr.log_index  AS current_log_index,
       prev.log_index  AS previous_log_index,
       curr.transaction_id
FROM web3.events curr
LEFT JOIN web3.events prev
  ON curr.transaction_id = prev.transaction_id
 AND curr.log_index = prev.log_index + 1;

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

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

[User] Find all smart contracts deployed in 2022 that have never received any transactions.

[Assistant]
SELECT sc.contract_id, sc.creator_address, sc.timestamp AS deployment_time
FROM blockchain.smart_contracts sc
LEFT JOIN blockchain.transactions t
  ON t.receiver_address = sc.contract_id
WHERE sc.timestamp >= '2022-01-01' AND sc.timestamp < '2023-01-01'
  AND t.transaction_id IS NULL;

[User] Which active services have a standard fee less than 100, and what are the agency IDs and categories for these services?

[Assistant] SELECT service_name, agency_id, category FROM government_services.services WHERE is_active = TRUE AND standard_fee < 100;

[User] Show me the username and email of all users who own at least one wallet.

[Assistant] SELECT DISTINCT T1.username, T1.email FROM blockchain.users AS T1 JOIN blockchain.wallets AS T2 ON T1.user_id = T2.user_id;

[User] Get the number of insurance products grouped by product_type and their active status. Return product_type, is_active, and the count of products.

[Assistant]
SELECT product_type, is_active, COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type, is_active;

[User] List all claim documents that do not have a description. Show the document_id, claim_id, file_name, and uploaded_at.

[Assistant] SELECT document_id, claim_id, file_name, uploaded_at FROM insurance.claim_documents WHERE description IS NULL OR description = '';

[User] How many users have followed more than one person in total?

[Assistant]
SELECT follower_user_id, COUNT(DISTINCT following_user_id) AS following_count
FROM social_media.follows
GROUP BY follower_user_id
HAVING COUNT(DISTINCT following_user_id) > 1;

[User] Show me all documents that have a version greater than 2 and include the document name, upload timestamp, and description.

[Assistant] SELECT document_id, document_name, upload_timestamp, description FROM legal_services.documents WHERE version > 2;

[User] List the reference number and status for all applications, including the registration date of the citizen who submitted it.

[Assistant] SELECT a.reference_number, a.status, c.registration_date FROM government_services.applications AS a JOIN citizens AS c ON a.citizen_id = c.citizen_id;

[User] How many documents of each type exist in the system? Show the document type and the count.

[Assistant]
SELECT document_type, COUNT(*) AS document_count
FROM legal_services.documents
group BY document_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
CREATE TABLE token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )
CREATE TABLE smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )
##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
)
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, 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 )
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )

[User] Find the average score for each player who has participated in game sessions.

[Assistant]
SELECT player_id, AVG(score) AS avg_score
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Now show only players who have also unlocked at least one achievement.

[Assistant]
SELECT gs.player_id, AVG(gs.score) AS avg_score
FROM gaming_technology.game_sessions gs
WHERE gs.player_id IN (
    SELECT DISTINCT pa.player_id FROM gaming_technology.player_achievements pa
)
GROUP BY gs.player_id;

[User] Can you also include the total number of achievements each player has unlocked?

[Assistant]
SELECT gs.player_id, AVG(gs.score) AS avg_score, COUNT(pa.achievement_id) AS total_achievements
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.player_achievements pa ON gs.player_id = pa.player_id
GROUP BY gs.player_id;

[User] I received duplicate player rows. Can you fix the SQL so the achievement count is correct for each player?

[Assistant]
SELECT gs.player_id, AVG(gs.score) AS avg_score, (
    SELECT COUNT(DISTINCT pa.achievement_id)
    FROM gaming_technology.player_achievements pa
    WHERE pa.player_id = gs.player_id
) AS total_achievements
FROM gaming_technology.game_sessions gs
WHERE gs.player_id IN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
)
GROUP BY gs.player_id;

[User] For each chain in the smart money token inflow data, calculate the total number of addresses involved in buy transactions and the total number of addresses involved in sell transactions. Display the chain, total buy addresses, and total sell addresses.

[Assistant] SELECT chain, SUM(CASE WHEN type = 1 THEN address_amount ELSE 0 END) AS total_buy_addresses, SUM(CASE WHEN type = 2 THEN address_amount ELSE 0 END) AS total_sell_addresses FROM smart_money_token_inflow WHERE type IN (1, 2) GROUP BY chain;

[User] List all insurance plans that will expire within the next 30 days, showing the patient IDs and subscriber names.

[Assistant]
SELECT patient_id, subscriber_name, policy_number, expiration_date
FROM healthcare.patient_insurance
WHERE expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '30 days');

[User] Actually, I only need to see plans that are primary insurance.

[Assistant]
SELECT patient_id, subscriber_name, policy_number, expiration_date
FROM healthcare.patient_insurance
WHERE expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '30 days')
AND is_primary = true;

[User] Can you also sort the results by expiration date in ascending order?

[Assistant]
SELECT patient_id, subscriber_name, policy_number, expiration_date
FROM healthcare.patient_insurance
WHERE expiration_date BETWEEN CURRENT_DATE AND (CURRENT_DATE + INTERVAL '30 days')
AND is_primary = true
ORDER BY expiration_date ASC;

[User] Show me each invoice and the invoice_number of the next invoice for the same client, along with how many days apart their issue_dates are.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date;

[User] Please restrict to pairs where the days_between is greater than 30.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30;

[User] And only include pairs where both invoices have status 'Overdue'.

[Assistant]
SELECT a.invoice_number AS invoice_number,
       b.invoice_number AS next_invoice_number,
       (b.issue_date - a.issue_date) AS days_between
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.client_id = b.client_id
   AND b.issue_date > a.issue_date
 WHERE (b.issue_date - a.issue_date) > 30
   AND a.status = 'Overdue'
   AND b.status = 'Overdue';

[User] Calculate the total PNL and total Net Flow for all tokens recorded on the 'Arbitrum' chain.

[Assistant] SELECT SUM(pnl) as total_pnl, SUM(net_flow) as total_net_flow FROM smart_money_token_performance WHERE chain = 'Arbitrum';

[User] Can you calculate the total PNL and total Net Flow for *all* chains? Show the chain, total PNL, and total Net Flow, ordered by total PNL in descending order.

[Assistant] SELECT chain, SUM(pnl) as total_pnl, SUM(net_flow) as total_net_flow FROM smart_money_token_performance GROUP BY chain ORDER BY total_pnl DESC;