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 token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )

[User] List all tokens with a price below $1 and a 24-hour trading volume over $5 million.

[Assistant] SELECT token_name, token_symbol, price, total_volume FROM token_basic_info WHERE price < 1 AND total_volume::numeric > 5000000;

[User] For the 'DeFi' narrative, what is the average price, average market cap, and average 24-hour trading volume of its tokens?

[Assistant] SELECT AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume FROM token_basic_info WHERE narrative = 'DeFi'

[User] Instead of just 'DeFi', show these average metrics (price, market cap, 24h volume) for *all* narratives.

[Assistant] SELECT narrative, AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume FROM token_basic_info WHERE narrative IS NOT NULL GROUP BY narrative

[User] Only include narratives with at least 10 tokens and an average market cap above $500,000,000. Order the results by average market cap descending and show the top 5.

[Assistant] SELECT narrative, AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume FROM token_basic_info WHERE narrative IS NOT NULL GROUP BY narrative HAVING COUNT(*) >= 10 AND AVG(market_cap) > 500000000 ORDER BY avg_market_cap DESC LIMIT 5

[User] Also include the average trend rank for each of these narratives.

[Assistant] SELECT narrative, AVG(price) AS avg_price, AVG(market_cap) AS avg_market_cap, AVG(CAST(total_volume AS DOUBLE PRECISION)) AS avg_total_volume, AVG(trend_rank) AS avg_trend_rank FROM token_basic_info WHERE narrative IS NOT NULL GROUP BY narrative HAVING COUNT(*) >= 10 AND AVG(market_cap) > 500000000 ORDER BY avg_market_cap DESC LIMIT 5

[User] Show me the top 3 tokens by trend rank in the 'NFT' narrative, along with their price and 24-hour trading volume.

[Assistant] SELECT token_name, token_symbol, price, total_volume FROM token_basic_info WHERE narrative = 'NFT' ORDER BY trend_rank ASC LIMIT 3;

[User] Can you also include their 1-hour and 7-day price change percentages?

[Assistant] SELECT token_name, token_symbol, price, total_volume, price_change_percentage_1h, price_change_percentage_7d FROM token_basic_info WHERE narrative = 'NFT' ORDER BY trend_rank ASC LIMIT 3;

[User] Actually, I only want tokens with positive price changes in both time frames.

[Assistant] SELECT token_name, token_symbol, price, total_volume, price_change_percentage_1h, price_change_percentage_7d FROM token_basic_info WHERE narrative = 'NFT' AND price_change_percentage_1h > 0 AND price_change_percentage_7d > 0 ORDER BY trend_rank ASC LIMIT 3;

[User] Now order the results by 24-hour trading volume instead of trend rank.

[Assistant] SELECT token_name, token_symbol, price, total_volume, price_change_percentage_1h, price_change_percentage_7d FROM token_basic_info WHERE narrative = 'NFT' AND price_change_percentage_1h > 0 AND price_change_percentage_7d > 0 ORDER BY total_volume::numeric DESC LIMIT 3;

[User] Show tokens with a trend rank worse than 30 (higher number) that also have a positive price change over the last 24 hours. Display their symbol, chain, price, trend rank, and 24h price change.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0

[User] Only show results for tokens on the 'Ethereum' chain.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0 AND chain = 'Ethereum'

[User] Also filter for tokens with a market cap greater than $100,000,000.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0 AND chain = 'Ethereum' AND market_cap > 100000000

[User] Order the results by 24-hour price change percentage descending and show the top 10.

[Assistant] SELECT token_symbol, chain, price, trend_rank, price_change_percentage_24h FROM token_basic_info WHERE trend_rank > 30 AND price_change_percentage_24h > 0 AND chain = 'Ethereum' AND market_cap > 100000000 ORDER BY price_change_percentage_24h DESC LIMIT 10

[User] List tokens that have a 24-hour trading volume greater than $10,000,000 and a negative price change percentage over the last 24 hours. Show the token symbol, chain, total volume, and the 24-hour price change percentage.

[Assistant] SELECT token_symbol, chain, total_volume, price_change_percentage_24h FROM token_basic_info WHERE CAST(REPLACE(total_volume, ',', '') AS numeric) > 10000000 AND price_change_percentage_24h < 0

[User] From those results, filter further to only include tokens with a market cap rank of 100 or better. Order the results by 24-hour trading volume in descending order.

[Assistant] SELECT token_symbol, chain, total_volume, price_change_percentage_24h FROM token_basic_info WHERE CAST(REPLACE(total_volume, ',', '') AS numeric) > 10000000 AND price_change_percentage_24h < 0 AND market_cap_rank IS NOT NULL AND market_cap_rank <= 100 ORDER BY CAST(REPLACE(total_volume, ',', '') AS numeric) DESC

[User] What is the average market cap for all tokens belonging to the 'GameFi' narrative?

[Assistant] SELECT AVG(market_cap) FROM token_basic_info WHERE narrative = 'GameFi'

[User] Find tokens on the 'Polygon' chain with a market cap greater than $1,000,000,000 and a positive price change in the last 24 hours. List their symbol, name, market cap, and 24h price change.

[Assistant] SELECT token_symbol, token_name, market_cap, price_change_percentage_24h FROM token_basic_info WHERE chain = 'Polygon' AND market_cap > 1000000000 AND price_change_percentage_24h > 0;

[User] Also include their current price and 7-day price change percentage. Order the results by market cap descending.

[Assistant] SELECT token_symbol, token_name, market_cap, price_change_percentage_24h, price, price_change_percentage_7d FROM token_basic_info WHERE chain = 'Polygon' AND market_cap > 1000000000 AND price_change_percentage_24h > 0 ORDER BY market_cap 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 character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    primary_contact_email character varying(128),
    main_phone_number character varying(32),
    website_url character varying(255),
    established_date date,
    parent_agency_id character varying(64), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)

[User] List all applications including the application reference number, the first and last name of the citizen who submitted it, and the name of the service the application is for.

[Assistant] SELECT T1.reference_number, T2.first_name, T2.last_name, T3.service_name FROM applications AS T1 JOIN citizens AS T2 ON T1.citizen_id = T2.citizen_id JOIN services AS T3 ON T1.service_id = T3.service_id

[User] For citizens who registered before January 1, 2023, show the total number of notifications sent to them for each channel. List the citizen's first name, last name, the channel, and the count of notifications.

[Assistant]
SELECT
  T1.first_name,
  T1.last_name,
  T2.channel,
  COUNT(T2.notification_id) AS notification_count
FROM government_services.citizens AS T1
INNER JOIN government_services.notifications AS T2
  ON T1.citizen_id = T2.citizen_id
WHERE
  T1.registration_date < '2023-01-01'
GROUP BY
  T1.citizen_id,
  T1.first_name,
  T1.last_name,
  T2.channel;

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

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

[User] List all applications that have at least one document with a verification status of 'Verified'. Show the application reference number and the name of the service associated with the application.

[Assistant]
SELECT
  T1.reference_number,
  T2.service_name
FROM government_services.applications AS T1
INNER JOIN government_services.services AS T2
  ON T1.service_id = T2.service_id
