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;

[User] For each chain, show the total number of smart money addresses and the count of addresses with positive profit.

[Assistant] SELECT chain, COUNT(address) AS total_addresses, COUNT(CASE WHEN profit > 0 THEN address END) AS positive_profit_addresses FROM smart_money_profit GROUP BY chain

[User] Filter the results to only include chains where the total number of addresses is greater than 100. Also, include the percentage of addresses with positive profit for each chain.

[Assistant] SELECT chain, COUNT(address) AS total_addresses, COUNT(CASE WHEN profit > 0 THEN address END) AS positive_profit_addresses, CAST(COUNT(CASE WHEN profit > 0 THEN address END) AS REAL) * 100 / COUNT(address) AS positive_profit_percentage FROM smart_money_profit GROUP BY chain HAVING COUNT(address) > 100

[User] Which are the top 5 smart money addresses with the highest ROI on the BSC chain, and what are their profit, realized ratio, and most profitable token?

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token FROM smart_money_profit WHERE chain = 'BSC' ORDER BY roi DESC LIMIT 5;

[User] Can you also include their rank and last trade time in the output?

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' ORDER BY roi DESC LIMIT 5;

[User] I only want to see addresses with a profit above $10,000 and a realized ratio higher than 0.8.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY roi DESC LIMIT 5;

[User] Now, show the top one among these by profit instead of ROI.

[Assistant] SELECT address, profit, roi, realized_ratio, most_profit_token, rank, last_trade_time FROM smart_money_profit WHERE chain = 'BSC' AND profit > 10000 AND realized_ratio > 0.8 ORDER BY profit DESC LIMIT 1;

[User] List smart money addresses on the 'Arbitrum' chain with a realized ratio between 0.5 and 0.8 and positive profit. Show address, profit, and realized_ratio.

[Assistant] SELECT address, profit, realized_ratio FROM smart_money_profit WHERE chain = 'Arbitrum' AND realized_ratio BETWEEN 0.5 AND 0.8 AND profit > 0

[User] Add the 'most_profit_token' and 'last_trade_time' to the result. Also, order by profit descending.

[Assistant] SELECT address, profit, realized_ratio, most_profit_token, last_trade_time FROM smart_money_profit WHERE chain = 'Arbitrum' AND realized_ratio BETWEEN 0.5 AND 0.8 AND profit > 0 ORDER BY profit DESC

[User] What is the average profit and average ROI for smart money addresses ranked in the top 500?

[Assistant] SELECT AVG(profit), AVG(roi) FROM smart_money_profit WHERE rank <= 500

[User] How many addresses on the Polygon chain have an ROI above 5?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE chain = 'Polygon' AND roi > 5;

[User] Also show the average profit of these addresses.

[Assistant] SELECT COUNT(*) AS address_count, AVG(profit) AS avg_profit FROM smart_money_profit WHERE chain = 'Polygon' AND roi > 5;


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;


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.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )

[User] Give me the count of developers per country.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count
FROM gaming_technology.developers
GROUP BY country;

[User] Actually, include only countries with more than 5 developers.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count
FROM gaming_technology.developers
GROUP BY country
HAVING COUNT(*) > 5;

[User] Also calculate the average founded_year per country as avg_year.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count,
       AVG(founded_year) AS avg_year
FROM gaming_technology.developers
GROUP BY country
HAVING COUNT(*) > 5;

[User] Order the results by avg_year descending.

[Assistant]
SELECT country,
       COUNT(*) AS developer_count,
       AVG(founded_year) AS avg_year
FROM gaming_technology.developers
GROUP BY country
HAVING COUNT(*) > 5
ORDER BY avg_year DESC;

[User] Could you list all pairs of developers in the same country but different companies? Return developer1, developer2, and country.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id;

[User] Now restrict pairs to only those in country 'USA' or 'Canada'.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada');

[User] Sort the pairs by developer1 name ascending.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada')
ORDER BY d1.name ASC;

[User] Find all pairs of developers in the same country but founded in different years. Show each developer's name, their founded_year, and the shared country.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country, d1.founded_year AS founded1, d2.founded_year AS founded2
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
  AND d1.founded_year <> d2.founded_year;

[User] Now show only those pairs where the difference in their founded_year is at least 10 years.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country, d1.founded_year AS founded1, d2.founded_year AS founded2, ABS(d1.founded_year - d2.founded_year) AS year_diff
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
  AND d1.developer_id < d2.developer_id
WHERE ABS(d1.founded_year - d2.founded_year) >= 10;

[User] List all developer names and their countries.

[Assistant] SELECT name, country FROM gaming_technology.developers;

[User] Filter the list to only include developers from countries that start with 'U'.

[Assistant] SELECT name, country FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] For these developers from countries starting with 'U', what are the minimum and maximum founded years?

[Assistant] SELECT MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] Also, include the average founded year and the total count of developers in this filtered group.

[Assistant] SELECT COUNT(*), AVG(founded_year), MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] Which countries have the highest number of developer companies founded after 2005? Please show country, the number of developers, and order by developer count descending.

[Assistant]
SELECT country, COUNT(*) AS developer_count
FROM gaming_technology.developers
WHERE founded_year > 2005
GROUP BY country
ORDER BY developer_count DESC;

[User] Exclude any rows where the country value is NULL or an empty string.

[Assistant]
SELECT country, COUNT(*) AS developer_count
FROM gaming_technology.developers
WHERE founded_year > 2005
  AND country IS NOT NULL
  AND country <> ''
GROUP BY country
ORDER BY developer_count DESC;

[User] Can you also show the earliest founded_year among all developers in each country?

[Assistant]
SELECT country, COUNT(*) AS developer_count, MIN(founded_year) AS earliest_founded_year
FROM gaming_technology.developers
WHERE founded_year > 2005
  AND country IS NOT NULL
  AND country <> ''
GROUP BY country
ORDER BY developer_count DESC;

[User] Show me the names and websites of all developers whose website contains '.com'.

[Assistant] SELECT name, website FROM gaming_technology.developers WHERE website LIKE '%.com%';

[User] Only include developers from 'USA'.

[Assistant] SELECT name, website FROM gaming_technology.developers WHERE website LIKE '%.com%' AND country = 'USA';

[User] Order the results by the developer's name in ascending order.

[Assistant] SELECT name, website FROM gaming_technology.developers WHERE website LIKE '%.com%' AND country = 'USA' ORDER BY name ASC;

[User] Could you list each developer along with the next developer founded after them in the same country? Return columns current_developer, next_developer, and years_difference.

[Assistant]
SELECT d1.name AS current_developer,
       d2.name AS next_developer,
       d2.founded_year - d1.founded_year AS years_difference
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d2.founded_year > d1.founded_year
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.developers dx
  WHERE dx.country = d1.country
    AND dx.founded_year > d1.founded_year
    AND dx.founded_year < d2.founded_year
);

[User] Actually, exclude pairs where the difference is more than 10 years.

