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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.loans ( loan_id text, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months integer, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

[User] Only show documents with version 3.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

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

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

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

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

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

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

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

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

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

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

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

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

[User] List all drivers.

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] List the top 5 exchanges with the highest total USD value of tokens held on the 'Ethereum' chain for the latest snapshot time.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

[User] Include their professional email addresses as well.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.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 )

[User] List pairs of invoices for the same case where one invoice's total_amount is lower than another's; show lower_invoice_number, higher_invoice_number, and case_id.

[Assistant]
SELECT a.invoice_number AS lower_invoice_number,
       b.invoice_number AS higher_invoice_number,
       a.case_id
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.case_id = b.case_id
   AND a.total_amount < b.total_amount;

[User] Please only include cases that have at least two invoices and sort by case_id and lower_invoice_number.

[Assistant]
SELECT a.invoice_number AS lower_invoice_number,
       b.invoice_number AS higher_invoice_number,
       a.case_id
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.case_id = b.case_id
   AND a.total_amount < b.total_amount
 ORDER BY a.case_id, a.invoice_number;

[User] For each client, show the earliest and latest invoice issue_date, along with the total amount invoiced. Include client_id, earliest_issue_date, latest_issue_date, and total_amount.

[Assistant]
SELECT client_id, MIN(issue_date) AS earliest_issue_date, MAX(issue_date) AS latest_issue_date, SUM(total_amount) AS total_amount
FROM legal_services.invoices
GROUP BY client_id;

[User] Show me pairs of invoice numbers for the same case.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id ORDER BY T1.case_id, T1.invoice_number, T2.invoice_number

[User] Only include pairs where the total amount of one invoice is greater than the other.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount ORDER BY T1.case_id, invoice1_amount DESC

[User] Exclude pairs where the issue dates are more than 90 days apart.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount, ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) AS days_apart FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount AND ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) <= 90 ORDER BY T1.case_id, days_apart ASC

[User] Show me all invoice numbers and due dates where the amount paid is exactly zero.

[Assistant] SELECT invoice_number, due_date FROM legal_services.invoices WHERE amount_paid = 0;

[User] Show the count of invoices for each case ID.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id ORDER BY invoice_count DESC

[User] Only include case IDs with more than 2 invoices.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY invoice_count DESC

[User] For these cases, what is the average total amount across all invoices?

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount DESC

[User] Order the results by average total amount ascending.

[Assistant] SELECT case_id, COUNT(invoice_id) AS invoice_count, AVG(total_amount) AS average_total_amount FROM legal_services.invoices WHERE case_id IS NOT NULL GROUP BY case_id HAVING COUNT(invoice_id) > 2 ORDER BY average_total_amount ASC


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
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] Retrieve the passenger_id, first_name, last_name, and total number of bookings each passenger has made in 2023, including only those with at least one booking.

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

[User] Also, include the sum of fares paid by each passenger and order by total_fares descending.

[Assistant]
SELECT p.passenger_id, p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, SUM(b.fare) AS total_fares
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2023-01-01' AND b.booking_time < '2024-01-01'
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 0
ORDER BY total_fares DESC;

[User] Show all trips along with the vehicle's make and model, the driver full name, and the route distance in kilometers.

[Assistant]
SELECT t.trip_id, v.make, v.model, d.first_name || ' ' || d.last_name AS driver_full_name, r.distance_km
FROM transportation.trips t
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
JOIN transportation.drivers d ON t.driver_id = d.driver_id
JOIN transportation.routes r ON t.route_id = r.route_id;

[User] List every maintenance log for each vehicle, including the vehicle's license plate and the mechanic's name.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id;

[User] I want to see only the maintenance logs where the service cost exceeds 500.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500;

[User] Add the odometer reading and sort the results by service date descending.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost, ml.odometer_reading
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500
ORDER BY ml.service_date DESC;

[User] Sorry, actually, I also want to see the recommended next_service_due_date in the output.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, v.license_plate, ml.service_date, ml.service_type, ml.description, ml.mechanic_name, ml.cost, ml.odometer_reading, ml.next_service_due_date
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE ml.cost > 500
ORDER BY ml.service_date DESC;

[User] List all fuel refueling events with the refueled vehicle's make and model, the fuel type used, and the fueling location ID.

[Assistant]
SELECT fl.fuel_log_id, fl.log_timestamp, v.make, v.model, fl.fuel_type, fl.quantity, fl.unit, fl.total_cost, fl.location_id
FROM transportation.fuel_logs fl
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_id;