WHERE EXISTS (
  SELECT
    1
  FROM government_services.documents AS T3
  WHERE
    T3.application_id = T1.application_id AND T3.verification_status = 'Verified'
);

[User] Now, only include applications that were submitted in the year 2024.

[Assistant]
SELECT
  T1.reference_number,
  T2.service_name
FROM government_services.applications AS T1
INNER JOIN government_services.services AS T2
  ON T1.service_id = T2.service_id
WHERE EXISTS (
  SELECT
    1
  FROM government_services.documents AS T3
  WHERE
    T3.application_id = T1.application_id AND T3.verification_status = 'Verified'
)
AND EXTRACT(YEAR FROM T1.submitted_at) = 2024;

[User] List the first name, last name, and job title for all employees, along with the name of the agency they belong to.

[Assistant] SELECT T1.first_name, T1.last_name, T1.job_title, T2.agency_name FROM employees AS T1 JOIN agencies AS T2 ON T1.agency_id = T2.agency_id

[User] Provide a breakdown of the total number of applications submitted for each service category.

[Assistant] SELECT T2.category, count(T1.application_id) FROM applications AS T1 JOIN services AS T2 ON T1.service_id = T2.service_id GROUP BY T2.category

[User] Could you filter that list to only include categories with more than 50 applications?

[Assistant] SELECT T2.category, count(T1.application_id) FROM applications AS T1 JOIN services AS T2 ON T1.service_id = T2.service_id GROUP BY T2.category HAVING count(T1.application_id) > 50

[User] For each appointment, show the appointment ID, scheduled start time, the name of the service related to the appointment, and the agency name.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, s.service_name, ag.agency_name
FROM government_services.appointments a
JOIN government_services.services s ON a.service_id = s.service_id
JOIN government_services.agencies ag ON s.agency_id = ag.agency_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 smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )

[User] For each chain, show the total token_amount and usd_value for selling transactions (type=2).

[Assistant]
SELECT chain, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain;

[User] Can you break down these results further by narrative as well?

[Assistant]
SELECT chain, narrative, SUM(token_amount) AS total_sold_amount, SUM(usd_value) AS total_sold_usd_value
FROM smart_money_token_inflow
WHERE type = 2
GROUP BY chain, narrative;

[User] Which token symbols have the highest number of addresses buying them on the Ethereum chain? Show the top 3 symbols, their total address_amount, and narrative.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] I got incorrect results. I only want results where the summed address_amount is at least 10.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] Please add the total usd_value spent on buying each of these tokens.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses, SUM(usd_value) AS total_buy_usd_value
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] Also include the average price (avg_price) for each token.

[Assistant]
SELECT token_symbol, narrative, SUM(address_amount) AS total_buying_addresses, SUM(usd_value) AS total_buy_usd_value, AVG(avg_price) AS average_price
FROM smart_money_token_inflow
WHERE type = 1 AND chain = 'Ethereum'
GROUP BY token_symbol, narrative
HAVING SUM(address_amount) >= 10
ORDER BY total_buying_addresses DESC
LIMIT 3;

[User] How many distinct tokens did smart money buy on the 'BSC' chain in 2023?

[Assistant]
SELECT COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31';

[User] Can you break this down by narrative and show the count per narrative?

[Assistant]
SELECT narrative, COUNT(DISTINCT token_address) AS distinct_tokens_bought
FROM smart_money_token_inflow
WHERE type = 1
  AND chain = 'BSC'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') >= '2023-01-01'
  AND to_char(cast(token_address AS text), 'YYYY-MM-DD') <= '2023-12-31'
GROUP BY narrative
ORDER BY distinct_tokens_bought DESC;

[User] List all token symbols related to the 'Gaming' narrative that had a net positive token inflow.

[Assistant] SELECT token_symbol FROM smart_money_token_inflow WHERE narrative = 'Gaming' AND usd_value > 0 GROUP BY token_symbol;

[User] Which narrative had the highest total USD token inflow during Q1 of 2024, and which chain did these inflows primarily occur on?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 1;

[User] Could you modify the query to show the top 3 narratives by total inflow, along with their corresponding chains?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 3;

[User] What are the top 3 narratives by average USD purchase value per address (for buy transactions) across all chains?

[Assistant]
SELECT narrative, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Also include the chain in the output and compute results per narrative and chain.

[Assistant]
SELECT narrative, chain, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Only show combinations where the total address_amount is greater than 50.

[Assistant]
SELECT narrative, chain, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address, SUM(address_amount) AS total_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
HAVING SUM(address_amount) > 50
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] Add the total usd_value for each narrative and chain as a column in the result.

[Assistant]
SELECT narrative, chain, SUM(usd_value) AS total_usd_value, AVG(usd_value::float / NULLIF(address_amount,0)) AS avg_usd_per_address, SUM(address_amount) AS total_addresses
FROM smart_money_token_inflow
WHERE type = 1 AND address_amount > 0
GROUP BY narrative, chain
HAVING SUM(address_amount) > 50
ORDER BY avg_usd_per_address DESC
LIMIT 3;

[User] For each chain, which token had the highest number of smart money addresses buying it this week? Show the token symbol and narrative too.

[Assistant] SELECT chain, token_symbol, narrative, MAX(address_amount) AS max_buyers FROM smart_money_token_inflow WHERE type = 1 AND DATE_TRUNC('week', CURRENT_DATE) = DATE_TRUNC('week', CURRENT_DATE) GROUP BY chain, token_symbol, narrative;

[User] I got an error, I think the filter for the week may be wrong. Please revise the query so that it only counts buys from the current week.

[Assistant] SELECT chain, token_symbol, narrative, address_amount AS buyers FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(week FROM CURRENT_DATE) = EXTRACT(week FROM CURRENT_DATE) AND EXTRACT(year FROM CURRENT_DATE) = EXTRACT(year FROM CURRENT_DATE) ORDER BY chain, buyers 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.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )

[User] What is the average and maximum standard fee for services in each category?

[Assistant] SELECT category, AVG(standard_fee) AS avg_standard_fee, MAX(standard_fee) AS max_standard_fee FROM government_services.services GROUP BY category;

[User] Could you list pairs of services that belong to different agencies but share the same category? Provide the service names and their agency_ids.

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

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

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

[User] What is the average processing time in days for each service category?

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
GROUP BY category;

[User] Only include categories where the average_processing_time_days is greater than 5.

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
GROUP BY category
HAVING AVG(average_processing_time_days) > 5;

[User] Also include only active services in the calculation.

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
WHERE is_active = TRUE
GROUP BY category
HAVING AVG(average_processing_time_days) > 5;

[User] Sort the results by avg_processing_time in descending order.

[Assistant]
SELECT category, AVG(average_processing_time_days) AS avg_processing_time
FROM government_services.services
WHERE is_active = TRUE
GROUP BY category
HAVING AVG(average_processing_time_days) > 5
ORDER BY avg_processing_time DESC;

[User] Find for each category the service with the highest standard_fee and the service with the lowest standard_fee. Display the category, highest_fee_service, and lowest_fee_service.