[Assistant]
SELECT d1.name AS current_developer,
       d2.name AS next_developer,
       d2.founded_year - d1.founded_year AS years_difference
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d2.founded_year > d1.founded_year
WHERE NOT EXISTS (
  SELECT 1
  FROM gaming_technology.developers dx
  WHERE dx.country = d1.country
    AND dx.founded_year > d1.founded_year
    AND dx.founded_year < d2.founded_year
)
  AND (d2.founded_year - d1.founded_year) <= 10;

[User] Also, only include countries with at least three developers.

[Assistant]
SELECT d1.name AS current_developer,
       d2.name AS next_developer,
       d2.founded_year - d1.founded_year AS years_difference
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d2.founded_year > d1.founded_year
WHERE d1.country IN (
  SELECT country
  FROM gaming_technology.developers
  GROUP BY country
  HAVING COUNT(*) >= 3
)
  AND NOT EXISTS (
    SELECT 1
    FROM gaming_technology.developers dx
    WHERE dx.country = d1.country
      AND dx.founded_year > d1.founded_year
      AND dx.founded_year < d2.founded_year
  )
  AND (d2.founded_year - d1.founded_year) <= 10
ORDER BY d1.country ASC, years_difference ASC;

[User] I want to find pairs of developers who share the same website domain. Show each pair's names and the domain.

[Assistant]
SELECT d1.name AS dev1,
       d2.name AS dev2,
       SPLIT_PART(SPLIT_PART(d1.website, '://', 2), '/', 1) AS domain
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON SPLIT_PART(SPLIT_PART(d1.website, '://', 2), '/', 1) = SPLIT_PART(SPLIT_PART(d2.website, '://', 2), '/', 1)
 AND d1.developer_id < d2.developer_id;

[User] Now only include domains that have at least 3 developers.

[Assistant]
WITH base AS (
  SELECT developer_id, name,
         SPLIT_PART(SPLIT_PART(website, '://', 2), '/', 1) AS domain
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
    AND website <> ''
), popular AS (
  SELECT domain
  FROM base
  GROUP BY domain
  HAVING COUNT(*) >= 3
)
SELECT b1.name AS dev1,
       b2.name AS dev2,
       b1.domain
FROM base b1
JOIN base b2
  ON b1.domain = b2.domain
 AND b1.developer_id < b2.developer_id
JOIN popular p
  ON b1.domain = p.domain;

[User] Exclude the 'localhost' domain.

[Assistant]
WITH base AS (
  SELECT developer_id, name,
         SPLIT_PART(SPLIT_PART(website, '://', 2), '/', 1) AS domain
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
    AND website <> ''
), popular AS (
  SELECT domain
  FROM base
  GROUP BY domain
  HAVING COUNT(*) >= 3
)
SELECT b1.name AS dev1,
       b2.name AS dev2,
       b1.domain
FROM base b1
JOIN base b2
  ON b1.domain = b2.domain
 AND b1.developer_id < b2.developer_id
JOIN popular p
  ON b1.domain = p.domain
WHERE b1.domain <> 'localhost';

[User] Order the results by domain ascending and limit to 10 rows.

[Assistant]
WITH base AS (
  SELECT developer_id, name,
         SPLIT_PART(SPLIT_PART(website, '://', 2), '/', 1) AS domain
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
    AND website <> ''
), popular AS (
  SELECT domain
  FROM base
  GROUP BY domain
  HAVING COUNT(*) >= 3
)
SELECT b1.name AS dev1,
       b2.name AS dev2,
       b1.domain
FROM base b1
JOIN base b2
  ON b1.domain = b2.domain
 AND b1.developer_id < b2.developer_id
JOIN popular p
  ON b1.domain = p.domain
WHERE b1.domain <> 'localhost'
ORDER BY b1.domain ASC
LIMIT 10;

[User] Find all pairs of developers who share the exact same founded_year but are from different countries. Show both developer names, their countries, and the founded_year.

[Assistant]
SELECT d1.name AS developer1_name, d1.country AS country1, d2.name AS developer2_name, d2.country AS country2, d1.founded_year
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.founded_year = d2.founded_year
 AND d1.developer_id < d2.developer_id
 AND d1.country <> d2.country;

[User] Can you also include the website of each developer in the output?

[Assistant]
SELECT d1.name AS developer1_name, d1.country AS country1, d1.website AS developer1_website,
       d2.name AS developer2_name, d2.country AS country2, d2.website AS developer2_website, d1.founded_year
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.founded_year = d2.founded_year
 AND d1.developer_id < d2.developer_id
 AND d1.country <> d2.country;

[User] I want to find pairs of developers that share the same website domain. For each pair, show both developer names and the domain.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.domain AS domain
FROM (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
) d1
JOIN (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL
) d2
  ON d1.domain = d2.domain
  AND d1.developer_id < d2.developer_id;

[User] Exclude any pairs where the website field is an empty string.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.domain AS domain
FROM (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL AND website <> ''
) d1
JOIN (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL AND website <> ''
) d2
  ON d1.domain = d2.domain
  AND d1.developer_id < d2.developer_id;

[User] Only include pairs where both developers were founded after 2010.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.domain AS domain
FROM (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL AND website <> ''
) d1
JOIN (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL AND website <> ''
) d2
  ON d1.domain = d2.domain
  AND d1.developer_id < d2.developer_id
  AND d1.founded_year > 2010
  AND d2.founded_year > 2010;

[User] Sort the output by domain alphabetically and limit to 10 rows.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.domain AS domain
FROM (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL AND website <> ''
) d1
JOIN (
  SELECT developer_id, name,
         LOWER(regexp_replace(split_part(website, '://', 2), '/.*', '')) AS domain,
         founded_year
  FROM gaming_technology.developers
  WHERE website IS NOT NULL AND website <> ''
) d2
  ON d1.domain = d2.domain
  AND d1.developer_id < d2.developer_id
  AND d1.founded_year > 2010
  AND d2.founded_year > 2010
ORDER BY domain ASC
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 web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )

[User] Show the user_id, username, and email for users who registered at the same timestamp as another user.

[Assistant] SELECT u1.user_id, u1.username, u1.email FROM web3.users u1 JOIN web3.users u2 ON u1.created_at = u2.created_at AND u1.user_id <> u2.user_id;

[User] Show all users who registered before 2023-01-01, along with their usernames and registration dates.

[Assistant]
SELECT user_id, username, created_at
FROM web3.users
WHERE created_at < '2023-01-01';

[User] Can you additionally include their email addresses in the result?

[Assistant]
SELECT user_id, username, email, created_at
FROM web3.users
WHERE created_at < '2023-01-01';

[User] Show me all users whose username contains 'dev', including their user_id and email address.

[Assistant] SELECT user_id, username, email FROM web3.users WHERE username ILIKE '%dev%';

[User] Can you also show the registration date for each of those users?

[Assistant] SELECT user_id, username, email, created_at FROM web3.users WHERE username ILIKE '%dev%';

[User] List all users whose usernames start with 'alice' and show their creation dates.

[Assistant] SELECT username, created_at FROM web3.users WHERE username LIKE 'alice%';