[User] Show the total fare collected from bookings, grouped by the state/province of the destination location of the trip, for bookings made in May 2024.

[Assistant]
SELECT
  l.state_province,
  SUM(b.fare) AS total_fare_collected
FROM transportation.bookings AS b
JOIN transportation.trips AS t
  ON b.trip_id = t.trip_id
JOIN transportation.locations AS l
  ON t.destination_location_id = l.location_id
WHERE
  b.booking_time >= '2024-05-01 00:00:00' AND b.booking_time < '2024-06-01 00:00:00'
GROUP BY
  l.state_province;

[User] Filter this list to only include states/provinces where the total fare collected is greater than 10000 and also include the count of bookings for each of these states. Order the results by total fare descending.

[Assistant]
SELECT
  l.state_province,
  SUM(b.fare) AS total_fare_collected,
  COUNT(b.booking_id) AS booking_count
FROM transportation.bookings AS b
JOIN transportation.trips AS t
  ON b.trip_id = t.trip_id
JOIN transportation.locations AS l
  ON t.destination_location_id = l.location_id
WHERE
  b.booking_time >= '2024-05-01 00:00:00' AND b.booking_time < '2024-06-01 00:00:00'
GROUP BY
  l.state_province
HAVING
  SUM(b.fare) > 10000
ORDER BY
  total_fare_collected DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies ( policy_id text 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, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id 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.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, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Find the total number of unique document types stored in the claim_documents table.

[Assistant] SELECT COUNT(DISTINCT document_type) FROM insurance.claim_documents;

[User] For each claim, show the claim ID, incident date, the customer's first and last name, and the policy number under which it was filed.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id;

[User] Filter these results to only include claims reported in the year 2024.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01';

[User] Now, only show claims where the status is 'Settled' or 'Approved', and include the settlement amount.

[Assistant] SELECT cl.claim_id, cl.incident_date, c.first_name AS customer_first_name, c.last_name AS customer_last_name, p.policy_number, cl.settlement_amount FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id JOIN insurance.policies AS p ON cl.policy_id = p.policy_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved');

[User] For *these* settled or approved claims reported in 2024, find the count of associated claim documents and the total size of those documents. Show the claim ID, customer full name, and the document count and total size.

[Assistant] SELECT cl.claim_id, c.first_name AS customer_first_name, c.last_name AS customer_last_name, COUNT(cd.document_id) AS document_count, SUM(cd.file_size_bytes) AS total_document_size_bytes FROM insurance.claims AS cl JOIN insurance.customers AS c ON cl.customer_id = c.customer_id LEFT JOIN insurance.claim_documents AS cd ON cl.claim_id = cd.claim_id WHERE cl.reported_date >= '2024-01-01' AND cl.reported_date < '2025-01-01' AND cl.status IN ('Settled', 'Approved') GROUP BY cl.claim_id, c.first_name, c.last_name ORDER BY cl.claim_id;

[User] What is the minimum, maximum, and average commission rate among all agents?

[Assistant] SELECT MIN(commission_rate) AS min_commission_rate, MAX(commission_rate) AS max_commission_rate, AVG(commission_rate) AS average_commission_rate FROM insurance.agents;

[User] List policies issued by active agents to customers in the 'CA' state, including policy number, customer's first and last name, agent's first and last name, and the agent's license state.

[Assistant] SELECT p.policy_number, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name, a.license_state FROM insurance.policies AS p JOIN insurance.agents AS a ON p.agent_id = a.agent_id JOIN insurance.customers AS c ON p.customer_id = c.customer_id WHERE a.status = 'Active' AND c.state = 'CA';

[User] Show me the policy number, start date, end date, product name, and product type for all policies.

[Assistant] SELECT T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id

[User] Okay, now only show policies that started after '2023-01-01'.

[Assistant] SELECT T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.start_date > '2023-01-01'

[User] Also include the customer's first and last name in the results.

[Assistant] SELECT T3.first_name, T3.last_name, T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id JOIN insurance.customers AS T3 ON T1.customer_id = T3.customer_id WHERE T1.start_date > '2023-01-01'

[User] Sort the results by policy start date descending and limit to the top 10.

[Assistant] SELECT T3.first_name, T3.last_name, T1.policy_number, T1.start_date, T1.end_date, T2.product_name, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id JOIN insurance.customers AS T3 ON T1.customer_id = T3.customer_id WHERE T1.start_date > '2023-01-01' ORDER BY T1.start_date DESC LIMIT 10


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.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )

[User] Show the maximum and minimum current_players for each server status.

[Assistant] SELECT status, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status;

[User] Please also provide the total number of servers for each status.

[Assistant] SELECT status, COUNT(*) AS total_servers, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status;

[User] Could you sort the results by total_servers in descending order?

[Assistant] SELECT status, COUNT(*) AS total_servers, MAX(current_players) AS max_current_players, MIN(current_players) AS min_current_players FROM gaming_technology.servers GROUP BY status ORDER BY total_servers DESC;

[User] Can you show me the number of servers in each region, as well as the total max_players for each region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players FROM gaming_technology.servers GROUP BY region;

[User] Actually, can you also include the average number of current players per region?

[Assistant] SELECT region, COUNT(*) AS server_count, SUM(max_players) AS total_max_players, AVG(current_players) AS avg_current_players FROM gaming_technology.servers GROUP BY region;

[User] Show me all servers where current_players is 0, and include their server_id, server_name, and region.

[Assistant] SELECT server_id, server_name, region FROM gaming_technology.servers WHERE current_players = 0;

[User] Add the max_players and status columns.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0;

[User] Only show servers where status is not 'offline'.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline';

[User] Now sort the results by region ascending and max_players descending.

[Assistant] SELECT server_id, server_name, region, max_players, status FROM gaming_technology.servers WHERE current_players = 0 AND status <> 'offline' ORDER BY region ASC, max_players DESC;

[User] List all pairs of servers in the same region that are both 'online', showing server1_name, server2_name, and the absolute difference in current_players.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
WHERE s1.server_id <> s2.server_id
  AND s1.status = 'online'
  AND s2.status = 'online';

[User] Actually, only include each pair once (server1_id < server2_id) and where player_diff is less than 20.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
    AND s1.server_id < s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 20;

[User] Now, only include pairs where both servers have max_players greater than 100.

[Assistant]
SELECT
  s1.server_name AS server1_name,
  s2.server_name AS server2_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
    AND s1.server_id < s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 20
  AND s1.max_players > 100
  AND s2.max_players > 100;

[User] Show me all pairs of servers that are located in the same region, listing both server names and their region.

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

[User] Filter this list to only include pairs where both servers are currently 'online'.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] For these pairs, also show the current_players for both servers.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] Order the results by region ascending, then by the current players of the first server in the pair ascending.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.region, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.region = s2.region AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online' ORDER BY s1.region ASC, s1.current_players ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] How many addresses on the Ethereum chain have an ROI between 2 and 4?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

[User] Could you also show their average profit?

[Assistant] SELECT AVG(profit) AS avg_profit FROM smart_money_profit WHERE chain = 'Ethereum' AND roi >= 2 AND roi <= 4;

[User] List addresses on the 'Ethereum' chain that have an ROI greater than 5 and a profit greater than $1000. Show their address, profit, ROI, and realized ratio.

[Assistant] SELECT address, profit, roi, realized_ratio FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000

[User] Can you order these addresses by their profit in descending order?

[Assistant] SELECT address, profit, roi, realized_ratio FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000 ORDER BY profit DESC

[User] Only show addresses whose last trade time is in 2024.

[Assistant] SELECT address, profit, roi, realized_ratio FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000 AND last_trade_time LIKE '2024%' ORDER BY profit DESC

[User] Include the rank of these addresses in the output and show only the top 5 results.

[Assistant] SELECT address, profit, roi, realized_ratio, rank FROM smart_money_profit WHERE chain = 'Ethereum' AND roi > 5 AND profit > 1000 AND last_trade_time LIKE '2024%' ORDER BY profit DESC LIMIT 5

[User] Show all addresses that made their last trade in 2024, including their chain and profit.

[Assistant] SELECT address, chain, profit FROM smart_money_profit WHERE last_trade_time LIKE '2024%';

[User] For each chain, list the address with the highest ROI, showing the address, ROI, profit, and most profitable token.

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi;

[User] Add a filter to only include results where profit is greater than 50000.

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit WHERE profit > 50000 GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi WHERE t1.profit > 50000;

[User] Can you also add the rank of each address?

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token, t1.rank FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit WHERE profit > 50000 GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi WHERE t1.profit > 50000;

[User] Change the ROI filter to greater than 5 and profit greater than 100000.