[Assistant]
SELECT m.category,
       s_max.service_name AS highest_fee_service,
       s_min.service_name AS lowest_fee_service
FROM (
  SELECT category,
         MAX(standard_fee) AS max_fee,
         MIN(standard_fee) AS min_fee
  FROM government_services.services
  GROUP BY category
) m
JOIN government_services.services s_max
  ON s_max.category = m.category
  AND s_max.standard_fee = m.max_fee
JOIN government_services.services s_min
  ON s_min.category = m.category
  AND s_min.standard_fee = m.min_fee;

[User] Which agencies offer more than one type of service category? List the agency_id and the number of distinct categories they provide.

[Assistant] SELECT agency_id, COUNT(DISTINCT category) AS category_count FROM government_services.services GROUP BY agency_id HAVING COUNT(DISTINCT category) > 1;

[User] List all services whose eligibility criteria mention 'citizen'.

[Assistant] SELECT service_id, service_name, eligibility_criteria FROM government_services.services WHERE eligibility_criteria ILIKE '%citizen%';

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)

[User] List users who commented on posts and the content of the post they commented on. Show commenter username and post content.

[Assistant] SELECT T1.username, T2.content FROM social_media.users AS T1 JOIN social_media.comments AS T3 ON T1.user_id = T3.user_id JOIN social_media.posts AS T2 ON T3.post_id = T2.post_id;

[User] Now, only include those users who also liked the specific post they commented on.

[Assistant] SELECT T1.username, T2.content FROM social_media.users AS T1 JOIN social_media.comments AS T3 ON T1.user_id = T3.user_id JOIN social_media.posts AS T2 ON T3.post_id = T2.post_id JOIN social_media.likes AS T4 ON T1.user_id = T4.user_id AND T2.post_id = T4.post_id;

[User] Show me the usernames and full names of all users who have liked at least one post that was created in May 2024.

[Assistant]
SELECT DISTINCT u.username, u.full_name
FROM social_media.users u
JOIN social_media.likes l ON u.user_id = l.user_id
JOIN social_media.posts p ON l.post_id = p.post_id
WHERE p.created_at >= '2024-05-01' AND p.created_at < '2024-06-01';

[User] Some of these users appear multiple times. Can you also include the count of distinct posts they have liked from May 2024, as liked_posts_count?

[Assistant]
SELECT u.username, u.full_name, COUNT(DISTINCT p.post_id) AS liked_posts_count
FROM social_media.users u
JOIN social_media.likes l ON u.user_id = l.user_id
JOIN social_media.posts p ON l.post_id = p.post_id
WHERE p.created_at >= '2024-05-01' AND p.created_at < '2024-06-01'
GROUP BY u.user_id, u.username, u.full_name;

[User] Now, only show users who have liked more than 2 distinct posts from May 2024 and order them by liked_posts_count descending.

[Assistant]
SELECT u.username, u.full_name, COUNT(DISTINCT p.post_id) AS liked_posts_count
FROM social_media.users u
JOIN social_media.likes l ON u.user_id = l.user_id
JOIN social_media.posts p ON l.post_id = p.post_id
WHERE p.created_at >= '2024-05-01' AND p.created_at < '2024-06-01'
GROUP BY u.user_id, u.username, u.full_name
HAVING COUNT(DISTINCT p.post_id) > 2
ORDER BY liked_posts_count DESC;

[User] Show me the usernames and email addresses for users who have a non-empty bio and are verified.

[Assistant] SELECT username, email FROM social_media.users WHERE bio IS NOT NULL AND bio != '' AND is_verified = TRUE;

[User] For each user, show their username, email, and the number of posts they've created that contain at least one hashtag. Only include users who have created such posts.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT p.post_id) AS posts_with_hashtag_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
GROUP BY u.user_id, u.username, u.email
HAVING COUNT(DISTINCT p.post_id) > 0;

[User] Actually, I'd like to see, for each user, the total number of unique hashtags they've used across their posts too. Please include that as unique_hashtags_count.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT p.post_id) AS posts_with_hashtag_count, COUNT(DISTINCT ph.hashtag_id) AS unique_hashtags_count
FROM social_media.users u
JOIN social_media.posts p ON u.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
GROUP BY u.user_id, u.username, u.email
HAVING COUNT(DISTINCT p.post_id) > 0;

[User] List each conversation_id and the number of unread messages (where read_at is null).

[Assistant] SELECT m.conversation_id, COUNT(*) AS unread_messages FROM social_media.messages m WHERE m.read_at IS NULL GROUP BY m.conversation_id;

[User] Now only include group chats and show the group_name.

[Assistant] SELECT c.conversation_id, c.group_name, COUNT(m.message_id) AS unread_messages FROM social_media.conversations c JOIN social_media.messages m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND m.read_at IS NULL GROUP BY c.conversation_id, c.group_name;

[User] List each user and their total number of followers, including username, ordered by follower count descending.

[Assistant] SELECT u.user_id, u.username, COUNT(f.follower_user_id) AS follower_count FROM social_media.users u LEFT JOIN social_media.follows f ON u.user_id = f.following_user_id GROUP BY u.user_id, u.username ORDER BY follower_count DESC;

[User] Filter to only include users who have email_notifications_enabled = true.

[Assistant] SELECT u.user_id, u.username, COUNT(f.follower_user_id) AS follower_count FROM social_media.users u JOIN social_media.user_settings s ON u.user_id = s.user_id AND s.email_notifications_enabled = true LEFT JOIN social_media.follows f ON u.user_id = f.following_user_id GROUP BY u.user_id, u.username ORDER BY follower_count DESC;

[User] Also include only those users who are verified.

[Assistant] SELECT u.user_id, u.username, COUNT(f.follower_user_id) AS follower_count FROM social_media.users u JOIN social_media.user_settings s ON u.user_id = s.user_id AND s.email_notifications_enabled = true LEFT JOIN social_media.follows f ON u.user_id = f.following_user_id WHERE u.is_verified = true GROUP BY u.user_id, u.username ORDER BY follower_count DESC;

[User] Limit the results to the top 5 users.

[Assistant] SELECT u.user_id, u.username, COUNT(f.follower_user_id) AS follower_count FROM social_media.users u JOIN social_media.user_settings s ON u.user_id = s.user_id AND s.email_notifications_enabled = true LEFT JOIN social_media.follows f ON u.user_id = f.following_user_id WHERE u.is_verified = true GROUP BY u.user_id, u.username ORDER BY follower_count DESC LIMIT 5;

[User] List all group chats created in 2024, showing the group_name, conversation_id, and creation time.

[Assistant]
SELECT conversation_id, group_name, created_at
FROM social_media.conversations
WHERE is_group_chat = true AND created_at >= '2024-01-01' AND created_at < '2025-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )

[User] List all payments processed in USD, showing payment_id, guest_id, amount, and payment_timestamp.

[Assistant]
SELECT payment_id,
       guest_id,
       amount,
       payment_timestamp
FROM hospitality_technology.payments
WHERE currency_code = 'USD';

[User] Actually, only include those with amount greater than 1000.

[Assistant]
SELECT payment_id,
       guest_id,
       amount,
       payment_timestamp