[User] There's a typo in your SQL, it should be 'alice%' not 'alice%'. Also, sort the results by created_at in ascending order.

[Assistant] SELECT username, created_at FROM web3.users WHERE username LIKE 'alice%' ORDER BY created_at ASC;

[User] Actually, I need to see their email addresses too.

[Assistant] SELECT username, email, created_at FROM web3.users WHERE username LIKE 'alice%' ORDER BY created_at ASC;

[User] Now filter to only show users created in 2023.

[Assistant] SELECT username, email, created_at FROM web3.users WHERE username LIKE 'alice%' AND created_at BETWEEN '2023-01-01' AND '2023-12-31' ORDER BY created_at ASC;

[User] Find pairs of users who registered on the same weekday but in different years. List the user ID and registration date for both users, and the weekday name.

[Assistant] SELECT u1.user_id, u1.created_at AS user1_created_at, u2.user_id, u2.created_at AS user2_created_at, TO_CHAR(u1.created_at, 'Day') AS registration_weekday FROM web3.users u1 JOIN web3.users u2 ON TO_CHAR(u1.created_at, 'Day') = TO_CHAR(u2.created_at, 'Day') AND EXTRACT(YEAR FROM u1.created_at) <> EXTRACT(YEAR FROM u2.created_at) AND u1.user_id < u2.user_id ORDER BY TO_CHAR(u1.created_at, 'D'), u1.created_at;

[User] Show the usernames and registration dates for all users whose email ends with '@gmail.com'.

[Assistant] SELECT username, created_at FROM web3.users WHERE email LIKE '%@gmail.com';

[User] Actually, can you also include how many such users there are in total in the result?

[Assistant] SELECT username, created_at, COUNT(*) OVER() AS total_gmail_users FROM web3.users WHERE email LIKE '%@gmail.com';

[User] List all pairs of users who registered within one day of each other, including their user IDs, usernames, and the difference in registration time.

[Assistant] SELECT u1.user_id AS user_id_1, u1.username AS username_1, u2.user_id AS user_id_2, u2.username AS username_2, ABS(EXTRACT(EPOCH FROM (u1.created_at - u2.created_at))/3600) AS hours_difference FROM web3.users u1 JOIN web3.users u2 ON u1.user_id < u2.user_id AND ABS(u1.created_at - u2.created_at) <= INTERVAL '1 day';

[User] Find pairs of users who have different usernames but share the same username length. List both user IDs, usernames, and the shared username length.

[Assistant] SELECT u1.user_id, u1.username AS user1_username, u2.user_id, u2.username AS user2_username, LENGTH(u1.username) AS username_length FROM web3.users u1 JOIN web3.users u2 ON LENGTH(u1.username) = LENGTH(u2.username) AND u1.user_id < u2.user_id WHERE u1.username <> u2.username;

[User] Find all pairs of users who registered at exactly the same timestamp, showing both user IDs, usernames, and the shared registration timestamp.

[Assistant]
SELECT u1.user_id AS user_id_1, u1.username AS username_1, u2.user_id AS user_id_2, u2.username AS username_2, u1.created_at
FROM web3.users u1
JOIN web3.users u2
  ON u1.created_at = u2.created_at
  AND u1.user_id < u2.user_id;

[User] For each user, show how many users registered after them. Return the user_id, username, and the count of later registrants.

[Assistant] SELECT u1.user_id, u1.username, COUNT(u2.user_id) AS later_user_count FROM web3.users u1 LEFT JOIN web3.users u2 ON u2.created_at > u1.created_at GROUP BY u1.user_id, u1.username ORDER BY u1.user_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 trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] How many unread notifications does each user have?

[Assistant]
SELECT user_id,
       COUNT(*) AS unread_notifications
FROM trading_platform.notifications
WHERE read_at IS NULL
GROUP BY user_id;

[User] Provide a list of order_id and notification_id for all orders and notifications that occurred on the same day for each user.

[Assistant]
SELECT o.order_id,
       n.notification_id
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at);

[User] Now refine it to include only notifications that have been read and orders with status 'completed'.

[Assistant]
SELECT o.order_id,
       n.notification_id
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at)
WHERE o.status = 'completed'
  AND n.read_at IS NOT NULL;

[User] Include the order's quantity and notification message in the result, and sort by n.read_at descending.

[Assistant]
SELECT o.order_id,
       o.quantity,
       n.notification_id,
       n.message,
       n.read_at
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at)
WHERE o.status = 'completed'
  AND n.read_at IS NOT NULL
ORDER BY n.read_at DESC;

[User] Limit the output to the top 5 records.

[Assistant]
SELECT o.order_id,
       o.quantity,
       n.notification_id,
       n.message,
       n.read_at
FROM trading_platform.orders o
JOIN trading_platform.notifications n
  ON o.user_id = n.user_id
  AND DATE(o.created_at) = DATE(n.sent_at)
WHERE o.status = 'completed'
  AND n.read_at IS NOT NULL
ORDER BY n.read_at DESC
LIMIT 5;

[User] Give me a count of log entries for each user.

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

[User] Only show users who have more than 10 log entries.

[Assistant]
SELECT user_id, COUNT(*) AS log_count
FROM trading_platform.logs
GROUP BY user_id
HAVING COUNT(*) > 10;

[User] Please include their wallet addresses as well.

[Assistant]
SELECT l.user_id, w.address, COUNT(*) AS log_count
FROM trading_platform.logs l
JOIN trading_platform.wallets w ON l.user_id = w.user_id
GROUP BY l.user_id, w.address
HAVING COUNT(*) > 10;

[User] If a user has multiple wallets, show each in a separate row.

[Assistant]
SELECT l.user_id, w.address, COUNT(*) AS log_count
FROM trading_platform.logs l
JOIN trading_platform.wallets w ON l.user_id = w.user_id
GROUP BY l.user_id, w.address
HAVING COUNT(*) > 10;

[User] Show all users who have no wallets yet.

[Assistant]
SELECT DISTINCT k.user_id
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.wallets w ON k.user_id = w.user_id
WHERE w.wallet_id IS NULL;

[User] Show me all users who have both placed orders and have KYC status approved, along with their order count and most recent KYC review date.

[Assistant] SELECT o.user_id, COUNT(o.order_id) as order_count, MAX(k.reviewed_at) as last_kyc_review FROM trading_platform.orders o JOIN trading_platform.kyc_audit k ON o.user_id = k.user_id WHERE k.status = 'approved' GROUP BY o.user_id;

[User] List each user's username, email, and the total count of log entries they have recorded.

[Assistant] SELECT T1.username, T1.email, count(T2.log_id) FROM users AS T1 LEFT JOIN logs AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email

[User] Also include the date of their most recent log entry.

[Assistant] SELECT T1.username, T1.email, count(T2.log_id), max(T2.logged_at) FROM users AS T1 LEFT JOIN logs AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email

[User] Show each user's username and the total number of notifications they have received.

[Assistant] SELECT T1.username, count(T2.notification_id) FROM users AS T1 LEFT JOIN notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username

[User] Filter the results to only include users who have received notifications.