[Assistant] SELECT t1.chain, t1.address, t1.roi, t1.profit, t1.most_profit_token, t1.rank FROM smart_money_profit t1 INNER JOIN (SELECT chain, MAX(roi) as max_roi FROM smart_money_profit WHERE profit > 100000 AND roi > 5 GROUP BY chain) t2 ON t1.chain = t2.chain AND t1.roi = t2.max_roi WHERE t1.profit > 100000 AND t1.roi > 5;

[User] Which addresses across all chains have a realized ratio above 0.9 and a profit above $20,000? Show their address, chain, profit, realized ratio, and most profitable token.

[Assistant] SELECT address, chain, profit, realized_ratio, most_profit_token FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000;

[User] Order these addresses by profit in descending order, and show the top 3.

[Assistant] SELECT address, chain, profit, realized_ratio, most_profit_token FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000 ORDER BY profit DESC LIMIT 3;

[User] Please add their ROI and last trade time to the results.

[Assistant] SELECT address, chain, profit, roi, realized_ratio, most_profit_token, last_trade_time FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000 ORDER BY profit DESC LIMIT 3;

[User] Can you also filter to only include addresses with an ROI greater than 3?

[Assistant] SELECT address, chain, profit, roi, realized_ratio, most_profit_token, last_trade_time FROM smart_money_profit WHERE realized_ratio > 0.9 AND profit > 20000 AND roi > 3 ORDER BY profit DESC LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- hashed social security number (or national ID)
    address text NOT NULL, -- customer's primary address
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL,
    email character varying(128) UNIQUE, -- customer's email address
    phone_number character varying(32),
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of customer record creation
    status character varying(32) NOT NULL, -- e.g., Active, Inactive, Pending Verification
    risk_profile character varying(50), -- e.g., Low, Medium, High
    PRIMARY KEY (customer_id)
)
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    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, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    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, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades (
    trade_id character varying(64) NOT NULL, -- unique identifier for the trade
    account_id character varying(64) NOT NULL, -- investment account executing the trade
    security_id character varying(64) NOT NULL, -- security being traded
    order_id character varying(64), -- related order ID if applicable
    trade_type character varying(10) NOT NULL, -- 'Buy' or 'Sell'
    quantity numeric(19, 8) NOT NULL, -- number of units traded
    price_per_unit numeric(19, 8) NOT NULL, -- price per unit of the security
    total_amount numeric(19, 4) NOT NULL, -- total value of the trade (quantity * price)
    commission numeric(10, 4), -- commission fee charged for the trade
    trade_timestamp timestamp NOT NULL, -- exact time the trade was executed
    settlement_date date, -- date the trade settles
    status character varying(32) NOT NULL, -- e.g., Executed, Settled, Cancelled
    execution_venue character varying(100), -- where the trade was executed
    PRIMARY KEY (trade_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.loans (
    loan_id character varying(64) NOT NULL, -- unique identifier for the loan, could be same as account_id
    account_id character varying(64) NOT NULL UNIQUE, -- link to the general account record
    loan_type character varying(50) NOT NULL, -- e.g., Mortgage, Personal, Auto, Student
    principal_amount numeric(19, 4) NOT NULL, -- original loan amount
    current_principal_balance numeric(19, 4) NOT NULL, -- remaining principal
    interest_rate numeric(6, 4) NOT NULL, -- annual interest rate
    term_months integer NOT NULL, -- loan term in months
    origination_date date NOT NULL, -- date the loan was disbursed
    maturity_date date NOT NULL, -- date the loan is due to be fully repaid
    monthly_payment numeric(12, 4), -- scheduled monthly payment amount
    collateral_description text, -- description of collateral, if secured loan
    status character varying(32) NOT NULL, -- e.g., Active, Paid Off, Defaulted
    PRIMARY KEY (loan_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id)
)

[User] Show me all active accounts with a balance greater than 2000.

[Assistant]
SELECT account_id, account_number, customer_id, account_type, balance, currency
FROM financial_services.accounts
WHERE status = 'Open' AND balance > 2000;

[User] Add the opened date and last updated timestamp to the output, and order the result by balance descending.

[Assistant]
SELECT account_id, account_number, customer_id, account_type, balance, currency, opened_date, last_updated_at
FROM financial_services.accounts
WHERE status = 'Open' AND balance > 2000
ORDER BY balance DESC;

[User] I only want to see accounts opened in the last 12 months. Can you add that filter?

[Assistant]
SELECT account_id, account_number, customer_id, account_type, balance, currency, opened_date, last_updated_at
FROM financial_services.accounts
WHERE status = 'Open'
  AND balance > 2000
  AND opened_date >= CURRENT_DATE - INTERVAL '12 months'
ORDER BY balance DESC;

[User] List all distinct pairs of customers who live in the same zip_code, without duplicating pairs.

[Assistant]
SELECT
  c1.customer_id AS customer_a,
  c2.customer_id AS customer_b,
  c1.zip_code
FROM financial_services.customers c1
JOIN financial_services.customers c2
  ON c1.zip_code = c2.zip_code
 AND c1.customer_id < c2.customer_id;

[User] Also include the city for each pair in the result.

[Assistant]
SELECT
  c1.customer_id AS customer_a,
  c2.customer_id AS customer_b,
  c1.zip_code,
  c1.city
FROM financial_services.customers c1
JOIN financial_services.customers c2
  ON c1.zip_code = c2.zip_code
 AND c1.customer_id < c2.customer_id;

[User] Finally, order the output by zip_code.

[Assistant]
SELECT
  c1.customer_id AS customer_a,
  c2.customer_id AS customer_b,
  c1.zip_code,
  c1.city
FROM financial_services.customers c1
JOIN financial_services.customers c2
  ON c1.zip_code = c2.zip_code
 AND c1.customer_id < c2.customer_id
ORDER BY c1.zip_code;

[User] For each security traded in April 2024, calculate the total quantity traded and the maximum close_price from market_data for the same period.

[Assistant]
SELECT t.security_id,
       SUM(t.quantity) AS total_quantity,
       MAX(md.close_price) AS max_close_price
FROM financial_services.trades t
JOIN financial_services.market_data md
  ON t.security_id = md.security_id
WHERE t.trade_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
  AND md.data_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
GROUP BY t.security_id;

[User] Actually, only include trades executed on the 'NASDAQ' venue.

[Assistant]
SELECT t.security_id,
       SUM(t.quantity) AS total_quantity,
       MAX(md.close_price) AS max_close_price
FROM financial_services.trades t
JOIN financial_services.market_data md
  ON t.security_id = md.security_id
WHERE t.trade_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
  AND md.data_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
  AND t.execution_venue = 'NASDAQ'
GROUP BY t.security_id;

[User] Also, ensure that market_data entries are only from the 'Bloomberg' source.

[Assistant]
SELECT t.security_id,
       SUM(t.quantity) AS total_quantity,
       MAX(md.close_price) AS max_close_price
FROM financial_services.trades t
JOIN financial_services.market_data md
  ON t.security_id = md.security_id
WHERE t.trade_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
  AND md.data_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
  AND t.execution_venue = 'NASDAQ'
  AND md.source = 'Bloomberg'
GROUP BY t.security_id;

[User] Finally, order the results by total_quantity in descending order.

[Assistant]
SELECT t.security_id,
       SUM(t.quantity) AS total_quantity,
       MAX(md.close_price) AS max_close_price
FROM financial_services.trades t
JOIN financial_services.market_data md
  ON t.security_id = md.security_id
WHERE t.trade_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
  AND md.data_timestamp BETWEEN '2024-04-01' AND '2024-04-30'
  AND t.execution_venue = 'NASDAQ'
  AND md.source = 'Bloomberg'
GROUP BY t.security_id
ORDER BY total_quantity DESC;

[User] Show me the count of completed transactions and the sum of their amounts grouped by currency for May 2024.

[Assistant]
SELECT currency,
       COUNT(*) AS transaction_count,
       SUM(amount) AS total_amount
FROM financial_services.transactions
WHERE status = 'Completed'
  AND transaction_date BETWEEN '2024-05-01' AND '2024-05-31'
GROUP BY currency;

[User] Now exclude any currency group where the total amount is less than 10000.

[Assistant]
SELECT currency,
       COUNT(*) AS transaction_count,
       SUM(amount) AS total_amount
FROM financial_services.transactions
WHERE status = 'Completed'
  AND transaction_date BETWEEN '2024-05-01' AND '2024-05-31'
GROUP BY currency
HAVING SUM(amount) >= 10000;

[User] Sort the results by sum(amount) in descending order.

[Assistant]
SELECT currency,
       COUNT(*) AS transaction_count,
       SUM(amount) AS total_amount
FROM financial_services.transactions
WHERE status = 'Completed'
  AND transaction_date BETWEEN '2024-05-01' AND '2024-05-31'
GROUP BY currency
HAVING SUM(amount) >= 10000
ORDER BY total_amount DESC;