FROM hospitality_technology.payments
WHERE currency_code = 'USD'
  AND amount > 1000;

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

[Assistant]
SELECT payment_id,
       guest_id,
       amount,
       payment_timestamp
FROM hospitality_technology.payments
WHERE currency_code = 'USD'
  AND amount > 1000
ORDER BY amount DESC
LIMIT 5;

[User] Show the total payment amount grouped by currency_code and filtered to only include payments with status 'Pending' or 'Failed'.

[Assistant] SELECT currency_code, SUM(amount) AS total_amount FROM hospitality_technology.payments WHERE status IN ('Pending', 'Failed') GROUP BY currency_code;

[User] Actually, please break down the result further by payment method as well.

[Assistant] SELECT currency_code, payment_method, SUM(amount) AS total_amount FROM hospitality_technology.payments WHERE status IN ('Pending', 'Failed') GROUP BY currency_code, payment_method;

[User] Can you also count the number of distinct guests for each combination of currency_code and payment_method in the result?

[Assistant] SELECT currency_code, payment_method, SUM(amount) AS total_amount, COUNT(DISTINCT guest_id) AS guest_count FROM hospitality_technology.payments WHERE status IN ('Pending', 'Failed') GROUP BY currency_code, payment_method;

[User] Show the total payment amount and the number of payments processed by each staff member, including their staff_id_processed.

[Assistant] SELECT staff_id_processed, SUM(amount) AS total_payment_amount, COUNT(payment_id) AS payment_count FROM hospitality_technology.payments GROUP BY staff_id_processed;

[User] Show me all payments made with a credit card (payment_method = 'credit_card') where the amount is greater than $500, including the reservation ID and payment timestamp.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 ORDER BY payment_timestamp DESC;

[User] Now, include only payments that were processed by staff members with ID starting with 'STAFF1' and show the card type used.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp, card_type FROM hospitality_technology.payments WHERE payment_method = 'credit_card' AND amount > 500 AND staff_id_processed LIKE 'STAFF1%' ORDER BY payment_timestamp DESC;

[User] List all failed payments (status = 'failed') with their reservation IDs and amounts, ordered by the payment timestamp.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp FROM hospitality_technology.payments WHERE status = 'failed' ORDER BY payment_timestamp;

[User] Now, filter these to only include payments made in USD (currency_code = 'USD') and show the payment method used.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp, payment_method FROM hospitality_technology.payments WHERE status = 'failed' AND currency_code = 'USD' ORDER BY payment_timestamp;

[User] The query is missing the staff who processed these payments. Can you include that as well?

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp, payment_method, staff_id_processed FROM hospitality_technology.payments WHERE status = 'failed' AND currency_code = 'USD' ORDER BY payment_timestamp;

[User] Actually, I only need payments processed in the last 30 days and want to see the last four digits of the card used.

[Assistant] SELECT payment_id, reservation_id, amount, payment_timestamp, payment_method, staff_id_processed, card_last_four FROM hospitality_technology.payments WHERE status = 'failed' AND currency_code = 'USD' AND payment_timestamp >= NOW() - INTERVAL '30 days' ORDER BY payment_timestamp;

[User] List all payments made using a credit card, including guest_id, amount, payment_method, and payment_timestamp.

[Assistant] SELECT guest_id, amount, payment_method, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'CreditCard';

[User] Could you also include the last four digits of the card used for each payment?

[Assistant] SELECT guest_id, amount, payment_method, card_last_four, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'CreditCard';

[User] Show the total amount of payments processed by each payment_method.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
GROUP BY payment_method;

[User] Include only payments with status 'Succeeded' or 'Pending', and order by total_amount descending.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
WHERE status IN ('Succeeded', 'Pending')
GROUP BY payment_method
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
Node Label ':AircraftModel'. Properties: { model_id: String (Constraint: UNIQUE), model_name: String, manufacturer: String, passenger_capacity: Integer, max_range_km: Integer, engine_type: String, wingspan_m: Float, status: String, first_flight_date: Date }. Index on model_id.
Node Label ':Component'. Properties: { component_id: String (Constraint: UNIQUE), part_number: String (Constraint: UNIQUE), component_name: String, description: String, weight_kg: Float, cost_usd: Float, criticality_level: String }. Relationships: (:Component)-[:MADE_OF]->(:Material {material_id}), (:Component)-[:SUPPLIED_BY]->(:Supplier {supplier_id}). Index on component_id, part_number.
Node Label ':Material'. Properties: { material_id: String (Constraint: UNIQUE), material_name: String, specification: String, description: String, density_kg_m3: Float, tensile_strength_mpa: Integer }. Index on material_id.
Node Label ':AssemblyLine'. Properties: { line_id: String (Constraint: UNIQUE), line_name: String, location_building: String, location_area: String, capacity_units_per_month: Integer, status: String }. Relationship: (:AssemblyLine)-[:BUILDS_MODEL]->(:AircraftModel {model_id}). Index on line_id.
Node Label ':AssemblyStep'. Properties: { step_id: String (Constraint: UNIQUE), step_number: Integer, step_name: String, description: String, standard_duration_hours: Float, required_skill_level: String, workstation: String }. Relationship: (:AssemblyLine {line_id})-[:HAS_STEP {sequence: <step_number>}]->(:AssemblyStep). Index on step_id.
Node Label ':AircraftBuild'. Properties: { build_id: String (Constraint: UNIQUE), serial_number: String (Constraint: UNIQUE), build_start_date: Datetime, estimated_completion_date: Date, actual_completion_date: Datetime, current_status: String, customer_order_id: String }. Relationships: (:AircraftBuild)-[:IS_MODEL]->(:AircraftModel {model_id}), (:AircraftBuild)-[:ASSEMBLED_ON]->(:AssemblyLine {line_id}). Index on build_id, serial_number, current_status.
Node Label ':Inspection'. Properties: { inspection_id: String (Constraint: UNIQUE), inspection_type: String, inspection_timestamp: Datetime, result: String, remarks: String }. Relationships: (:AircraftBuild {build_id})-[:UNDERWENT]->(:Inspection), (:Inspection)-[:PERFORMED_BY]->(:Employee {employee_id}), (:Inspection)-[:INSPECTED_COMPONENT]->(:Component {component_id}) (optional), (:Inspection)-[:FOLLOWED_STEP]->(:AssemblyStep {step_id}) (optional). Index on inspection_id.

[User] 我想获取某个组件的详细信息，包括组件名称、描述、重量以及成本。

[Assistant]
MATCH (c:Component)
WHERE c.component_id = 'specific_component_id'
RETURN c.component_name, c.description, c.weight_kg, c.cost_usd

[User] 如果我想筛选出重量大于5公斤的组件，应该怎么修改查询？

[Assistant]
MATCH (c:Component)
WHERE c.component_id = 'specific_component_id' AND c.weight_kg > 5
RETURN c.component_name, c.description, c.weight_kg, c.cost_usd

[User] 能否再加上一个条件，只显示成本低于5000美元的组件？