[Assistant] SELECT T1.username, count(T2.notification_id) FROM users AS T1 JOIN notifications AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username

[User] Only show users who have received notifications AND have at least one log entry.

[Assistant] SELECT T1.username, count(distinct T2.notification_id), count(distinct T3.log_id) FROM users AS T1 JOIN notifications AS T2 ON T1.user_id = T2.user_id JOIN logs AS T3 ON T1.user_id = T3.user_id GROUP BY T1.user_id, T1.username

[User] The previous query excluded users who have notifications but no logs, or logs but no notifications. Please include all users who have either received notifications OR have logged an action. Show their username, total notification count (0 if none), and total log count (0 if none).

[Assistant] SELECT T1.username, count(distinct T2.notification_id), count(distinct T3.log_id) FROM users AS T1 LEFT JOIN notifications AS T2 ON T1.user_id = T2.user_id LEFT JOIN logs AS T3 ON T1.user_id = T3.user_id GROUP BY T1.user_id, T1.username

[User] List each user along with the number of wallets they own and the number of unique addresses found in their UTXOs.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COUNT(DISTINCT ut.address) as unique_utxo_addresses
FROM trading_platform.wallets w
JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id;

[User] Actually, only include users who have more than 1 unique UTXO address.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COUNT(DISTINCT ut.address) as unique_utxo_addresses
FROM trading_platform.wallets w
JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id
HAVING COUNT(DISTINCT ut.address) > 1;

[User] The query doesn't work because some users have no UTXOs. Please include all users with their wallet count, and show 0 for unique_utxo_addresses if they don't have any.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COALESCE(COUNT(DISTINCT ut.address), 0) as unique_utxo_addresses
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id;

[User] Now, show only users who have at least 2 wallets.

[Assistant]
SELECT u.user_id, COUNT(DISTINCT w.wallet_id) as wallet_count, COALESCE(COUNT(DISTINCT ut.address), 0) as unique_utxo_addresses
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos ut ON w.address = ut.address
JOIN (SELECT DISTINCT user_id FROM trading_platform.wallets) u ON w.user_id = u.user_id
GROUP BY u.user_id
HAVING COUNT(DISTINCT w.wallet_id) >= 2;

[User] List the names and URLs of all decentralized applications where the description includes the word 'exchange'.

[Assistant]
SELECT d.name, d.url
FROM trading_platform.dapps d
WHERE d.description ILIKE '%exchange%';

[User] I want to find the number of orders each user has placed along with their username and email.

[Assistant]
SELECT u.user_id, u.username, u.email, COUNT(o.order_id) AS order_count
FROM trading_platform.users u
LEFT JOIN trading_platform.orders o ON u.user_id = o.user_id
GROUP BY u.user_id, u.username, u.email;

[User] Actually, modify it to only include users who placed at least 5 orders and order the result by the order count descending.

[Assistant]
SELECT u.user_id, u.username, u.email, COUNT(o.order_id) AS order_count
FROM trading_platform.users u
LEFT JOIN trading_platform.orders o ON u.user_id = o.user_id
GROUP BY u.user_id, u.username, u.email
HAVING COUNT(o.order_id) >= 5
ORDER BY order_count 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
Index 'component_inventory'. Mapping: { properties: { inventory_record_id: { type: 'keyword' }, component_id: { type: 'keyword' }, quantity: { type: 'integer' }, location_warehouse: { type: 'keyword' }, location_bin: { type: 'keyword' }, received_date: { type: 'date' }, expiry_date: { type: 'date' }, batch_number: { type: 'keyword' }, last_updated: { type: 'date' } } }. Document _id can be inventory_record_id.

[User] 特定のコンポーネントの在庫情報を取得したいです。コンポーネントIDと在庫数量、倉庫の場所を含めてください。

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id';

[User] さらに、受け取り日が2022年以降の記録だけを表示するようにできますか？

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id' AND received_date >= '2022-01-01';

[User] 在庫数量が100未満のものだけに絞り込むことは可能ですか？

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id' AND received_date >= '2022-01-01' AND quantity < 100;

[User] 最後に、受け取り日を新しい順に並べ替えてください。

[Assistant] SELECT component_id, quantity, location_warehouse FROM component_inventory WHERE component_id = 'specific_component_id' AND received_date >= '2022-01-01' AND quantity < 100 ORDER BY received_date DESC;

[User] 特定の倉庫にあるコンポーネントの在庫情報を取得したいです。倉庫の場所、ビンの位置、在庫数量、コンポーネントIDを表示してください。

[Assistant] SELECT location_warehouse, location_bin, quantity, component_id FROM component_inventory WHERE location_warehouse = 'specific_warehouse';

[User] 受け取り日が2023年1月1日以降の記録だけに絞り込むことはできますか？

[Assistant] SELECT location_warehouse, location_bin, quantity, component_id FROM component_inventory WHERE location_warehouse = 'specific_warehouse' AND received_date >= '2023-01-01';

[User] さらに、最終更新日が過去1ヶ月以内のものだけを表示するようにできますか？

[Assistant] SELECT location_warehouse, location_bin, quantity, component_id FROM component_inventory WHERE location_warehouse = 'specific_warehouse' AND received_date >= '2023-01-01' AND last_updated >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);

[User] 最後に、コンポーネントIDごとにグループ化して、在庫数量の合計を表示してください。

[Assistant] SELECT location_warehouse, location_bin, component_id, SUM(quantity) AS total_quantity FROM component_inventory WHERE location_warehouse = 'specific_warehouse' AND received_date >= '2023-01-01' AND last_updated >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY component_id, location_warehouse, location_bin;

[User] 在庫記録の中で、特定のバッチ番号に関連する情報を取得したいです。バッチ番号と在庫数量、倉庫の位置を表示してください。

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number';

[User] 有効期限が2023年12月31日以前のものだけを除外できますか？

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number' AND (expiry_date > '2023-12-31' OR expiry_date IS NULL);

[User] さらに、倉庫の位置が特定の場所に限定されるようにできますか？例えば「Warehouse_A」のみ。

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number' AND (expiry_date > '2023-12-31' OR expiry_date IS NULL) AND location_warehouse = 'Warehouse_A';

[User] 最後に、在庫数量を多い順に並べ替えてください。

[Assistant] SELECT batch_number, quantity, location_warehouse FROM component_inventory WHERE batch_number = 'specific_batch_number' AND (expiry_date > '2023-12-31' OR expiry_date IS NULL) AND location_warehouse = 'Warehouse_A' ORDER BY quantity DESC;

[User] 특정 품질 등급 이상의 공급업체를 조회하고 싶습니다. 품질 등급, 공급업체 이름, 국가를 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "range": {
      "quality_rating": {
        "gte": 4.0
      }
    }
  },
  "_source": ["supplier_name", "country", "quality_rating"]
}

[User] 특정 국가에 속한 공급업체만 추가로 필터링하고 싶습니다. 예를 들어, 일본 소속 공급업체로 제한하고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating"]
}

[User] 연락처 담당자 이름과 인증 날짜도 결과에 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating", "contact_person", "certified_date"]
}

[User] 인증 날짜를 기준으로 오름차순 정렬을 추가해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "quality_rating": {
              "gte": 4.0
            }
          }
        },
        {
          "term": {
            "country": "Japan"
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "country", "quality_rating", "contact_person", "certified_date"],
  "sort": [
    {
      "certified_date": {
        "order": "asc"
      }
    }
  ]
}

[User] 특정 공급업체 ID로 공급업체의 세부 정보를 조회하고 싶습니다. 모든 필드를 포함해 주세요.

[Assistant] GET suppliers/_doc/{supplier_id}

[User] 만약 여러 공급업체 ID를 한 번에 조회하고 싶다면 어떻게 해야 하나요?

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  }
}

[User] 조회 결과에서 공급업체 이름과 연락처 이메일만 보고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  },
  "_source": ["supplier_name", "contact_email"]
}

[User] 결과를 공급업체 이름 기준으로 오름차순 정렬해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "terms": {
      "supplier_id": ["id1", "id2", "id3"]
    }
  },
  "_source": ["supplier_name", "contact_email"],
  "sort": [
    {
      "supplier_name.keyword": {
        "order": "asc"
      }
    }
  ]
}

[User] 특정 국가의 모든 공급업체 정보를 조회하고 싶습니다. 국가 이름, 공급업체 이름, 주소, 품질 등급을 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "term": {
      "country": "Korea"
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 품질 등급이 3.5 이상인 공급업체만 보고 싶습니다. 어떻게 수정해야 하나요?

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 인증 날짜가 2020년 이후인 공급업체만 추가로 필터링하고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"]
}

[User] 결과를 품질 등급 기준으로 내림차순 정렬해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"],
  "sort": [
    {
      "quality_rating": {
        "order": "desc"
      }
    }
  ]
}

[User] Can you help me retrieve a list of all aircraft builds for a specific model, including their assembly line details and current status?

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id';

[User] Can you filter this to show only builds that started after a specific date, for example, January 1, 2022?

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id' AND ab.build_start_date > '2022-01-01';

[User] What if I want to include only builds that are not yet completed?

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id' AND ab.build_start_date > '2022-01-01' AND ab.actual_completion_date IS NULL;

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

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id' AND ab.build_start_date > '2022-01-01' AND ab.actual_completion_date IS NULL
ORDER BY ab.build_start_date ASC;

[User] I need to get the total quantity of components in inventory for a specific warehouse location. Can you help with that?

[Assistant]
SELECT location_warehouse, SUM(quantity) AS total_quantity
FROM component_inventory
WHERE location_warehouse = 'specific_warehouse'
GROUP BY location_warehouse;

[User] Can you also include the component names for the inventory records in that warehouse?

[Assistant]
SELECT ci.location_warehouse, c.component_name, SUM(ci.quantity) AS total_quantity
FROM component_inventory ci
JOIN components c ON ci.component_id = c.component_id
WHERE ci.location_warehouse = 'specific_warehouse'
GROUP BY ci.location_warehouse, c.component_name;

[User] What if I want to filter out components with a total quantity less than 20?

[Assistant]
SELECT ci.location_warehouse, c.component_name, SUM(ci.quantity) AS total_quantity
FROM component_inventory ci
JOIN components c ON ci.component_id = c.component_id
WHERE ci.location_warehouse = 'specific_warehouse'
GROUP BY ci.location_warehouse, c.component_name
HAVING SUM(ci.quantity) >= 20;

[User] Can you sort the results by total quantity in descending order?

[Assistant]
SELECT ci.location_warehouse, c.component_name, SUM(ci.quantity) AS total_quantity
FROM component_inventory ci
JOIN components c ON ci.component_id = c.component_id
WHERE ci.location_warehouse = 'specific_warehouse'
GROUP BY ci.location_warehouse, c.component_name
HAVING SUM(ci.quantity) >= 20
ORDER BY total_quantity DESC;

[User] Can you help me fetch all inspection records for components associated with a specific aircraft build, along with the component names and inspection results?

[Assistant]
SELECT i.inspection_id, i.build_id, i.component_id, c.component_name, i.inspection_type, i.result, i.inspection_timestamp
FROM inspections i
JOIN components c ON i.component_id = c.component_id
WHERE i.build_id = 'specific_build_id';

[User] Can you filter this to include only inspections performed after a specific date, like February 1, 2023?

[Assistant]
SELECT i.inspection_id, i.build_id, i.component_id, c.component_name, i.inspection_type, i.result, i.inspection_timestamp
FROM inspections i
JOIN components c ON i.component_id = c.component_id
WHERE i.build_id = 'specific_build_id' AND i.inspection_timestamp > '2023-02-01';

[User] What if I want to see only inspections where the result is not 'Pass'?

[Assistant]
SELECT i.inspection_id, i.build_id, i.component_id, c.component_name, i.inspection_type, i.result, i.inspection_timestamp
FROM inspections i
JOIN components c ON i.component_id = c.component_id
WHERE i.build_id = 'specific_build_id' AND i.inspection_timestamp > '2023-02-01' AND i.result != 'Pass';

[User] Can you also include the inspector’s employee ID and sort the results by inspection timestamp in descending order?

[Assistant]
SELECT i.inspection_id, i.build_id, i.component_id, c.component_name, i.inspection_type, i.result, i.inspection_timestamp, i.inspector_employee_id
FROM inspections i
JOIN components c ON i.component_id = c.component_id
WHERE i.build_id = 'specific_build_id' AND i.inspection_timestamp > '2023-02-01' AND i.result != 'Pass'
ORDER BY i.inspection_timestamp 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 government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )

[User] Could you show me all scheduled appointments including appointment_id, scheduled_start_time, the citizen's full name, and the location name?

[Assistant]
SELECT a.appointment_id,
       a.scheduled_start_time,
       c.first_name || ' ' || c.last_name AS citizen_name,
       l.location_name
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.service_locations l ON a.location_id = l.location_id
WHERE a.status = 'Scheduled';

[User] Actually, include only those appointments scheduled after June 1, 2024.

[Assistant]
SELECT a.appointment_id,
       a.scheduled_start_time,
       c.first_name || ' ' || c.last_name AS citizen_name,
       l.location_name
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.service_locations l ON a.location_id = l.location_id
WHERE a.status = 'Scheduled'
  AND a.scheduled_start_time > '2024-06-01';

[User] For each employee, find their first and last name along with the number of applications they've been assigned. Only include employees with at least 5 assigned applications.

[Assistant]
SELECT e.first_name,
       e.last_name,
       COUNT(a.application_id) AS assigned_count
FROM government_services.employees e
JOIN government_services.applications a ON e.employee_id = a.assigned_employee_id
GROUP BY e.first_name, e.last_name
HAVING COUNT(a.application_id) >= 5;

[User] For each service location, show its name and the total number of appointments that have been scheduled there.

[Assistant] SELECT T1.location_name, COUNT(T2.appointment_id) AS total_appointments FROM government_services.service_locations AS T1 JOIN government_services.appointments AS T2 ON T1.location_id = T2.location_id GROUP BY T1.location_name;