[Assistant]
MATCH (c:Component)
WHERE c.component_id = 'specific_component_id' AND c.weight_kg > 5 AND c.cost_usd < 5000
RETURN c.component_name, c.description, c.weight_kg, c.cost_usd

[User] 请再加上关键性等级字段，并且按成本从低到高排序。

[Assistant]
MATCH (c:Component)
WHERE c.component_id = 'specific_component_id' AND c.weight_kg > 5 AND c.cost_usd < 5000
RETURN c.component_name, c.description, c.weight_kg, c.cost_usd, c.criticality_level
ORDER BY c.cost_usd ASC

[User] 我想查询某个飞机构建的所有检查记录，包括检查类型、检查结果、检查时间以及被检查的组件名称。

[Assistant]
MATCH (ab:AircraftBuild)-[:UNDERWENT]->(i:Inspection)-[:INSPECTED_COMPONENT]->(c:Component)
WHERE ab.build_id = 'specific_build_id'
RETURN i.inspection_type, i.result, i.inspection_timestamp, c.component_name

[User] 如果我想只显示检查结果为'Fail'的记录，应该怎么修改？

[Assistant]
MATCH (ab:AircraftBuild)-[:UNDERWENT]->(i:Inspection)-[:INSPECTED_COMPONENT]->(c:Component)
WHERE ab.build_id = 'specific_build_id' AND i.result = 'Fail'
RETURN i.inspection_type, i.result, i.inspection_timestamp, c.component_name

[User] 能否再加上一个条件，只显示检查时间在2023年6月1日之后的记录？

[Assistant]
MATCH (ab:AircraftBuild)-[:UNDERWENT]->(i:Inspection)-[:INSPECTED_COMPONENT]->(c:Component)
WHERE ab.build_id = 'specific_build_id' AND i.result = 'Fail' AND i.inspection_timestamp >= datetime('2023-06-01')
RETURN i.inspection_type, i.result, i.inspection_timestamp, c.component_name

[User] 请再加上检查备注字段，并按检查时间从新到旧排序。

[Assistant]
MATCH (ab:AircraftBuild)-[:UNDERWENT]->(i:Inspection)-[:INSPECTED_COMPONENT]->(c:Component)
WHERE ab.build_id = 'specific_build_id' AND i.result = 'Fail' AND i.inspection_timestamp >= datetime('2023-06-01')
RETURN i.inspection_type, i.result, i.inspection_timestamp, c.component_name, i.remarks
ORDER BY i.inspection_timestamp DESC

[User] 我想查询某个飞机型号的所有构建信息，包括构建的开始日期、预计完成日期以及所在的装配线名称和位置。

[Assistant]
MATCH (am:AircraftModel)-[:IS_MODEL]-(ab:AircraftBuild)-[:ASSEMBLED_ON]->(al:AssemblyLine)
WHERE am.model_id = 'specific_model_id'
RETURN ab.build_id, ab.build_start_date, ab.estimated_completion_date, al.line_name, al.location_building, al.location_area

[User] 能否只显示当前状态为'In Progress'的构建记录？

[Assistant]
MATCH (am:AircraftModel)-[:IS_MODEL]-(ab:AircraftBuild)-[:ASSEMBLED_ON]->(al:AssemblyLine)
WHERE am.model_id = 'specific_model_id' AND ab.current_status = 'In Progress'
RETURN ab.build_id, ab.build_start_date, ab.estimated_completion_date, al.line_name, al.location_building, al.location_area

[User] 如果我想进一步筛选出开始日期在2023年1月1日之后的记录，应该怎么做？

[Assistant]
MATCH (am:AircraftModel)-[:IS_MODEL]-(ab:AircraftBuild)-[:ASSEMBLED_ON]->(al:AssemblyLine)
WHERE am.model_id = 'specific_model_id' AND ab.current_status = 'In Progress' AND ab.build_start_date >= datetime('2023-01-01')
RETURN ab.build_id, ab.build_start_date, ab.estimated_completion_date, al.line_name, al.location_building, al.location_area

[User] 请按构建开始日期从早到晚排序结果。

[Assistant]
MATCH (am:AircraftModel)-[:IS_MODEL]-(ab:AircraftBuild)-[:ASSEMBLED_ON]->(al:AssemblyLine)
WHERE am.model_id = 'specific_model_id' AND ab.current_status = 'In Progress' AND ab.build_start_date >= datetime('2023-01-01')
RETURN ab.build_id, ab.build_start_date, ab.estimated_completion_date, al.line_name, al.location_building, al.location_area
ORDER BY ab.build_start_date ASC

[User] I need to get a list of employees assigned to a specific assembly line, including their job title and hire date.

[Assistant]
MATCH (e:Employee)-[:ASSIGNED_TO]->(al:AssemblyLine {line_id: 'specific_line_id'})
RETURN e.employee_id, e.first_name, e.last_name, e.job_title, e.hire_date

[User] Can you filter this to include only employees with a specific job title, for example, 'Technician'?

[Assistant]
MATCH (e:Employee)-[:ASSIGNED_TO]->(al:AssemblyLine {line_id: 'specific_line_id'})
WHERE e.job_title = 'Technician'
RETURN e.employee_id, e.first_name, e.last_name, e.job_title, e.hire_date

[User] What if I also want to see their skill certifications?

[Assistant]
MATCH (e:Employee)-[:ASSIGNED_TO]->(al:AssemblyLine {line_id: 'specific_line_id'})
WHERE e.job_title = 'Technician'
RETURN e.employee_id, e.first_name, e.last_name, e.job_title, e.hire_date, e.skill_certifications

[User] Can you help me retrieve the details of all aircraft builds for a specific aircraft model, including the build start date, estimated completion date, and the assembly line they are built on?

[Assistant]
MATCH (ab:AircraftBuild)-[:IS_MODEL]->(am:AircraftModel {model_id: 'specific_model_id'}), (ab)-[:ASSEMBLED_ON]->(al:AssemblyLine)
RETURN ab.build_id, ab.build_start_date, ab.estimated_completion_date, al.line_name

[User] Can you modify the query to include only builds that have not yet been completed?

[Assistant]
MATCH (ab:AircraftBuild)-[:IS_MODEL]->(am:AircraftModel {model_id: 'specific_model_id'}), (ab)-[:ASSEMBLED_ON]->(al:AssemblyLine)
WHERE ab.actual_completion_date IS NULL
RETURN ab.build_id, ab.build_start_date, ab.estimated_completion_date, al.line_name

[User] What if I want to further filter builds with a start date after January 1, 2023?

[Assistant]
MATCH (ab:AircraftBuild)-[:IS_MODEL]->(am:AircraftModel {model_id: 'specific_model_id'}), (ab)-[:ASSEMBLED_ON]->(al:AssemblyLine)
WHERE ab.actual_completion_date IS NULL AND ab.build_start_date > datetime('2023-01-01')
RETURN ab.build_id, ab.build_start_date, ab.estimated_completion_date, al.line_name

[User] Can you help me fetch the inventory details for components associated with a specific aircraft build, including the batch number, quantity, and warehouse location?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

[User] Can you modify this to show only inventory batches received after a specific date, say June 1, 2023?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE ib.received_date > datetime('2023-06-01')
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

[User] What if I also want to exclude batches with quantities less than 10?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE ib.received_date > datetime('2023-06-01') AND ib.quantity >= 10
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

[User] I need to check the inventory status of components, including their batch details and warehouse location.

[Assistant]
MATCH (i:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
RETURN c.component_id, c.component_name, i.inventory_record_id, i.quantity, i.location_warehouse, i.location_bin, i.received_date, i.batch_number

[User] Can you filter this to show only batches with a quantity less than 50?

[Assistant]
MATCH (i:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE i.quantity < 50
RETURN c.component_id, c.component_name, i.inventory_record_id, i.quantity, i.location_warehouse, i.location_bin, i.received_date, i.batch_number

[User] What if I want to exclude batches with an expiry date before 2024?

[Assistant]
MATCH (i:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE i.quantity < 50 AND i.expiry_date >= date('2024-01-01')
RETURN c.component_id, c.component_name, i.inventory_record_id, i.quantity, i.location_warehouse, i.location_bin, i.received_date, i.batch_number

[User] Can you order the results by received date in descending order?

[Assistant]
MATCH (i:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE i.quantity < 50 AND i.expiry_date >= date('2024-01-01')
RETURN c.component_id, c.component_name, i.inventory_record_id, i.quantity, i.location_warehouse, i.location_bin, i.received_date, i.batch_number
ORDER BY i.received_date 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 social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )

[User] How many users have non-empty full_name and bio fields? Return only the count.

[Assistant]
SELECT COUNT(*)
FROM social_media.users
WHERE full_name IS NOT NULL
  AND full_name <> ''
  AND bio IS NOT NULL
  AND bio <> '';

[User] Count how many users have not specified a value for their bio.

[Assistant] SELECT COUNT(*) FROM social_media.users WHERE bio IS NULL OR bio = '';

[User] List usernames and the length of their 'bio' field for users whose 'is_verified' status is true.

[Assistant] SELECT username, LENGTH(bio) AS bio_length FROM social_media.users WHERE is_verified IS TRUE;

[User] Show me the usernames and full names of all users who have updated their profile after April 1, 2024, and have specified a location.

[Assistant] SELECT username, full_name FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '';

[User] Actually, I also want to see their email addresses.

[Assistant] SELECT username, full_name, email FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '';

[User] Now, only show users whose profiles are verified.

[Assistant] SELECT username, full_name, email FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '' AND is_verified = true;

[User] Sort the results by username in ascending order.

[Assistant] SELECT username, full_name, email FROM social_media.users WHERE updated_at > '2024-04-01' AND location IS NOT NULL AND location <> '' AND is_verified = true ORDER BY username ASC;

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

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

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

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

[User] Show the username, full name, and location for all users who registered before January 1, 2024 and are not verified.

[Assistant] SELECT username, full_name, location FROM social_media.users WHERE created_at < '2024-01-01' AND is_verified = false;

[User] Only include those who have a non-empty location.

[Assistant] SELECT username, full_name, location FROM social_media.users WHERE created_at < '2024-01-01' AND is_verified = false AND location IS NOT NULL AND location <> '';

[User] List the username and email for users who joined after March 1, 2024, and are not verified.

[Assistant] SELECT username, email FROM social_media.users WHERE created_at >= '2024-03-01' AND is_verified = false;

[User] Now, only show users whose location is specified.

[Assistant] SELECT username, email FROM social_media.users WHERE created_at >= '2024-03-01' AND is_verified = false AND location IS NOT NULL;

[User] Also, include their full name.

[Assistant] SELECT username, email, full_name FROM social_media.users WHERE created_at >= '2024-03-01' AND is_verified = false AND location IS NOT NULL;

[User] Order the results by username alphabetically.

[Assistant] SELECT username, email, full_name FROM social_media.users WHERE created_at >= '2024-03-01' AND is_verified = false AND location IS NOT NULL ORDER BY username ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] Retrieve conversation IDs and user IDs of participants who joined after '2024-01-01', including their last_read_at timestamps.

[Assistant] SELECT conversation_id, user_id, last_read_at FROM social_media.conversation_participants WHERE joined_at > '2024-01-01';

[User] Get the total number of participants per conversation along with the number of participants who have private profiles.

[Assistant] SELECT cp.conversation_id, COUNT(cp.user_id) AS total_participants, SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) AS private_profile_count FROM social_media.conversation_participants cp LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id GROUP BY cp.conversation_id;

[User] Exclude conversations with fewer than 3 private profile participants.

[Assistant] SELECT cp.conversation_id, COUNT(cp.user_id) AS total_participants, SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) AS private_profile_count FROM social_media.conversation_participants cp LEFT JOIN social_media.user_settings us ON cp.user_id = us.user_id GROUP BY cp.conversation_id HAVING SUM(CASE WHEN us.private_profile THEN 1 ELSE 0 END) >= 3;

[User] Can you list each user's theme setting along with the number of likes they have given to posts?

[Assistant] SELECT us.user_id, us.theme, COUNT(l.like_id) AS like_count FROM social_media.user_settings us LEFT JOIN social_media.likes l ON us.user_id = l.user_id AND l.comment_id IS NULL GROUP BY us.user_id, us.theme;

[User] Actually, I only want the count of likes where push_notifications_enabled is true.

[Assistant] SELECT us.user_id, us.theme, COUNT(l.like_id) AS like_count FROM social_media.user_settings us LEFT JOIN social_media.likes l ON us.user_id = l.user_id AND l.comment_id IS NULL WHERE us.push_notifications_enabled = TRUE GROUP BY us.user_id, us.theme;

[User] Also, filter to users who have made at least 10 such likes.

[Assistant] SELECT us.user_id, us.theme, COUNT(l.like_id) AS like_count FROM social_media.user_settings us LEFT JOIN social_media.likes l ON us.user_id = l.user_id AND l.comment_id IS NULL WHERE us.push_notifications_enabled = TRUE GROUP BY us.user_id, us.theme HAVING COUNT(l.like_id) >= 10;

[User] And sort the results by like_count descending, limiting to the top 5.

[Assistant] SELECT us.user_id, us.theme, COUNT(l.like_id) AS like_count FROM social_media.user_settings us LEFT JOIN social_media.likes l ON us.user_id = l.user_id AND l.comment_id IS NULL WHERE us.push_notifications_enabled = TRUE GROUP BY us.user_id, us.theme HAVING COUNT(l.like_id) >= 10 ORDER BY like_count DESC LIMIT 5;

[User] List the usernames and the IDs of conversations they have joined.

[Assistant] SELECT T1.username, T2.conversation_id FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id;

[User] Can you filter this to only show users who joined after '2024-06-15'?

[Assistant] SELECT T1.username, T2.conversation_id FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id WHERE T2.joined_at > '2024-06-15';

[User] List the usernames and email addresses of users who have participated in any conversation.

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

[User] Can you also include the time they joined their first conversation?

[Assistant] SELECT T1.username, T1.email, MIN(T2.joined_at) AS first_joined_at FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id GROUP BY T1.user_id, T1.username, T1.email;