[User] List the first name and last name of each citizen and the scheduled start time for their appointments.

[Assistant] SELECT T1.first_name, T1.last_name, T2.scheduled_start_time FROM government_services.citizens AS T1 JOIN government_services.appointments AS T2 ON T1.citizen_id = T2.citizen_id;

[User] Now, only include appointments scheduled after July 1, 2024.

[Assistant] SELECT T1.first_name, T1.last_name, T2.scheduled_start_time FROM government_services.citizens AS T1 JOIN government_services.appointments AS T2 ON T1.citizen_id = T2.citizen_id WHERE T2.scheduled_start_time > '2024-07-01';

[User] What are all the unique job titles listed for employees?

[Assistant] SELECT DISTINCT job_title FROM government_services.employees;

[User] Could you show the count of employees for each job title?

[Assistant] SELECT job_title, COUNT(*) AS employee_count FROM government_services.employees GROUP BY job_title;

[User] Only show job titles where there are more than 5 employees.

[Assistant] SELECT job_title, COUNT(*) AS employee_count FROM government_services.employees GROUP BY job_title HAVING COUNT(*) > 5;

[User] Also, exclude job titles that include the word 'Assistant'.

[Assistant] SELECT job_title, COUNT(*) AS employee_count FROM government_services.employees WHERE job_title NOT ILIKE '%Assistant%' GROUP BY job_title HAVING COUNT(*) > 5;

[User] List the application ID, citizen ID, assigned employee's full name, and total amount paid for each approved application.

[Assistant]
SELECT a.application_id,
       a.citizen_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       COALESCE(SUM(p.amount), 0) AS total_paid
FROM government_services.applications a
LEFT JOIN government_services.employees e
  ON a.assigned_employee_id = e.employee_id
LEFT JOIN government_services.payments p
  ON a.application_id = p.application_id
WHERE a.status = 'Approved'
GROUP BY a.application_id, a.citizen_id, e.first_name, e.last_name;