[User] Only show users whose email ends with '.com' and joined after '2024-01-15'.

[Assistant] SELECT T1.username, T1.email, MIN(T2.joined_at) AS first_joined_at FROM social_media.users AS T1 JOIN social_media.conversation_participants AS T2 ON T1.user_id = T2.user_id WHERE T1.email LIKE '%.com' GROUP BY T1.user_id, T1.username, T1.email HAVING MIN(T2.joined_at) > '2024-01-15';

[User] How many posts have been updated after they were created?

[Assistant]
SELECT COUNT(*) AS updated_post_count
FROM social_media.posts
WHERE updated_at IS NOT NULL AND updated_at > created_at;

[User] For each user, show their user ID and the count of unread notifications they have received.

[Assistant]
SELECT recipient_user_id, COUNT(*) AS unread_notification_count
FROM social_media.notifications
WHERE read_at IS NULL
GROUP BY recipient_user_id;

[User] Can you also show the notification types for those unread notifications?

[Assistant]
SELECT recipient_user_id, notification_type, COUNT(*) AS unread_notification_count
FROM social_media.notifications
WHERE read_at IS NULL
GROUP BY recipient_user_id, notification_type;

[User] Actually, only include users who have joined at least one conversation, and also show one conversation_id they joined.

[Assistant]
SELECT n.recipient_user_id, n.notification_type, COUNT(*) AS unread_notification_count, cp.conversation_id
FROM social_media.notifications n
JOIN social_media.conversation_participants cp ON cp.user_id = n.recipient_user_id
WHERE n.read_at IS NULL
GROUP BY n.recipient_user_id, n.notification_type, cp.conversation_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 financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )

[User] What is the average interest rate for loans of type 'Mortgage'?

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage'

[User] Refine this to only include loans with status 'Active'.

[Assistant] SELECT AVG(interest_rate) FROM financial_services.loans WHERE loan_type = 'Mortgage' AND status = 'Active'

[User] Show me the total principal amount for each loan type, along with the count of loans and average monthly payment, but only for loans originated in the last 5 years.

[Assistant] SELECT loan_type, SUM(principal_amount) AS total_principal, COUNT(loan_id) AS loan_count, AVG(monthly_payment) AS avg_monthly_payment FROM financial_services.loans WHERE origination_date >= CURRENT_DATE - INTERVAL '5 years' GROUP BY loan_type;

[User] Show me all loans with a term longer than 36 months, including their loan_id, account_id, and principal_amount.

[Assistant] SELECT loan_id, account_id, principal_amount FROM financial_services.loans WHERE term_months > 36;

[User] Can you also include their origination_date and current_principal_balance?

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36;

[User] Filter to only show loans that are not yet matured (maturity_date > CURRENT_DATE).

[Assistant] SELECT loan_id, account_id, principal_amount, current_principal_balance, origination_date FROM financial_services.loans WHERE term_months > 36 AND maturity_date > CURRENT_DATE;

[User] For each loan type, show the total outstanding principal balance and the number of active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type;

[User] Sort the result by total_outstanding_balance in ascending order.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type ORDER BY total_outstanding_balance ASC;

[User] Only include loan types where there are more than 10 active loans.

[Assistant] SELECT loan_type, SUM(current_principal_balance) AS total_outstanding_balance, COUNT(*) AS active_loan_count FROM financial_services.loans WHERE status = 'ACTIVE' GROUP BY loan_type HAVING COUNT(*) > 10 ORDER BY total_outstanding_balance ASC;

[User] Show all loans with a maturity date in the next 60 days, along with their account_id, principal_amount, interest_rate, and maturity_date.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days';

[User] Only include loans where the status is not 'CLOSED' or 'PAID_OFF'.

[Assistant] SELECT loan_id, account_id, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] Also, display the loan_type in the result.

[Assistant] SELECT loan_id, account_id, loan_type, principal_amount, interest_rate, maturity_date FROM financial_services.loans WHERE maturity_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '60 days' AND status NOT IN ('CLOSED', 'PAID_OFF');

[User] What is the average interest rate for auto loans (loan_type = 'Auto') with a principal amount between $20,000 and $50,000?

[Assistant] SELECT AVG(interest_rate) AS avg_interest_rate FROM financial_services.loans WHERE loan_type = 'Auto' AND principal_amount BETWEEN 20000 AND 50000;

[User] List all auto loans (loan_id, principal_amount, interest_rate) where the current principal balance is less than 40% of the original principal amount, along with the account_id and the difference between principal_amount and current_principal_balance.

[Assistant] SELECT loan_id, principal_amount, interest_rate, account_id, (principal_amount - current_principal_balance) AS amount_paid FROM financial_services.loans WHERE loan_type = 'Auto' AND current_principal_balance < (0.4 * principal_amount);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)

[User] For each claim, count the number of beneficiaries associated with its policy. Show claim_id and beneficiary_count, only for claims with more than 2 beneficiaries.

[Assistant]
SELECT c.claim_id, COUNT(pb.beneficiary_id) AS beneficiary_count
FROM insurance.claims c
JOIN insurance.policy_beneficiaries pb ON c.policy_id = pb.policy_id
GROUP BY c.claim_id
HAVING COUNT(pb.beneficiary_id) > 2;

[User] Now restrict the result to claims reported in 2023.

[Assistant]
SELECT c.claim_id, COUNT(pb.beneficiary_id) AS beneficiary_count
FROM insurance.claims c
JOIN insurance.policy_beneficiaries pb ON c.policy_id = pb.policy_id
WHERE c.reported_date >= '2023-01-01' AND c.reported_date < '2024-01-01'
GROUP BY c.claim_id
HAVING COUNT(pb.beneficiary_id) > 2;

[User] List all premium payments with the amount_paid exactly 1000, showing the payment_id and payment_date.

[Assistant]
SELECT payment_id, payment_date
FROM insurance.premium_payments
WHERE amount_paid = 1000;

[User] What is the average estimated_loss for each claim status?

[Assistant]
SELECT status, AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
GROUP BY status;

[User] Show the number of claims filed for each distinct status, ordered by the count in descending order.

[Assistant]
SELECT status, COUNT(*) AS claim_count
FROM insurance.claims
GROUP BY status
ORDER BY claim_count DESC;

[User] Show all premium payments along with the incident date and estimated loss of any associated claims for the same policy. List payment_id, amount_paid, payment_date, incident_date, and estimated_loss.

[Assistant] SELECT T1.payment_id, T1.amount_paid, T1.payment_date, T2.incident_date, T2.estimated_loss FROM insurance.premium_payments AS T1 LEFT JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id;

[User] Refine the results to only show payments for policies that have an associated claim with an estimated loss exceeding 10000.

[Assistant] SELECT T1.payment_id, T1.amount_paid, T1.payment_date, T2.incident_date, T2.estimated_loss FROM insurance.premium_payments AS T1 JOIN insurance.claims AS T2 ON T1.policy_id = T2.policy_id WHERE T2.estimated_loss > 10000;

[User] How many agents are currently active in each license state?

[Assistant]
SELECT license_state, COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state;

[User] List each claim_handler_id along with the number of claims they've handled and the total settlement_amount they've paid out.

[Assistant]
SELECT claim_handler_id,
       COUNT(*) AS total_claims,
       SUM(settlement_amount) AS total_settlement
FROM insurance.claims
GROUP BY claim_handler_id;

[User] In addition, include the claim_id of the single claim with the highest settlement_amount for each handler.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

[User] Only include handlers who have managed at least 3 claims and have a non-null claim_handler_id.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

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

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  )
ORDER BY ag.total_settlement DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )

[User] List the first name, last name, and email of all customers who live in New York or California.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE state IN ('NY', 'CA');

[User] Find all customers whose email address ends with '@gmail.com'. Please show the customer_id, first name, and email.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com';

[User] Also, restrict this to only customers who are currently 'inactive'.

[Assistant] SELECT customer_id, first_name, email FROM insurance.customers WHERE email LIKE '%@gmail.com' AND status = 'inactive';

[User] How many customers have a non-null phone number in your system?

[Assistant] SELECT COUNT(*) FROM insurance.customers WHERE phone_number IS NOT NULL;

[User] Which cities have more than 10 active customers in the state of Texas? Provide the city name and the customer count.

[Assistant]
SELECT city, COUNT(*) AS customer_count
FROM insurance.customers
WHERE state = 'TX' AND status = 'Active'
GROUP BY city
HAVING COUNT(*) > 10;

[User] How many customers were created in 2023?

[Assistant]
SELECT COUNT(*)
FROM insurance.customers
WHERE EXTRACT(YEAR FROM created_at) = 2023;

[User] Show me the full names and email addresses of all customers who registered after January 1st, 2024.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE created_at > '2024-01-01';

[User] I also want to see their city and state in the result.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01';

[User] Sort the output by the created_at timestamp, newest first.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Limit the result to the top 10 most recently registered customers.

[Assistant] SELECT first_name, last_name, email, city, state FROM insurance.customers WHERE created_at > '2024-01-01' ORDER BY created_at DESC LIMIT 10;

[User] Show me a list of all customers from California along with their full names and phone numbers.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number FROM insurance.customers WHERE state = 'CA';

[User] Can you also include their email addresses in the results?

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA';

[User] Actually, show me only those customers whose status is 'active'.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA' AND status = 'active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] List all rooms that are currently marked as 'OutOfOrder' or 'Maintenance'. Show their room number and current status.

[Assistant] SELECT room_number, status FROM hospitality_technology.rooms WHERE status IN ('OutOfOrder', 'Maintenance');

[User] Add the property ID and floor number for these rooms, and sort the results by property ID then floor.

[Assistant] SELECT property_id, floor, room_number, status FROM hospitality_technology.rooms WHERE status IN ('OutOfOrder', 'Maintenance') ORDER BY property_id, floor;

[User] List all service orders, including the service name and quantity, along with the full name of the staff member who placed the order.

[Assistant] SELECT so.order_id, s.service_name, so.quantity, st.first_name, st.last_name FROM hospitality_technology.service_orders AS so JOIN hospitality_technology.services AS s ON so.service_id = s.service_id JOIN hospitality_technology.staff AS st ON so.staff_id_ordered = st.staff_id;

[User] Filter this list to only include orders placed by staff members with position 'Concierge'.

[Assistant] SELECT so.order_id, s.service_name, so.quantity, st.first_name, st.last_name FROM hospitality_technology.service_orders AS so JOIN hospitality_technology.services AS s ON so.service_id = s.service_id JOIN hospitality_technology.staff AS st ON so.staff_id_ordered = st.staff_id WHERE st.position = 'Concierge';

[User] Show me the list of all room numbers and their corresponding guest full names for current reservations (status is 'Occupied' or 'CheckedIn').

[Assistant]
SELECT r.room_number, g.first_name || ' ' || g.last_name AS guest_full_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
WHERE res.status IN ('Occupied', 'CheckedIn');

[User] Add the property name to the result and sort the list by property name, then by room number.

[Assistant]
SELECT p.property_name, r.room_number, g.first_name || ' ' || g.last_name AS guest_full_name
FROM hospitality_technology.reservations res
JOIN hospitality_technology.rooms r ON res.room_id = r.room_id
JOIN hospitality_technology.guests g ON res.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE res.status IN ('Occupied', 'CheckedIn')
ORDER BY p.property_name, r.room_number;

[User] For properties located in the city 'Los Angeles', list all rooms that are on floor 3. Include the property name and room number.

[Assistant] SELECT p.property_name, r.room_number FROM hospitality_technology.properties p JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.city = 'Los Angeles' AND r.floor = 3;

[User] Further filter this list to only include rooms that are designated as smoking rooms.

[Assistant] SELECT p.property_name, r.room_number FROM hospitality_technology.properties p JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.city = 'Los Angeles' AND r.floor = 3 AND r.is_smoking = true;

[User] Sort the results by property name and then by room number, and limit to the first 20 entries.

[Assistant] SELECT p.property_name, r.room_number FROM hospitality_technology.properties p JOIN hospitality_technology.rooms r ON p.property_id = r.property_id WHERE p.city = 'Los Angeles' AND r.floor = 3 AND r.is_smoking = true ORDER BY p.property_name, r.room_number LIMIT 20;

[User] For each reservation in the last three months, show the reservation ID, check-in date, number of adults, and the corresponding room type name.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.created_at >= NOW() - INTERVAL '3 months';

[User] Also include the name of the property for each reservation.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '3 months';

[User] Sort the results by number of adults descending, and then by check-in date ascending.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '3 months'
ORDER BY r.num_adults DESC, r.check_in_date ASC;

[User] List the names and email addresses of guests who have made a reservation in the last 60 days.

[Assistant]
SELECT DISTINCT g.first_name, g.last_name, g.email
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
WHERE r.created_at >= NOW() - INTERVAL '60 days';

[User] Only show guests who have stayed at a property with a star rating of at least 4.

[Assistant]
SELECT DISTINCT g.first_name, g.last_name, g.email
FROM hospitality_technology.guests g
JOIN hospitality_technology.reservations r ON g.guest_id = r.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '60 days' AND p.star_rating >= 4;

[User] For each property, show the property_name, the total number of available services, and the average price of those services.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS total_available_services,
       AVG(s.price) AS avg_service_price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
WHERE s.is_available = TRUE
GROUP BY p.property_name;

[User] Now exclude properties that have zero available services and only include those with an average price greater than 50.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS total_available_services,
       AVG(s.price) AS avg_service_price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
WHERE s.is_available = TRUE
GROUP BY p.property_name
HAVING COUNT(s.service_id) > 0
   AND AVG(s.price) > 50;

[User] Also, restrict the services to only those in the 'Wellness' and 'Spa' departments.

[Assistant]
SELECT p.property_name,
       COUNT(s.service_id) AS total_available_services,
       AVG(s.price) AS avg_service_price
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
WHERE s.is_available = TRUE
  AND s.department IN ('Wellness', 'Spa')
GROUP BY p.property_name
HAVING COUNT(s.service_id) > 0
   AND AVG(s.price) > 50;