[User] For each employee, retrieve their full name and the number of appointments scheduled for them in the next 7 days, including employees with no appointments.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name,
       COUNT(a.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments a
  ON e.employee_id = a.employee_id
  AND a.scheduled_start_time BETWEEN now() AND now() + INTERVAL '7 days'
GROUP BY e.first_name, e.last_name;

[User] Give me a list of employees (first and last name) along with the count of appointments they have scheduled.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(a.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments a ON e.employee_id = a.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Only show employees who have scheduled at least 5 appointments.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(a.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments a ON e.employee_id = a.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(a.appointment_id) >= 5;

[User] Can you also show the average duration of their appointments in minutes?

[Assistant]
SELECT e.first_name, e.last_name, COUNT(a.appointment_id) AS appointment_count,
       AVG(EXTRACT(EPOCH FROM (a.scheduled_end_time - a.scheduled_start_time)) / 60) AS avg_duration_minutes
FROM government_services.employees e
LEFT JOIN government_services.appointments a ON e.employee_id = a.employee_id
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(a.appointment_id) >= 5;

[User] I got an error because some appointments have missing end times. Can you fix the query to only compute the average using appointments where both start and end times are present?

[Assistant]
SELECT e.first_name, e.last_name, COUNT(a.appointment_id) AS appointment_count,
       AVG(EXTRACT(EPOCH FROM (a.scheduled_end_time - a.scheduled_start_time)) / 60) AS avg_duration_minutes
FROM government_services.employees e
LEFT JOIN government_services.appointments a ON e.employee_id = a.employee_id AND a.scheduled_start_time IS NOT NULL AND a.scheduled_end_time IS NOT NULL
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(a.appointment_id) >= 5;

[User] Show me the first and last names of citizens, the appointment id, and the department of the employee who scheduled their appointment.

[Assistant]
SELECT c.first_name, c.last_name, a.appointment_id, e.department
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.employees e ON a.employee_id = e.employee_id;

[User] Can you also include the scheduled start time and filter to show only appointments with the status 'Scheduled'?

[Assistant]
SELECT c.first_name, c.last_name, a.appointment_id, e.department, a.scheduled_start_time
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.employees e ON a.employee_id = e.employee_id
WHERE a.status = 'Scheduled';

[User] Which citizens have submitted more than two applications? Provide their full name and the total number of applications.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name,
       COUNT(*) AS application_count
FROM government_services.citizens c
JOIN government_services.applications a
  ON c.citizen_id = a.citizen_id
GROUP BY c.citizen_id, c.first_name, c.last_name
HAVING COUNT(*) > 2;


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 erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

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

[Assistant] SELECT wallet_address, token_id, contract_address FROM nft_holders WHERE contract_type = 'ERC1155' AND CAST(amount AS decimal) > 1000;

[User] Can you join this with the nft_metadata table to include the name and image_uri of each token?

[Assistant] SELECT nh.wallet_address, nh.token_id, nh.contract_address, nm.name, nm.image_uri FROM nft_holders nh JOIN nft_metadata nm ON nh.contract_address = nm.contract_address AND nh.token_id = nm.token_id WHERE nh.contract_type = 'ERC1155' AND CAST(nh.amount AS decimal) > 1000;

[User] List each Avalanche token's total transfer volume over the past 7 days along with its creator from token_info.

[Assistant]
WITH recent_transfers AS (
  SELECT
    ta.tick,
    SUM(ta.amt) AS total_volume
  FROM token_activities_avalanche ta
  WHERE ta.block_timestamp >= now() - INTERVAL '7 days'
  GROUP BY ta.tick
)
SELECT
  rt.tick,
  rt.total_volume,
  ti.creator
FROM recent_transfers rt
LEFT JOIN token_info ti
  ON rt.tick = ti.tick
-- If token_info has multiple records per tick, pick the most recent:
  AND ti.block_timestamp = (
    SELECT MAX(block_timestamp)
    FROM token_info
    WHERE tick = rt.tick
  );

[User] Filter to tokens where total_volume > 10000 and creator starts with '0x1'.

[Assistant]
WITH recent_transfers AS (
  SELECT
    ta.tick,
    SUM(ta.amt) AS total_volume
  FROM token_activities_avalanche ta
  WHERE ta.block_timestamp >= now() - INTERVAL '7 days'
  GROUP BY ta.tick
)
SELECT
  rt.tick,
  rt.total_volume,
  ti.creator
FROM recent_transfers rt
LEFT JOIN token_info ti
  ON rt.tick = ti.tick
  AND ti.block_timestamp = (
    SELECT MAX(block_timestamp)
    FROM token_info
    WHERE tick = rt.tick
  )
WHERE rt.total_volume > 10000
  AND ti.creator LIKE '0x1%'
ORDER BY rt.total_volume DESC;

[User] For each NFT collection deployed on Ethereum, count the number of distinct wallets that have ever held any token from that collection.

[Assistant]
SELECT
  nc.contract_address,
  nc.name,
  COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM nft_collections nc
JOIN nft_holder_historical nh
  ON nc.contract_address = nh.contract_address
WHERE nc.blockchain = 'Ethereum'
GROUP BY nc.contract_address, nc.name;

[User] Include each collection's token_count and floor_price from nft_collections.

[Assistant]
SELECT
  nc.contract_address,
  nc.name,
  nc.token_count,
  nc.floor_price,
  COUNT(DISTINCT nh.wallet_address) AS holder_count
FROM nft_collections nc
JOIN nft_holder_historical nh
  ON nc.contract_address = nh.contract_address
WHERE nc.blockchain = 'Ethereum'
GROUP BY
  nc.contract_address,
  nc.name,
  nc.token_count,
  nc.floor_price;

[User] Show me all NFT collections on the 'Ethereum' blockchain, listing their name, contract address, and ERC type.

[Assistant] SELECT name, contract_address, erc_type FROM nft_collections WHERE blockchain = 'Ethereum'

[User] For these Ethereum collections, can you show the total number of unique wallets that have ever held an NFT from each collection by joining with the historical holder table?

[Assistant] SELECT nc.name, nc.contract_address, COUNT(DISTINCT nhh.wallet_address) AS unique_holders FROM nft_collections nc JOIN nft_holder_historical nhh ON nc.contract_address = nhh.contract_address WHERE nc.blockchain = 'Ethereum' GROUP BY nc.name, nc.contract_address

[User] Only show collections that have more than 100 unique holders, sorted by the number of unique holders descending.

[Assistant] SELECT nc.name, nc.contract_address, COUNT(DISTINCT nhh.wallet_address) AS unique_holders FROM nft_collections nc JOIN nft_holder_historical nhh ON nc.contract_address = nhh.contract_address WHERE nc.blockchain = 'Ethereum' GROUP BY nc.name, nc.contract_address HAVING COUNT(DISTINCT nhh.wallet_address) > 100 ORDER BY unique_holders DESC

[User] List all SUI coins that have 'active' status, showing object ID, coin type, and balance.

[Assistant] SELECT object_id, coin_type, balance FROM sui_coins WHERE status = 'active'

[User] Can you also include the owner address for these coins?

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active'

[User] Filter the results to only include coins where the balance is greater than 5000000.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND balance > 5000000

[User] Show me the top 20 largest balances from this list, sorted descending.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND balance > 5000000 ORDER BY balance DESC LIMIT 20

[User] Show ERC20 tokens with total supply greater than 100,000,000, displaying symbol, name, contract address, and total supply from the token_metas table.

[Assistant] SELECT symbol, name, contract_address, total_supply FROM token_metas WHERE total_supply > '100000000';

[User] Include the number of decimals for each token and the latest USD price by joining with token_prices_latest.

[Assistant] SELECT tm.symbol, tm.name, tm.contract_address, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.total_supply > '100000000';

[User] Filter the results to only include tokens where the latest USD price is less than 1.0.

[Assistant] SELECT tm.symbol, tm.name, tm.contract_address, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.total_supply > '100000000' AND tpl.price < 1.0;

[User] Order the results by total supply descending and limit to the top 15 tokens.

[Assistant] SELECT tm.symbol, tm.name, tm.contract_address, tm.total_supply, tm.decimals, tpl.price FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE tm.total_supply > '100000000' AND tpl.price < 1.0 ORDER BY CAST(tm.total_supply AS REAL) DESC LIMIT 15;

[User] List collection name, contract address, token count, and floor price for NFT collections on the Ethereum blockchain.

[Assistant] SELECT name, contract_address, token_count, floor_price FROM nft_collections WHERE blockchain = 'Ethereum';

[User] Also include the average rarity score for NFTs within each collection.

[Assistant] SELECT nc.name, nc.contract_address, nc.token_count, nc.floor_price, AVG(nm.rarity_score) AS avg_rarity_score FROM nft_collections nc JOIN nft_metadata nm ON nc.contract_address = nm.contract_address WHERE nc.blockchain = 'Ethereum' GROUP BY nc.name, nc.contract_address, nc.token_count, nc.floor_price;

[User] Filter the results to only include collections with an average rarity score above 75.

[Assistant] SELECT nc.name, nc.contract_address, nc.token_count, nc.floor_price, AVG(nm.rarity_score) AS avg_rarity_score FROM nft_collections nc JOIN nft_metadata nm ON nc.contract_address = nm.contract_address WHERE nc.blockchain = 'Ethereum' GROUP BY nc.name, nc.contract_address, nc.token_count, nc.floor_price HAVING AVG(nm.rarity_score) > 75;

[User] Order the results by average rarity score descending and limit to the top 10 collections.

[Assistant] SELECT nc.name, nc.contract_address, nc.token_count, nc.floor_price, AVG(nm.rarity_score) AS avg_rarity_score FROM nft_collections nc JOIN nft_metadata nm ON nc.contract_address = nm.contract_address WHERE nc.blockchain = 'Ethereum' GROUP BY nc.name, nc.contract_address, nc.token_count, nc.floor_price HAVING AVG(nm.rarity_score) > 75 ORDER BY avg_rarity_score DESC LIMIT 10;

[User] List all SUI coins with 'active' status, showing their owner address and balance.

[Assistant] SELECT owner, balance FROM sui_coins WHERE status = 'active';

[User] Add the coin type and object ID to the results.

[Assistant] SELECT owner, balance, coin_type, object_id FROM sui_coins WHERE status = 'active';

[User] Now, filter the results to only show coins where the balance is greater than '500000000' and sort by balance descending.

[Assistant] SELECT owner, balance, coin_type, object_id FROM sui_coins WHERE status = 'active' AND CAST(balance AS DECIMAL) > 500000000 ORDER BY CAST(balance AS DECIMAL) DESC;

[User] Limit the output to the top 10 results.

[Assistant] SELECT owner, balance, coin_type, object_id FROM sui_coins WHERE status = 'active' AND CAST(balance AS DECIMAL) > 500000000 ORDER BY CAST(balance AS DECIMAL) DESC LIMIT 10;

[User] List all NFTs minted on the Ethereum blockchain in the last 14 days, including their contract address, token ID, name, and minter.

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

[User] Show also the collection name for each NFT by joining with the nft_collections table.

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

[User] I only want NFTs where the rarity_score is above 80, and order the results by rarity_score descending.

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

[User] For each wallet that currently holds more than 5000 units of any ERC20 token, show the wallet address and contract address.

[Assistant]
SELECT contract_address, wallet_address, CAST(amount AS numeric) AS amount
FROM erc20_balances
WHERE CAST(amount AS numeric) > 5000;

[User] Can you also show the latest price for each token by joining with token_prices_latest?

[Assistant]
SELECT eb.contract_address, eb.wallet_address, CAST(eb.amount AS numeric) AS amount, tpl.price AS latest_price
FROM erc20_balances eb
LEFT JOIN token_prices_latest tpl
  ON tpl.address = eb.contract_address
WHERE CAST(eb.amount AS numeric) > 5000;

[User] Actually, I need only those results where the latest price is above 1.

[Assistant]
SELECT eb.contract_address, eb.wallet_address, CAST(eb.amount AS numeric) AS amount, tpl.price AS latest_price
FROM erc20_balances eb
LEFT JOIN token_prices_latest tpl
  ON tpl.address = eb.contract_address
WHERE CAST(eb.amount AS numeric) > 5000 AND tpl.price > 1;

[User] Add the decimals column from the token_prices_latest table in the result, and limit to the top 10 highest amounts.

[Assistant]
SELECT eb.contract_address, eb.wallet_address, CAST(eb.amount AS numeric) AS amount, tpl.price AS latest_price, tpl.decimals
FROM erc20_balances eb
LEFT JOIN token_prices_latest tpl
  ON tpl.address = eb.contract_address
WHERE CAST(eb.amount AS numeric) > 5000 AND tpl.price > 1
ORDER BY amount 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 transportation.vehicles (
    vehicle_id character varying(64) NOT NULL,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] I need to find the average maintenance cost per service type.

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type;

[User] Can you filter to only include service types with avg cost greater than 300?

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING AVG(cost) > 300;

[User] Also include the number of services for each of those types.

[Assistant]
SELECT service_type, COUNT(*) AS service_count, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING AVG(cost) > 300;

[User] Sort the result by avg_cost descending and show only the top 3 service types.

[Assistant]
SELECT service_type, COUNT(*) AS service_count, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING AVG(cost) > 300
ORDER BY avg_cost DESC
LIMIT 3;

[User] Retrieve each completed booking's booking_id, passenger full name, trip_id, scheduled_departure, and fare for bookings where the trip's passenger_count is at least 10.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_name, b.trip_id, t.scheduled_departure, b.fare
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
JOIN transportation.trips t ON b.trip_id = t.trip_id
WHERE b.status = 'Completed'
  AND t.passenger_count >= 10;

[User] Retrieve each vehicle's latest maintenance service date and mechanic alongside its make and model.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, ml.service_date, ml.mechanic_name
FROM transportation.vehicles v
JOIN transportation.maintenance_logs ml ON v.vehicle_id = ml.vehicle_id
WHERE ml.service_date = (
    SELECT MAX(service_date)
    FROM transportation.maintenance_logs
    WHERE vehicle_id = v.vehicle_id
);

[User] For each route, show the route_number, origin and destination location names with their cities, and the average departure delay (in minutes) for trips where actual_departure was later than scheduled_departure.

[Assistant]
SELECT r.route_number,
       lo.name       AS origin_name,
       lo.city       AS origin_city,
       ld.name       AS destination_name,
       ld.city       AS destination_city,
       AVG(EXTRACT(EPOCH FROM (t.actual_departure - t.scheduled_departure)) / 60) AS avg_delay_minutes
FROM transportation.routes r
JOIN transportation.trips t
  ON r.route_id = t.route_id
JOIN transportation.locations lo
  ON r.origin_location_id = lo.location_id
JOIN transportation.locations ld
  ON r.destination_location_id = ld.location_id
WHERE t.actual_departure > t.scheduled_departure
GROUP BY r.route_number, origin_name, origin_city, destination_name, destination_city;

[User] Count the number of maintenance services per service_type and show service_type and service_count.

[Assistant]
SELECT service_type, COUNT(*) AS service_count
FROM transportation.maintenance_logs
GROUP BY service_type;

[User] Only include service types with more than 5 services and order the results by service_count descending.

[Assistant]
SELECT service_type, COUNT(*) AS service_count
FROM transportation.maintenance_logs
GROUP BY service_type
HAVING COUNT(*) > 5
ORDER BY service_count DESC;

[User] I need a list of all routes and the number of trips made on each route.

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

[User] Actually, show the route_number and description instead of route_id.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description;

[User] Also, only include routes with more than 20 trips and sort by trip_count descending.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description
HAVING COUNT(t.trip_id) > 20
ORDER BY trip_count DESC;

[User] Finally, display the average passenger count per trip for each of these routes.

[Assistant]
SELECT r.route_number,
       r.description,
       COUNT(t.trip_id) AS trip_count,
       AVG(t.passenger_count) AS avg_passengers
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
GROUP BY r.route_number, r.description
HAVING COUNT(t.trip_id) > 20
ORDER BY trip_count DESC;

[User] Show me the top 3 vehicles with the highest average passenger count on completed trips, and include each vehicle's license plate, make, and the average passenger count.

[Assistant]
SELECT v.vehicle_id,
       v.license_plate,
       v.make,
       AVG(t.passenger_count) AS avg_passengers
FROM transportation.vehicles v
JOIN transportation.trips t
  ON v.vehicle_id = t.vehicle_id
WHERE t.status = 'Completed'
GROUP BY v.vehicle_id, v.license_plate, v.make
ORDER BY avg_passengers DESC
LIMIT 3;

[User] List all drivers who have operated trips using Electric vehicles. Include driver ID, full name, and the number of Electric trips they've operated.

[Assistant]
SELECT d.driver_id, d.first_name || ' ' || d.last_name AS full_name, COUNT(*) AS electric_trip_count
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE v.fuel_type = 'Electric'
GROUP BY d.driver_id, d.first_name, d.last_name;

[User] Now, show only drivers who have operated at least 2 Electric trips.

[Assistant]
SELECT d.driver_id, d.first_name || ' ' || d.last_name AS full_name, COUNT(*) AS electric_trip_count
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE v.fuel_type = 'Electric'
GROUP BY d.driver_id, d.first_name, d.last_name
HAVING COUNT(*) >= 2;

[User] Can you also include each driver's email and hire date in the result?

[Assistant]
SELECT d.driver_id, d.first_name || ' ' || d.last_name AS full_name, d.email, d.hire_date, COUNT(*) AS electric_trip_count
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE v.fuel_type = 'Electric'
GROUP BY d.driver_id, d.first_name, d.last_name, d.email, d.hire_date
HAVING COUNT(*) >= 2;

[User] Sorry, I got an error saying that 'email' and 'hire_date' must appear in the GROUP BY clause. Can you fix the query?

[Assistant]
SELECT d.driver_id, d.first_name || ' ' || d.last_name AS full_name, d.email, d.hire_date, COUNT(*) AS electric_trip_count
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id
WHERE v.fuel_type = 'Electric'
GROUP BY d.driver_id, d.first_name, d.last_name, d.email, d.hire_date
HAVING COUNT(*) >= 2;

[User] Show the average maintenance cost for vehicles of each make, including only vehicles that have had at least one maintenance log.

[Assistant] SELECT v.make, AVG(ml.cost) AS average_maintenance_cost FROM transportation.vehicles AS v JOIN transportation.maintenance_logs AS ml ON v.vehicle_id = ml.vehicle_id GROUP BY v.make ORDER BY average_maintenance_cost DESC;

[User] List all bookings with the passenger's full name, booking status, and fare amount, but only for bookings where the fare is greater than 50.

[Assistant] SELECT p.first_name, p.last_name, b.status, b.fare FROM transportation.bookings b JOIN transportation.passengers p ON b.passenger_id = p.passenger_id WHERE b.fare > 50;