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_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )

[User] List tokens on 'Arbitrum' with liquidity over 5000000.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000;

[User] Filter those tokens to only include ones with a positive price change in the last 24 hours.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0;

[User] Order the results by 24-hour trading volume descending and show the top 5 tokens.

[Assistant] SELECT * FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 5;

[User] Also show their market cap and trend rank.

[Assistant] SELECT token_symbol, token_name, chain, price, liquidity, price_change_percentage_24h, volume_24h, market_cap, trend_rank FROM token_dexpool_info WHERE chain = 'Arbitrum' AND liquidity > 5000000 AND price_change_percentage_24h > 0 ORDER BY volume_24h DESC LIMIT 5;

[User] Which three tokens on the Arbitrum chain have the lowest 6-hour price change percentage?

[Assistant] SELECT token_symbol, price_change_percentage_6h FROM token_dexpool_info WHERE chain = 'Arbitrum' ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] Please also show their current price and trading volume.

[Assistant] SELECT token_symbol, price_change_percentage_6h, price, volume_24h FROM token_dexpool_info WHERE chain = 'Arbitrum' ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] Now include their liquidity and market cap in the result.

[Assistant] SELECT token_symbol, price_change_percentage_6h, price, volume_24h, liquidity, market_cap FROM token_dexpool_info WHERE chain = 'Arbitrum' ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] Restrict to only those tokens where market cap is above 10 million.

[Assistant] SELECT token_symbol, price_change_percentage_6h, price, volume_24h, liquidity, market_cap FROM token_dexpool_info WHERE chain = 'Arbitrum' AND market_cap > 10000000 ORDER BY price_change_percentage_6h ASC LIMIT 3;

[User] List tokens with trend rank 5 or better and a price below $1. Show symbol, price, and trend rank.

[Assistant] SELECT token_symbol, price, trend_rank FROM token_dexpool_info WHERE trend_rank IS NOT NULL AND trend_rank <= 5 AND price < 1;

[User] Find tokens on the 'Ethereum' chain with a 6-hour price increase above 5%, and include their net_flow and roi from smart money performance.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5;

[User] Only include those with a 24h trading volume greater than 1000000.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, d.volume_24h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5
  AND d.volume_24h > 1000000;

[User] Sort the results by net_flow descending and limit to the top 3 tokens.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, d.volume_24h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5
  AND d.volume_24h > 1000000
ORDER BY p.net_flow DESC
LIMIT 3;

[User] Also include the number of makers in the last 24h for each of these tokens.

[Assistant]
SELECT d.token_symbol, d.chain, d.price_change_percentage_6h, d.volume_24h, d.makers_24h, p.net_flow, p.roi
FROM token_dexpool_info d
JOIN smart_money_token_performance p ON d.token_symbol = p.token_symbol AND d.chain = p.chain
WHERE d.chain = 'Ethereum' AND d.price_change_percentage_6h > 5
  AND d.volume_24h > 1000000
ORDER BY p.net_flow DESC
LIMIT 3;

[User] For each chain, find the token with the highest 24h trading volume and the token with the lowest 24h trading volume. Show chain, high_volume_token, high_volume_24h, low_volume_token, and low_volume_24h.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       n.low_volume_token,
       n.low_volume_24h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain;

[User] Exclude chains where the highest volume is below 100,000.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       n.low_volume_token,
       n.low_volume_24h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain
WHERE m.high_volume_24h >= 100000;

[User] Also include the 6h price change percentage for those high and low volume tokens in the output.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h,
         price_change_percentage_6h AS high_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h,
         price_change_percentage_6h AS low_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       m.high_change_6h,
       n.low_volume_token,
       n.low_volume_24h,
       n.low_change_6h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain;

[User] Finally, order the result by chain in ascending order.

[Assistant]
WITH max_vol AS (
  SELECT chain,
         token_symbol AS high_volume_token,
         volume_24h AS high_volume_24h,
         price_change_percentage_6h AS high_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MAX(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
), min_vol AS (
  SELECT chain,
         token_symbol AS low_volume_token,
         volume_24h AS low_volume_24h,
         price_change_percentage_6h AS low_change_6h
  FROM token_dexpool_info
  WHERE (chain, volume_24h) IN (
    SELECT chain, MIN(volume_24h)
    FROM token_dexpool_info
    GROUP BY chain
  )
)
SELECT m.chain,
       m.high_volume_token,
       m.high_volume_24h,
       m.high_change_6h,
       n.low_volume_token,
       n.low_volume_24h,
       n.low_change_6h
FROM max_vol m
JOIN min_vol n ON m.chain = n.chain
ORDER BY m.chain ASC;

[User] Find tokens that have a positive price change percentage over the last 1 hour, 6 hours, and 24 hours. Display their symbol and chain.

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0;

[User] Only show results for chains where the average trend rank is better than 5 (lower value indicates higher popularity).

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5);

[User] Order the results by the 24-hour price change percentage in descending order.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC;

[User] Limit the result to the top 20 tokens.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC LIMIT 20;

[User] What is the total market cap for all tokens listed on the 'Polygon' chain?

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon';

[User] Only sum the market cap for tokens on 'Polygon' that have a 24-hour volume greater than 500000.

[Assistant] SELECT SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Also show the number of unique tokens that meet these criteria.

[Assistant] SELECT COUNT(DISTINCT token_symbol), SUM(market_cap) FROM token_dexpool_info WHERE chain = 'Polygon' AND volume_24h > 500000;

[User] Can you show the total market cap and token count for *each* chain that meets these volume criteria, ordered by total market cap descending?

[Assistant] SELECT chain, COUNT(DISTINCT token_symbol) AS token_count, SUM(market_cap) AS total_market_cap FROM token_dexpool_info WHERE volume_24h > 500000 GROUP BY chain ORDER BY total_market_cap DESC;

[User] Compute the average realized_ratio and average pnl for smart money token performance grouped by chain.

[Assistant]
SELECT chain, AVG(realized_ratio) AS avg_realized_ratio, AVG(pnl) AS avg_pnl
FROM smart_money_token_performance
GROUP BY chain;

[User] Show only the chains where the average pnl is greater than 10000.

[Assistant]
SELECT chain, AVG(realized_ratio) AS avg_realized_ratio, AVG(pnl) AS avg_pnl
FROM smart_money_token_performance
GROUP BY chain
HAVING AVG(pnl) > 10000;

[User] Which two tokens on each chain have the greatest difference in their 24h price change percentage? Show token_symbol A, token_symbol B, chain, and the absolute difference.

[Assistant]
SELECT DISTINCT ON (t1.chain)
  t1.token_symbol AS symbol_a,
  t2.token_symbol AS symbol_b,
  t1.chain,
  ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) AS diff_24h
FROM token_dexpool_info t1
JOIN token_dexpool_info t2
  ON t1.chain = t2.chain
  AND t1.token_symbol < t2.token_symbol
ORDER BY t1.chain, diff_24h DESC;

[User] Actually, I want only the chains where this top difference is at least 15% and show the top 2 pairs per chain.

[Assistant]
SELECT symbol_a, symbol_b, chain, diff_24h
FROM (
  SELECT
    t1.token_symbol AS symbol_a,
    t2.token_symbol AS symbol_b,
    t1.chain,
    ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) AS diff_24h,
    ROW_NUMBER() OVER(
      PARTITION BY t1.chain
      ORDER BY ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) DESC
    ) AS rn
  FROM token_dexpool_info t1
  JOIN token_dexpool_info t2
    ON t1.chain = t2.chain
    AND t1.token_symbol < t2.token_symbol
  WHERE ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) >= 15
) sub
WHERE rn <= 2
ORDER BY chain, diff_24h DESC;

[User] Also sort the overall result by diff_24h descending and limit to the top 5 records.

[Assistant]
SELECT *
FROM (
  SELECT symbol_a, symbol_b, chain, diff_24h
  FROM (
    SELECT
      t1.token_symbol AS symbol_a,
      t2.token_symbol AS symbol_b,
      t1.chain,
      ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) AS diff_24h,
      ROW_NUMBER() OVER(
        PARTITION BY t1.chain
        ORDER BY ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) DESC
      ) AS rn
    FROM token_dexpool_info t1
    JOIN token_dexpool_info t2
      ON t1.chain = t2.chain
      AND t1.token_symbol < t2.token_symbol
    WHERE ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) >= 15
  ) sub1
  WHERE rn <= 2
) sub2
ORDER BY diff_24h DESC
LIMIT 5;

[User] Could you include the current price of both tokens in the output as well?

[Assistant]
SELECT symbol_a, symbol_b, chain, price_a, price_b, diff_24h
FROM (
  SELECT
    t1.token_symbol AS symbol_a,
    t2.token_symbol AS symbol_b,
    t1.chain,
    t1.price AS price_a,
    t2.price AS price_b,
    ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) AS diff_24h,
    ROW_NUMBER() OVER(
      PARTITION BY t1.chain
      ORDER BY ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) DESC
    ) AS rn
  FROM token_dexpool_info t1
  JOIN token_dexpool_info t2
    ON t1.chain = t2.chain
    AND t1.token_symbol < t2.token_symbol
  WHERE ABS(t1.price_change_percentage_24h - t2.price_change_percentage_24h) >= 15
) sub
WHERE rn <= 2
ORDER BY diff_24h DESC
LIMIT 5;

[User] For each chain, find the token with the highest price and the token with the lowest price. List chain, high_price_token, max_price, low_price_token, and min_price.

[Assistant]
WITH max_prices AS (
  SELECT chain,
         token_symbol AS high_price_token,
         price AS max_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MAX(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
),
min_prices AS (
  SELECT chain,
         token_symbol AS low_price_token,
         price AS min_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MIN(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
)
SELECT m.chain,
       m.high_price_token,
       m.max_price,
       n.low_price_token,
       n.min_price
FROM max_prices m
JOIN min_prices n
  ON m.chain = n.chain;

[User] Exclude any chain where min_price is below 0.01 and only show the top 3 chains by max_price descending.

[Assistant]
WITH max_prices AS (
  SELECT chain,
         token_symbol AS high_price_token,
         price AS max_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MAX(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
),
min_prices AS (
  SELECT chain,
         token_symbol AS low_price_token,
         price AS min_price
  FROM token_dexpool_info t1
  WHERE price = (
    SELECT MIN(price)
    FROM token_dexpool_info t2
    WHERE t2.chain = t1.chain
  )
)
SELECT m.chain,
       m.high_price_token,
       m.max_price,
       n.low_price_token,
       n.min_price
FROM max_prices m
JOIN min_prices n
  ON m.chain = n.chain
WHERE n.min_price >= 0.01
ORDER BY m.max_price DESC
LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )

[User] I want to see, for each game, the total number of sessions and the average cost of its in-game items.

[Assistant] SELECT gs.game_id, COUNT(*) AS session_count, AVG(igi.cost_amount) AS avg_item_cost FROM gaming_technology.game_sessions gs JOIN gaming_technology.in_game_items igi ON gs.game_id = igi.game_id GROUP BY gs.game_id;

[User] Actually, only include games that have at least 100 sessions.

[Assistant] SELECT gs.game_id, COUNT(*) AS session_count, AVG(igi.cost_amount) AS avg_item_cost FROM gaming_technology.game_sessions gs JOIN gaming_technology.in_game_items igi ON gs.game_id = igi.game_id GROUP BY gs.game_id HAVING COUNT(*) >= 100;

[User] Also, include the number of distinct items available for each game.

[Assistant] SELECT gs.game_id, COUNT(*) AS session_count, AVG(igi.cost_amount) AS avg_item_cost, COUNT(DISTINCT igi.item_id) AS distinct_item_count FROM gaming_technology.game_sessions gs JOIN gaming_technology.in_game_items igi ON gs.game_id = igi.game_id GROUP BY gs.game_id HAVING COUNT(*) >= 100;

[User] Show all in-game items (name, rarity) that belong to games where the average session score across all sessions for that game is greater than 300.

[Assistant] SELECT ii.item_name, ii.rarity FROM gaming_technology.in_game_items AS ii WHERE ii.game_id IN (SELECT game_id FROM gaming_technology.game_sessions GROUP BY game_id HAVING AVG(score) > 300);

[User] Additionally, include the total number of sessions for each of these items' games.

[Assistant] SELECT ii.item_name, ii.rarity, gs.total_sessions FROM gaming_technology.in_game_items AS ii JOIN (SELECT game_id, COUNT(*) AS total_sessions, AVG(score) AS avg_score FROM gaming_technology.game_sessions GROUP BY game_id) AS gs ON ii.game_id = gs.game_id WHERE gs.avg_score > 300;

[User] List the names of servers and their regions, and the names of achievements available in the games hosted on those servers.

[Assistant] SELECT s.server_name, s.region, a.name AS achievement_name FROM gaming_technology.servers AS s JOIN gaming_technology.achievements AS a ON s.game_id = a.game_id;

[User] Could you list the top 5 highest average session scores for each game, showing the game title, developer name, and the average score?

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Actually, I'd like to focus only on games in the 'Action' and 'RPG' genres.

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE g.genre IN ('Action','RPG')
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Also, include the total number of sessions for each of those games.

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE g.genre IN ('Action','RPG')
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Finally, restrict the results to games released after January 1, 2020.

[Assistant]
SELECT g.title AS game_title,
       d.name AS developer_name,
       AVG(gs.score) AS average_score,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.game_sessions gs
JOIN gaming_technology.games g ON gs.game_id = g.game_id
JOIN gaming_technology.developers d ON g.developer_id = d.developer_id
WHERE g.genre IN ('Action','RPG')
  AND g.release_date > '2020-01-01'
GROUP BY g.title, d.name
ORDER BY average_score DESC
LIMIT 5;

[User] Which achievements have the highest unlock counts? List the top 5 achievement names along with the number of distinct players who unlocked each.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Only exclude hidden achievements from the ranking.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
ORDER BY player_count DESC
LIMIT 5;

[User] Now include only achievements unlocked by at least 50 players and order by player_count descending.

[Assistant]
SELECT a.name,
       COUNT(DISTINCT pa.player_id) AS player_count
FROM gaming_technology.achievements a
JOIN gaming_technology.player_achievements pa ON a.achievement_id = pa.achievement_id
WHERE a.hidden = FALSE
GROUP BY a.name
HAVING COUNT(DISTINCT pa.player_id) >= 50
ORDER BY player_count DESC;

[User] For each in-game item type, display the item type, total quantity held by players, and the average cost amount of those items.

[Assistant]
SELECT i.item_type,
       COALESCE(SUM(pi.quantity), 0) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
GROUP BY i.item_type;

[User] Now restrict to items with rarity 'Epic'.

[Assistant]
SELECT i.item_type,
       COALESCE(SUM(pi.quantity), 0) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type;

[User] Also exclude any groups where the average cost_amount is less than 100.

[Assistant]
SELECT i.item_type,
       SUM(pi.quantity) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type
HAVING AVG(i.cost_amount) >= 100;

[User] Please order the results by total_quantity descending.

[Assistant]
SELECT i.item_type,
       SUM(pi.quantity) AS total_quantity,
       AVG(i.cost_amount) AS avg_cost
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.rarity = 'Epic'
GROUP BY i.item_type
HAVING AVG(i.cost_amount) >= 100
ORDER BY total_quantity DESC;

[User] Could you list all games, show their title and genre, and also include the total number of achievements for each game?

[Assistant] SELECT g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY g.game_id, g.title, g.genre;

[User] Okay, now can you also include the developer's name for each game?

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre;

[User] Can you filter the results to only show games from the 'Action' genre or games developed in 'Japan'?

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id WHERE g.genre = 'Action' OR d.country = 'Japan' GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre;

[User] Finally, order the results by the total number of achievements in descending order, and only show games with at least one achievement.

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre HAVING COUNT(a.achievement_id) > 0 ORDER BY total_achievements DESC;

[User] For each game, show the game title, the total duration of all sessions in seconds, and the average score.

[Assistant] SELECT g.title, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Could you also show the total number of sessions for each game?

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Filter the results to only include games with more than 100 sessions.

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title HAVING COUNT(gs.session_id) > 100;

[User] List the names and types of all in-game items that have a rarity of 'Epic'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic';

[User] Further restrict the list to only include items of item_type 'Weapon'.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon';

[User] Order these results by their cost_amount in descending order.

[Assistant] SELECT item_name, item_type FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Please also include the cost_currency and cost_amount in the output.

[Assistant] SELECT item_name, item_type, cost_currency, cost_amount FROM gaming_technology.in_game_items WHERE rarity = 'Epic' AND item_type = 'Weapon' ORDER BY cost_amount DESC;

[User] Show the usernames of players and a count of how many different item types they have in their inventory.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username;

[User] Only include players who have 3 or more different item types.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3;

[User] Order the results by the count of unique item types in descending order.

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3 ORDER BY count(DISTINCT T3.item_type) DESC;

[User] For these players, could you also show the total quantity of all items they possess?

[Assistant] SELECT T1.username, count(DISTINCT T3.item_type), sum(T2.quantity) FROM gaming_technology.players AS T1 JOIN gaming_technology.player_inventory AS T2 ON T1.player_id = T2.player_id JOIN gaming_technology.in_game_items AS T3 ON T2.item_id = T3.item_id GROUP BY T1.username HAVING count(DISTINCT T3.item_type) >= 3 ORDER BY count(DISTINCT T3.item_type) 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.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )

[User] I want to retrieve the agent ID, first and last name, along with their manager's contact email and phone number.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id;

[User] Please filter to only agents who have a non-null manager and whose hire_date is after '2022-06-30'.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30';

[User] Additionally, sort the results by the agent's hire_date in ascending order.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30'
ORDER BY a.hire_date ASC;

[User] Finally, limit the result to 10 rows.

[Assistant]
SELECT a.agent_id,
       a.first_name || ' ' || a.last_name AS agent_name,
       m.contact_email AS manager_email,
       m.contact_phone AS manager_phone
FROM insurance.agents a
INNER JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2022-06-30'
ORDER BY a.hire_date ASC
LIMIT 10;

[User] Please list the agent ID, agent's name, and manager's email for all agents who have a commission_rate greater than 0.12.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, m.contact_email AS manager_email
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.12;

[User] Filter these results to only include agents whose own status is 'active'.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, m.contact_email AS manager_email
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.commission_rate > 0.12 AND a.status = 'active';

[User] What is the average commission_rate for each agent status and only show statuses with an average commission_rate above 0.05?

[Assistant]
SELECT status,
       AVG(commission_rate) AS avg_commission_rate
FROM insurance.agents
GROUP BY status
HAVING AVG(commission_rate) > 0.05;

[User] Find all agents hired after '2021-01-01', including their first_name, last_name, hire_date, and their manager's full name.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE a.hire_date > '2021-01-01';

[User] Actually, include only those whose manager is in the same license_state as the agent.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01';

[User] I need only those with commission_rate above 0.05 and status 'Active'.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active';

[User] Sort the results by commission_rate descending and limit to the top 10.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.hire_date,
       a.commission_rate,
       m.first_name || ' ' || m.last_name AS manager_full_name
FROM insurance.agents a
JOIN insurance.agents m
  ON a.manager_id = m.agent_id
 AND a.license_state = m.license_state
WHERE a.hire_date > '2021-01-01'
  AND a.commission_rate > 0.05
  AND a.status = 'Active'
ORDER BY a.commission_rate DESC
LIMIT 10;

[User] Find managers who have at least one agent reporting to them whose status is 'inactive'. List the manager's full name and the full name of the inactive agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Could you also include the inactive agent's termination date in the results?

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive'

[User] Filter the results to only include cases where the manager is currently 'active'.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, T1.first_name AS agent_first_name, T1.last_name AS agent_last_name, T1.termination_date FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id WHERE T1.status = 'inactive' AND T2.status = 'active'

[User] Retrieve a list of agents who were hired in 2024. Include agent_id, first_name, last_name, hire_date.

[Assistant]
SELECT agent_id, first_name, last_name, hire_date
FROM insurance.agents
WHERE hire_date >= '2024-01-01' AND hire_date < '2025-01-01';

[User] Show the full name of each manager and the average commission rate of the agents who report directly to them. Only include managers who have at least one reporting agent.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name

[User] Filter the results to only show managers whose average agent commission rate is above 0.12.

[Assistant] SELECT T2.first_name AS manager_first_name, T2.last_name AS manager_last_name, AVG(T1.commission_rate) AS average_agent_commission_rate FROM insurance.agents AS T1 JOIN insurance.agents AS T2 ON T1.manager_id = T2.agent_id GROUP BY T2.agent_id, T2.first_name, T2.last_name HAVING AVG(T1.commission_rate) > 0.12

[User] List each agent along with their manager's contact_email. Include agent_id, first_name, last_name, manager_id, and manager's contact_email.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.manager_id,
       m.contact_email AS manager_contact_email
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id;

[User] Actually, only include records where the manager is currently active.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.manager_id,
       m.contact_email AS manager_contact_email
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE m.status = 'active';

[User] Which five license states have the highest count of active agents? Return the license_state and agent_count.

[Assistant]
SELECT license_state,
       COUNT(*) AS agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state
ORDER BY agent_count DESC
LIMIT 5;

[User] List the full names and contact email of agents whose agency name contains 'Insurance'.

[Assistant] SELECT first_name, last_name, contact_email FROM insurance.agents WHERE agency_name LIKE '%Insurance%'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)

[User] List all documents along with the document type and the case name they are associated with.

[Assistant]
SELECT d.document_name, d.document_type, c.case_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id;

[User] Show only documents uploaded by lawyers whose specialization is 'Employment Law'.

[Assistant]
SELECT d.document_name, d.document_type, c.case_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.specialization = 'Employment Law';

[User] Also, include the lawyer's full name and order the results by upload_timestamp descending.

[Assistant]
SELECT d.document_name, d.document_type, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.specialization = 'Employment Law'
ORDER BY d.upload_timestamp DESC;

[User] Exclude any documents where the document_type is null.

[Assistant]
SELECT d.document_name, d.document_type, c.case_name, l.first_name || ' ' || l.last_name AS lawyer_full_name
FROM legal_services.documents d
JOIN legal_services.cases c ON d.case_id = c.case_id
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.specialization = 'Employment Law' AND d.document_type IS NOT NULL
ORDER BY d.upload_timestamp DESC;

[User] Show me a list of all appointments with the subject and full name of the assigned lawyer.

[Assistant]
SELECT a.appointment_id, a.subject, l.first_name || ' ' || l.last_name AS lawyer_full_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id;

[User] Can you show me all invoices with their invoice number, total amount, due date, and the full name of the client associated with the invoice?

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id;

[User] I only want invoices where the due date is in the next 14 days. Could you update the query?

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
WHERE i.due_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '14 days';

[User] Also, add the status column from invoices and order the results by due_date ascending.

[Assistant]
SELECT i.invoice_number, i.total_amount, i.due_date, i.status, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
JOIN legal_services.clients c ON i.client_id = c.client_id
WHERE i.due_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '14 days'
ORDER BY i.due_date ASC;

[User] Which lawyers have handled cases in the 'Federal Court' jurisdiction? Return each lawyer's first and last name, the case number, and the court jurisdiction.

[Assistant]
SELECT l.first_name, l.last_name, c.case_number, c.court_jurisdiction
FROM legal_services.lawyers l
JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
WHERE c.court_jurisdiction = 'Federal Court';

[User] Retrieve all lawyers specializing in 'Corporate Law', including their first_name, last_name, email, and phone.

[Assistant]
SELECT first_name, last_name, email, phone
FROM legal_services.lawyers
WHERE specialization = 'Corporate Law';

[User] List each client's first and last name along with the number of cases they have, alias the count as case_count.

[Assistant]
SELECT cl.first_name, cl.last_name, COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name;

[User] Actually, only include clients who have more than 2 cases.

[Assistant]
SELECT cl.first_name, cl.last_name, COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING COUNT(c.case_id) > 2;

[User] Also sort the results by case_count descending and then by the client's last_name ascending.

[Assistant]
SELECT cl.first_name, cl.last_name, COUNT(c.case_id) AS case_count
FROM legal_services.clients cl
LEFT JOIN legal_services.cases c ON cl.client_id = c.client_id
GROUP BY cl.client_id, cl.first_name, cl.last_name
HAVING COUNT(c.case_id) > 2
ORDER BY case_count DESC, cl.last_name ASC;

[User] Show the subject and start time of appointments, along with the full name of the lawyer assigned to each appointment.

[Assistant] SELECT T1.subject, T1.start_time, T2.first_name, T2.last_name FROM legal_services.appointments AS T1 JOIN legal_services.lawyers AS T2 ON T1.lawyer_id = T2.lawyer_id

[User] Only include appointments that have been completed after the start of 2024.

[Assistant] SELECT T1.subject, T1.start_time, T2.first_name, T2.last_name FROM legal_services.appointments AS T1 JOIN legal_services.lawyers AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T1.status = 'Completed' AND T1.start_time >= '2024-01-01'

[User] List the full name and firm name for all lawyers who are not partners.

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

[User] Now, only show those non-partner lawyers whose specialization is 'Litigation'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = FALSE AND T1.specialization = 'Litigation'

[User] Filter this list to only include those hired after 2021-01-01 and order by hire date.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = FALSE AND T1.specialization = 'Litigation' AND T1.hire_date > '2021-01-01' ORDER BY T1.hire_date

[User] Get me a list of law firms with the firm_name, founded_date, the managing partner's full name, and the total number of partners at that firm.

[Assistant]
SELECT f.firm_name, f.founded_date, mp.first_name || ' ' || mp.last_name AS managing_partner_full_name, COUNT(l.lawyer_id) FILTER (WHERE l.is_partner) AS partner_count
FROM legal_services.law_firms f
LEFT JOIN legal_services.lawyers mp ON f.managing_partner_id = mp.lawyer_id
LEFT JOIN legal_services.lawyers l ON f.firm_id = l.firm_id
GROUP BY f.firm_id, f.firm_name, f.founded_date, mp.first_name, mp.last_name;

[User] Now restrict the list to firms founded after 2010 that have at least 2 partners, and order by partner_count descending.

[Assistant]
SELECT f.firm_name, f.founded_date, mp.first_name || ' ' || mp.last_name AS managing_partner_full_name, COUNT(l.lawyer_id) FILTER (WHERE l.is_partner) AS partner_count
FROM legal_services.law_firms f
LEFT JOIN legal_services.lawyers mp ON f.managing_partner_id = mp.lawyer_id
LEFT JOIN legal_services.lawyers l ON f.firm_id = l.firm_id
GROUP BY f.firm_id, f.firm_name, f.founded_date, mp.first_name, mp.last_name
HAVING COUNT(l.lawyer_id) FILTER (WHERE l.is_partner) >= 2
  AND f.founded_date > '2010-01-01'
ORDER BY partner_count DESC;

[User] Show me all open cases along with the case number, the client's full name, and the name and email of the lead lawyer.

[Assistant]
SELECT c.case_number, cl.first_name || ' ' || cl.last_name AS client_full_name, l.first_name || ' ' || l.last_name AS lead_lawyer_full_name, l.email AS lead_lawyer_email
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
JOIN legal_services.lawyers l ON c.lead_lawyer_id = l.lawyer_id
WHERE c.status = 'Open';

[User] Now also include the court_jurisdiction and only include cases opened after January 1, 2022.

[Assistant]
SELECT c.case_number, cl.first_name || ' ' || cl.last_name AS client_full_name, l.first_name || ' ' || l.last_name AS lead_lawyer_full_name, l.email AS lead_lawyer_email, c.court_jurisdiction
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
JOIN legal_services.lawyers l ON c.lead_lawyer_id = l.lawyer_id
WHERE c.status = 'Open'
  AND c.date_opened > '2022-01-01';

[User] Great, please sort the results by date_opened ascending and show only the first 10 rows.

[Assistant]
SELECT c.case_number, cl.first_name || ' ' || cl.last_name AS client_full_name, l.first_name || ' ' || l.last_name AS lead_lawyer_full_name, l.email AS lead_lawyer_email, c.court_jurisdiction
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
JOIN legal_services.lawyers l ON c.lead_lawyer_id = l.lawyer_id
WHERE c.status = 'Open'
  AND c.date_opened > '2022-01-01'
ORDER BY c.date_opened 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 transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)

[User] For each trip, show the trip ID, vehicle ID, driver ID, and both the actual starting and ending location IDs.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id FROM transportation.trips;

[User] List all unique pairs of origin and destination location IDs that have been used in trips, and count how many trips have occurred for each pair.

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

[User] Find pairs of trip IDs where both trips departed on the same calendar day, shared the same origin and destination locations, but were distinct trips.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id;

[User] From those pairs, filter the results to only include pairs where the actual departure times were within 2 hours of each other.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date,
  t1.actual_departure AS actual_departure_1,
  t2.actual_departure AS actual_departure_2
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id
WHERE
  t1.actual_departure IS NOT NULL
  AND t2.actual_departure IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (t1.actual_departure - t2.actual_departure))) <= 7200;

[User] Show the average passenger_count for each trip status.

[Assistant]
SELECT status, AVG(passenger_count) AS avg_passengers
FROM transportation.trips
GROUP BY status;

[User] Only include statuses with at least 10 trips.

[Assistant]
SELECT status, AVG(passenger_count) AS avg_passengers
FROM transportation.trips
GROUP BY status
HAVING COUNT(*) >= 10;

[User] Retrieve trip_id and passenger full names for all trips where the passenger record was created before the scheduled departure.

[Assistant]
SELECT t.trip_id, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure;

[User] Filter the results to only include trips with passenger_count greater than 5.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5;

[User] Also sort the output by passenger_count descending and limit to the top 10 records.

[Assistant]
SELECT t.trip_id, t.passenger_count, p.first_name || ' ' || p.last_name AS passenger_name
FROM transportation.trips t
JOIN transportation.passengers p
  ON p.created_at < t.scheduled_departure
WHERE t.passenger_count > 5
ORDER BY t.passenger_count DESC
LIMIT 10;

[User] Show me the trip details including actual and scheduled times, and the difference between them for all trips associated with a specific driver, say driver_id 'DRV789'.

[Assistant]
SELECT
  trip_id,
  vehicle_id,
  scheduled_departure,
  actual_departure,
  scheduled_arrival,
  actual_arrival,
  status,
  (actual_departure - scheduled_departure) AS departure_delay,
  (actual_arrival - scheduled_arrival) AS arrival_delay
FROM transportation.trips
WHERE
  driver_id = 'DRV789';

[User] Now, focusing on driver 'DRV789', identify consecutive pairs of trips based on scheduled departure time. Show the trip IDs and scheduled times for both trips in each pair.

[Assistant]
SELECT
  t1.trip_id AS first_trip_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t2.trip_id AS next_trip_id,
  t2.scheduled_departure AS next_scheduled_departure
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.driver_id = t2.driver_id
WHERE
  t1.driver_id = 'DRV789'
  AND t2.scheduled_departure = (
    SELECT MIN(scheduled_departure)
    FROM transportation.trips AS t3
    WHERE
      t3.driver_id = t1.driver_id
      AND t3.scheduled_departure > t1.scheduled_departure
  )
ORDER BY
  t1.scheduled_departure;

[User] Filter these consecutive trips for driver 'DRV789' to only show pairs where the destination location of the first trip is the same as the origin location of the second trip.

[Assistant]
SELECT
  t1.trip_id AS first_trip_id,
  t1.scheduled_departure AS first_scheduled_departure,
  t1.destination_location_id AS first_trip_destination,
  t2.trip_id AS next_trip_id,
  t2.scheduled_departure AS next_scheduled_departure,
  t2.origin_location_id AS next_trip_origin
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.driver_id = t2.driver_id
WHERE
  t1.driver_id = 'DRV789'
  AND t2.scheduled_departure = (
    SELECT MIN(scheduled_departure)
    FROM transportation.trips AS t3
    WHERE
      t3.driver_id = t1.driver_id
      AND t3.scheduled_departure > t1.scheduled_departure
  )
  AND t1.destination_location_id = t2.origin_location_id
ORDER BY
  t1.scheduled_departure;

[User] Can you show me all pairs of trips that use the same vehicle but have different drivers? Please include both trip IDs, vehicle_id, and the driver_id for each trip.

[Assistant]
SELECT t1.trip_id AS trip_id_1, t2.trip_id AS trip_id_2, t1.vehicle_id, t1.driver_id AS driver_id_1, t2.driver_id AS driver_id_2
FROM transportation.trips t1
JOIN transportation.trips t2
  ON t1.vehicle_id = t2.vehicle_id
 AND t1.trip_id < t2.trip_id
 AND t1.driver_id <> t2.driver_id;

[User] Actually, I also want to see only those pairs where both trips have a status of 'Completed'.

[Assistant]
SELECT t1.trip_id AS trip_id_1, t2.trip_id AS trip_id_2, t1.vehicle_id, t1.driver_id AS driver_id_1, t2.driver_id AS driver_id_2
FROM transportation.trips t1
JOIN transportation.trips t2
  ON t1.vehicle_id = t2.vehicle_id
 AND t1.trip_id < t2.trip_id
 AND t1.driver_id <> t2.driver_id
WHERE t1.status = 'Completed' AND t2.status = 'Completed';

[User] Show me all in-progress trips with their current locations (origin_location_id) and destinations, along with the scheduled vs actual departure time difference in minutes.

[Assistant] SELECT trip_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress';

[User] Can you also include the vehicle_id and driver_id, and order by the departure delay in descending order?

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress' ORDER BY departure_delay_minutes DESC;

[User] Now filter to only show trips that have been delayed by more than 30 minutes.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id, EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 AS departure_delay_minutes FROM transportation.trips WHERE status = 'In Progress' AND EXTRACT(EPOCH FROM (actual_departure - scheduled_departure))/60 > 30 ORDER BY departure_delay_minutes DESC;

[User] List all trips that were completed and experienced a significant delay in actual arrival compared to the scheduled arrival (more than 45 minutes).

[Assistant]
SELECT
  trip_id,
  vehicle_id,
  driver_id,
  scheduled_arrival,
  actual_arrival,
  (actual_arrival - scheduled_arrival) AS arrival_delay
FROM transportation.trips
WHERE
  status = 'Completed'
  AND actual_arrival IS NOT NULL
  AND actual_arrival > scheduled_arrival + INTERVAL '45 minutes';

[User] For those completed trips with significant arrival delays, provide a count of how many fall into different delay duration categories: '45-90 mins', '>90 mins'.

[Assistant]
SELECT
  CASE
    WHEN (actual_arrival - scheduled_arrival) > INTERVAL '45 minutes' AND (actual_arrival - scheduled_arrival) <= INTERVAL '90 minutes' THEN '45-90 mins'
    WHEN (actual_arrival - scheduled_arrival) > INTERVAL '90 minutes' THEN '>90 mins'
    ELSE 'Other Delays' -- Should not be reached based on previous filter, but good practice
  END AS delay_category,
  COUNT(*)
FROM transportation.trips
WHERE
  status = 'Completed'
  AND actual_arrival IS NOT NULL
  AND actual_arrival > scheduled_arrival + INTERVAL '45 minutes'
GROUP BY
  delay_category;

[User] Show me the count of trips by status for each vehicle, but only include vehicles that have had more than 5 trips total.

[Assistant] SELECT vehicle_id, status, COUNT(*) as trip_count FROM transportation.trips GROUP BY vehicle_id, status HAVING COUNT(*) > 5;

[User] Now filter this to only show vehicles that have had at least 2 cancelled trips.

[Assistant] SELECT vehicle_id, COUNT(*) as cancelled_trips FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2;

[User] Combine both queries to show me vehicles with more than 5 total trips and at least 2 cancelled trips, along with their complete status distribution.

[Assistant] SELECT t.vehicle_id, t.status, COUNT(*) as trip_count FROM transportation.trips t JOIN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 5 INTERSECT SELECT vehicle_id FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2) v ON t.vehicle_id = v.vehicle_id GROUP BY t.vehicle_id, t.status;


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.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List all service orders with quantity greater than 3, showing the order ID, total price, and the staff member who placed the order.

[Assistant]
SELECT order_id, total_price, staff_id_ordered
FROM hospitality_technology.service_orders
WHERE quantity > 3;

[User] Please add the delivery timestamp, and only show orders that were actually delivered (delivery_timestamp is not null).

[Assistant]
SELECT order_id, total_price, staff_id_ordered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL;

[User] Now, show only those orders where the delivered staff is different from the ordered staff, and sort by delivery timestamp ascending.

[Assistant]
SELECT order_id, total_price, staff_id_ordered, staff_id_delivered, delivery_timestamp
FROM hospitality_technology.service_orders
WHERE quantity > 3
  AND delivery_timestamp IS NOT NULL
  AND staff_id_ordered <> staff_id_delivered
ORDER BY delivery_timestamp ASC;

[User] List each staff member who delivered orders, along with the number of orders they delivered.

[Assistant] SELECT staff_id_delivered, COUNT(order_id) AS delivered_orders FROM hospitality_technology.service_orders WHERE staff_id_delivered IS NOT NULL GROUP BY staff_id_delivered;

[User] Only show staff who delivered more than 10 orders.

[Assistant] SELECT staff_id_delivered, COUNT(order_id) AS delivered_orders FROM hospitality_technology.service_orders WHERE staff_id_delivered IS NOT NULL GROUP BY staff_id_delivered HAVING COUNT(order_id) > 10;

[User] Get the total_quantity and total_revenue (sum of total_price) for each staff member who placed orders (staff_id_ordered).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
GROUP BY staff_id_ordered;

[User] Filter to staff who have delivered at least one order (staff_id_delivered is not null).

[Assistant]
SELECT staff_id_ordered,
       SUM(quantity) AS total_quantity,
       SUM(total_price) AS total_revenue
FROM hospitality_technology.service_orders
WHERE staff_id_delivered IS NOT NULL
GROUP BY staff_id_ordered;

[User] For these staff members, list each order along with the previous order they placed, including first_order_timestamp and second_order_timestamp, and the time difference in hours.

[Assistant]
SELECT t1.staff_id_ordered,
       t1.order_id AS first_order_id,
       t2.order_id AS second_order_id,
       t1.order_timestamp AS first_order_timestamp,
       t2.order_timestamp AS second_order_timestamp,
       EXTRACT(EPOCH FROM (t2.order_timestamp - t1.order_timestamp)) / 3600 AS hours_diff
FROM hospitality_technology.service_orders t1
JOIN hospitality_technology.service_orders t2
  ON t1.staff_id_ordered = t2.staff_id_ordered
 AND t2.order_timestamp > t1.order_timestamp
 AND NOT EXISTS (
       SELECT 1 FROM hospitality_technology.service_orders t3
       WHERE t3.staff_id_ordered = t1.staff_id_ordered
         AND t3.order_timestamp > t1.order_timestamp
         AND t3.order_timestamp < t2.order_timestamp
   )
WHERE t1.staff_id_delivered IS NOT NULL
  AND t2.staff_id_delivered IS NOT NULL
ORDER BY t1.staff_id_ordered, t1.order_timestamp;

[User] Show me the total quantity and total price for each service ordered by each guest.

[Assistant] SELECT guest_id, service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_price FROM hospitality_technology.service_orders GROUP BY guest_id, service_id;

[User] List the total number of service orders placed by each staff member who delivered the service.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered;

[User] Show only those staff members who have delivered at least 20 service orders and order the results by order_count descending.

[Assistant] SELECT staff_id_delivered, COUNT(*) AS order_count FROM hospitality_technology.service_orders GROUP BY staff_id_delivered HAVING COUNT(*) >= 20 ORDER BY order_count DESC;

[User] Show the total revenue and the average order value for each order status.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status;

[User] Please only include statuses where the total revenue is above 1000.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000;

[User] Also order the results by total revenue descending.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000 ORDER BY total_revenue DESC;

[User] Show me the total quantity and total revenue for each service, along with the number of unique guests who ordered each service.

[Assistant] SELECT service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_revenue, COUNT(DISTINCT guest_id) AS unique_guest_count FROM hospitality_technology.service_orders GROUP BY service_id;

[User] Now, only include services where the total revenue is above 1000 and sort by total_revenue descending.

[Assistant] SELECT service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_revenue, COUNT(DISTINCT guest_id) AS unique_guest_count FROM hospitality_technology.service_orders GROUP BY service_id HAVING SUM(total_price) > 1000 ORDER BY total_revenue DESC;

[User] Which day had the highest number of service orders? Show the date and order count.

[Assistant]
SELECT DATE(order_timestamp) AS order_date,
       COUNT(*) AS order_count
FROM hospitality_technology.service_orders
GROUP BY DATE(order_timestamp)
ORDER BY order_count DESC
LIMIT 1;

[User] Now, list the top 10 busiest days but only include days with more than 5 orders.

[Assistant]
SELECT DATE(order_timestamp) AS order_date,
       COUNT(*) AS order_count
FROM hospitality_technology.service_orders
GROUP BY DATE(order_timestamp)
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 10;

[User] List all service orders with quantity greater than 1 and total price exceeding 50. Show order ID, guest ID, quantity, and total price.

[Assistant] SELECT order_id, guest_id, quantity, total_price FROM hospitality_technology.service_orders WHERE quantity > 1 AND total_price > 50;

[User] Find guests who ordered the same service more than once on the same reservation and date. Return guest_id, reservation_id, service_id, and the date.

[Assistant]
SELECT so1.guest_id,
       so1.reservation_id,
       so1.service_id,
       DATE(so1.order_timestamp) AS order_date
FROM hospitality_technology.service_orders so1
JOIN hospitality_technology.service_orders so2
  ON so1.guest_id = so2.guest_id
 AND so1.reservation_id = so2.reservation_id
 AND so1.service_id = so2.service_id
 AND DATE(so1.order_timestamp) = DATE(so2.order_timestamp)
 AND so1.order_id < so2.order_id
GROUP BY so1.guest_id, so1.reservation_id, so1.service_id, DATE(so1.order_timestamp);

[User] Actually, consider only orders where status = 'Delivered'.

[Assistant]
SELECT so1.guest_id,
       so1.reservation_id,
       so1.service_id,
       DATE(so1.order_timestamp) AS order_date
FROM hospitality_technology.service_orders so1
JOIN hospitality_technology.service_orders so2
  ON so1.guest_id = so2.guest_id
 AND so1.reservation_id = so2.reservation_id
 AND so1.service_id = so2.service_id
 AND DATE(so1.order_timestamp) = DATE(so2.order_timestamp)
 AND so1.order_id < so2.order_id
WHERE so1.status = 'Delivered'
  AND so2.status = 'Delivered'
GROUP BY so1.guest_id, so1.reservation_id, so1.service_id, DATE(so1.order_timestamp);

[User] Also, count how many times each service was reordered per date and sort by that count descending.

[Assistant]
SELECT so1.guest_id,
       so1.reservation_id,
       so1.service_id,
       DATE(so1.order_timestamp) AS order_date,
       COUNT(*) AS reorder_count
FROM hospitality_technology.service_orders so1
JOIN hospitality_technology.service_orders so2
  ON so1.guest_id = so2.guest_id
 AND so1.reservation_id = so2.reservation_id
 AND so1.service_id = so2.service_id
 AND DATE(so1.order_timestamp) = DATE(so2.order_timestamp)
 AND so1.order_id < so2.order_id
WHERE so1.status = 'Delivered'
  AND so2.status = 'Delivered'
GROUP BY so1.guest_id, so1.reservation_id, so1.service_id, DATE(so1.order_timestamp)
ORDER BY reorder_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
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )

[User] Show me the subjects and start times of all appointments for a specific client, along with the assigned lawyer ID.

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123';

[User] Could you narrow it down to only include appointments where the status is 'Rescheduled' or 'Postponed'?

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed');

[User] Also, please make sure the appointments were created after June 1st, 2024 and order the results by start_time ascending.

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed') AND created_at > '2024-06-01' ORDER BY start_time ASC;

[User] I want to find all appointment pairs where two appointments are scheduled for the same client at overlapping times. Provide the appointment_id from both overlapping appointments.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.client_id = a2.client_id
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time;

[User] Actually, only include pairs where both appointments have status 'scheduled'.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.client_id = a2.client_id
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
WHERE a1.status = 'scheduled'
  AND a2.status = 'scheduled';

[User] And ensure the overlapping appointments start within 1 hour of each other.

[Assistant]
SELECT a1.appointment_id AS appointment_id_1, a2.appointment_id AS appointment_id_2
FROM legal_services.appointments a1
JOIN legal_services.appointments a2
  ON a1.client_id = a2.client_id
 AND a1.appointment_id < a2.appointment_id
 AND a1.start_time < a2.end_time
 AND a2.start_time < a1.end_time
 AND ABS(EXTRACT(EPOCH FROM (a1.start_time - a2.start_time))) <= 3600
WHERE a1.status = 'scheduled'
  AND a2.status = 'scheduled';

[User] List each appointment along with the start_time of the next appointment for the same lawyer. Include appointment_id and next_start_time.

[Assistant]
SELECT appointment_id,
       LEAD(start_time) OVER (PARTITION BY lawyer_id ORDER BY start_time) AS next_start_time
FROM legal_services.appointments;

[User] Only include those where next_start_time is within 30 days of the original appointment.

[Assistant]
WITH ordered AS (
  SELECT appointment_id,
         start_time,
         LEAD(start_time) OVER (PARTITION BY lawyer_id ORDER BY start_time) AS next_start_time
  FROM legal_services.appointments
)
SELECT appointment_id, next_start_time
FROM ordered
WHERE next_start_time IS NOT NULL
  AND next_start_time <= start_time + INTERVAL '30 days';

[User] List all appointments for the client with ID 'client_001' showing the lawyer's ID, appointment subject, and start time.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time
FROM legal_services.appointments a
WHERE a.client_id = 'client_001';

[User] Actually, please also include the case ID in the results.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time, a.case_id
FROM legal_services.appointments a
WHERE a.client_id = 'client_001';

[User] Now, sort the results by start time from newest to oldest.

[Assistant]
SELECT a.lawyer_id, a.subject, a.start_time, a.case_id
FROM legal_services.appointments a
WHERE a.client_id = 'client_001'
ORDER BY a.start_time DESC;

[User] How many appointments have been scheduled on weekends?

[Assistant]
SELECT COUNT(*) AS weekend_appointments
FROM legal_services.appointments
WHERE EXTRACT(DOW FROM start_time) IN (0,6);

[User] Show me all appointments with their subjects and the names of the lawyers who handled them.

[Assistant]
SELECT a.appointment_id, a.subject, l.first_name, l.last_name
FROM legal_services.appointments a
JOIN legal_services.lawyers l ON a.lawyer_id = l.lawyer_id;

[User] Find all pairs of appointments that are scheduled for the same case and overlap in time. Show the IDs of the two overlapping appointments and the shared case ID.

[Assistant] SELECT t1.appointment_id AS appointment1_id, t2.appointment_id AS appointment2_id, t1.case_id FROM legal_services.appointments AS t1 JOIN legal_services.appointments AS t2 ON t1.case_id = t2.case_id AND t1.appointment_id != t2.appointment_id WHERE t1.start_time < t2.end_time AND t2.start_time < t1.end_time;

[User] Show me all appointments where the lawyer_id matches the client_id, and display the appointment_id, start_time, and status.

[Assistant] SELECT appointment_id, start_time, status FROM legal_services.appointments WHERE lawyer_id = client_id;

[User] List the appointment ID, subject, location, and lawyer ID for all appointments where there is at least one other appointment with the same location and lawyer assigned.

[Assistant] SELECT appointment_id, subject, location, lawyer_id FROM legal_services.appointments AS a1 WHERE EXISTS (SELECT 1 FROM legal_services.appointments AS a2 WHERE a1.location = a2.location AND a1.lawyer_id = a2.lawyer_id AND a1.appointment_id != a2.appointment_id);

[User] Actually, can you also include the start time for these appointments?

[Assistant] SELECT appointment_id, subject, location, lawyer_id, start_time FROM legal_services.appointments AS a1 WHERE EXISTS (SELECT 1 FROM legal_services.appointments AS a2 WHERE a1.location = a2.location AND a1.lawyer_id = a2.lawyer_id AND a1.appointment_id != a2.appointment_id);

[User] Now, only show appointments with status 'Scheduled' and sort them by creation timestamp descending.

[Assistant] SELECT appointment_id, subject, location, lawyer_id, start_time FROM legal_services.appointments AS a1 WHERE a1.status = 'Scheduled' AND EXISTS (SELECT 1 FROM legal_services.appointments AS a2 WHERE a1.location = a2.location AND a1.lawyer_id = a2.lawyer_id AND a1.appointment_id != a2.appointment_id) ORDER BY a1.created_at DESC;

[User] Find appointments that are longer than 30 minutes.

[Assistant] SELECT * FROM legal_services.appointments WHERE end_time IS NOT NULL AND start_time IS NOT NULL AND end_time > start_time + INTERVAL '30 minutes'


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.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)

[User] For each trip, provide the trip_id, the total fuel quantity refueled, and the number of refueling events that occurred during the trip.

[Assistant]
SELECT trip_id, SUM(quantity) AS total_fuel_quantity, COUNT(*) AS refuel_event_count
FROM transportation.fuel_logs
WHERE trip_id IS NOT NULL
GROUP BY trip_id;

[User] For each fuel type, list the number of unique locations where fuel refueling occurred, and also show the total quantity refueled for that fuel type and location.

[Assistant]
SELECT fuel_type, location_id, COUNT(DISTINCT location_id) AS unique_location_count, SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY fuel_type, location_id;

[User] Show all fuel logs for vehicle_id 'VH123', including the timestamp, fuel type, quantity, and the location_id. Sort the list by timestamp descending.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] Can you also include the odometer reading and total cost for each fuel log in the result?

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
ORDER BY log_timestamp DESC;

[User] I only want to see records where the total_cost is above 100.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp DESC;

[User] Actually, please limit the results to just the 5 most recent logs.

[Assistant]
SELECT fuel_log_id, log_timestamp, fuel_type, quantity, location_id, odometer_reading, total_cost
FROM transportation.fuel_logs
WHERE vehicle_id = 'VH123'
  AND total_cost > 100
ORDER BY log_timestamp DESC
LIMIT 5;

[User] I need the total fuel cost per vehicle for each fuel type.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type;

[User] Filter this to only include records where the cost_per_unit is greater than 1.50.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type;

[User] Also, sort the result by the total cost in descending order.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC;

[User] Finally, limit the output to the top 5 entries.

[Assistant]
SELECT vehicle_id, fuel_type, SUM(total_cost) AS total_cost_per_type
FROM transportation.fuel_logs
WHERE cost_per_unit > 1.50
GROUP BY vehicle_id, fuel_type
ORDER BY total_cost_per_type DESC
LIMIT 5;

[User] For each vehicle, show the first and last fueling events including their timestamps and the quantities refueled.

[Assistant]
WITH first_last AS (
  SELECT
    vehicle_id,
    MIN(log_timestamp) AS first_time,
    MAX(log_timestamp) AS last_time
  FROM transportation.fuel_logs
  GROUP BY vehicle_id
)
SELECT
  f1.vehicle_id,
  f1.log_timestamp AS first_refuel_time,
  f1.quantity AS first_quantity,
  f2.log_timestamp AS last_refuel_time,
  f2.quantity AS last_quantity
FROM first_last fl
JOIN transportation.fuel_logs f1
  ON fl.vehicle_id = f1.vehicle_id
  AND fl.first_time = f1.log_timestamp
JOIN transportation.fuel_logs f2
  ON fl.vehicle_id = f2.vehicle_id
  AND fl.last_time = f2.log_timestamp;

[User] For each fuel_type, can you calculate the total total_cost and the average total_cost from the fuel_logs table?

[Assistant]
SELECT fuel_type,
       SUM(total_cost) AS total_cost_sum,
       AVG(total_cost) AS average_cost
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Please exclude any fuel_type with fewer than 5 fuel log entries.

[Assistant]
SELECT fuel_type,
       SUM(total_cost) AS total_cost_sum,
       AVG(total_cost) AS average_cost
FROM transportation.fuel_logs
GROUP BY fuel_type
HAVING COUNT(*) >= 5;

[User] For each fueling event, show its fuel_log_id, vehicle_id, log_timestamp, and the previous fueling event's fuel_log_id, log_timestamp, and quantity for the same vehicle.

[Assistant]
SELECT fl.fuel_log_id,
       fl.vehicle_id,
       fl.log_timestamp AS current_timestamp,
       fl.quantity AS current_quantity,
       prev.fuel_log_id AS previous_fuel_log_id,
       prev.log_timestamp AS previous_timestamp,
       prev.quantity AS previous_quantity
FROM transportation.fuel_logs fl
LEFT JOIN transportation.fuel_logs prev
  ON fl.vehicle_id = prev.vehicle_id
  AND prev.log_timestamp = (
    SELECT MAX(log_timestamp)
    FROM transportation.fuel_logs
    WHERE vehicle_id = fl.vehicle_id
      AND log_timestamp < fl.log_timestamp
  );

[User] I need a summary of fueling events grouped by fuel_type: count of events and total quantity.

[Assistant]
SELECT
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Actually, could you break it down by vehicle as well, so I can see for each vehicle and fuel_type the number of events and total quantity?

[Assistant]
SELECT
  vehicle_id,
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type;

[User] Only include those groups where total_quantity exceeds 100 units.

[Assistant]
SELECT
  vehicle_id,
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type
HAVING SUM(quantity) > 100;

[User] Sort the results by total_quantity descending and limit to top 5 rows.

[Assistant]
SELECT
  vehicle_id,
  fuel_type,
  COUNT(*) AS event_count,
  SUM(quantity) AS total_quantity
FROM transportation.fuel_logs
GROUP BY vehicle_id, fuel_type
HAVING SUM(quantity) > 100
ORDER BY total_quantity DESC
LIMIT 5;

[User] List each vehicle that has both Diesel and Gasoline fueling events. Show vehicle_id, the fuel_log_id and log_timestamp for the Diesel event, and the fuel_log_id and log_timestamp for the Gasoline event.

[Assistant]
SELECT d.vehicle_id,
       d.fuel_log_id AS diesel_log_id,
       d.log_timestamp AS diesel_timestamp,
       g.fuel_log_id AS gasoline_log_id,
       g.log_timestamp AS gasoline_timestamp
FROM transportation.fuel_logs d
JOIN transportation.fuel_logs g
  ON d.vehicle_id = g.vehicle_id
WHERE d.fuel_type = 'Diesel'
  AND g.fuel_type = 'Gasoline';

[User] Could you restrict the results to events that occurred within the last 6 months?

[Assistant]
SELECT d.vehicle_id,
       d.fuel_log_id AS diesel_log_id,
       d.log_timestamp AS diesel_timestamp,
       g.fuel_log_id AS gasoline_log_id,
       g.log_timestamp AS gasoline_timestamp
FROM transportation.fuel_logs d
JOIN transportation.fuel_logs g
  ON d.vehicle_id = g.vehicle_id
WHERE d.fuel_type = 'Diesel'
  AND g.fuel_type = 'Gasoline'
  AND d.log_timestamp >= NOW() - INTERVAL '6 months'
  AND g.log_timestamp >= NOW() - INTERVAL '6 months';

[User] Also include the total_cost for both logs and alias them as diesel_cost and gasoline_cost.

[Assistant]
SELECT d.vehicle_id,
       d.fuel_log_id      AS diesel_log_id,
       d.log_timestamp   AS diesel_timestamp,
       d.total_cost      AS diesel_cost,
       g.fuel_log_id      AS gasoline_log_id,
       g.log_timestamp   AS gasoline_timestamp,
       g.total_cost      AS gasoline_cost
FROM transportation.fuel_logs d
JOIN transportation.fuel_logs g
  ON d.vehicle_id = g.vehicle_id
WHERE d.fuel_type = 'Diesel'
  AND g.fuel_type = 'Gasoline'
  AND d.log_timestamp >= NOW() - INTERVAL '6 months'
  AND g.log_timestamp >= NOW() - INTERVAL '6 months';

[User] List consecutive fueling events for each vehicle where the refill quantity increased compared to the previous event. Include vehicle_id, previous timestamp and quantity, current timestamp and quantity.

[Assistant]
SELECT
  prev.vehicle_id,
  prev.log_timestamp AS previous_time,
  prev.quantity AS previous_quantity,
  curr.log_timestamp AS current_time,
  curr.quantity AS current_quantity
FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS rn
  FROM transportation.fuel_logs
) prev
JOIN (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY log_timestamp) AS rn
  FROM transportation.fuel_logs
) curr
  ON prev.vehicle_id = curr.vehicle_id
  AND curr.rn = prev.rn + 1
WHERE curr.quantity > prev.quantity;


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 text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] List all active insurance products, including their product name, type, and base premium.

[Assistant] SELECT product_name, product_type, base_premium FROM insurance.insurance_products WHERE is_active = TRUE;

[User] Show me all claim documents that are PDFs and were uploaded in the last 30 days, along with their claim IDs and file sizes.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes, c.policy_id FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);

[User] I also want to see the policy details for these claims, including the coverage limit and premium amount.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes, c.policy_id, p.coverage_limit, p.premium_amount FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id JOIN insurance.policies p ON c.policy_id = p.policy_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);

[User] Now filter to only show documents larger than 1MB and include the upload date.

[Assistant] SELECT cd.document_id, cd.claim_id, cd.file_size_bytes, cd.uploaded_at, c.policy_id, p.coverage_limit, p.premium_amount FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id JOIN insurance.policies p ON c.policy_id = p.policy_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND cd.file_size_bytes > 1000000;

[User] Finally, show me the count of such PDF documents per policy, ordered by count descending.

[Assistant] SELECT c.policy_id, COUNT(cd.document_id) AS pdf_count FROM insurance.claim_documents cd JOIN insurance.claims c ON cd.claim_id = c.claim_id WHERE cd.mime_type = 'application/pdf' AND cd.uploaded_at >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) AND cd.file_size_bytes > 1000000 GROUP BY c.policy_id ORDER BY pdf_count DESC;

[User] List all claims that have at least one document of type 'INVOICE', including the claim ID, incident date, estimated loss, and the document's file name.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE';

[User] Also show the file size in bytes and the uploaded date for each document.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name, d.file_size_bytes, d.uploaded_at
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE';

[User] Actually, just show the claims where the document file size is greater than 100,000 bytes.

[Assistant]
SELECT c.claim_id, c.incident_date, c.estimated_loss, d.file_name, d.file_size_bytes, d.uploaded_at
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.document_type = 'INVOICE'
  AND d.file_size_bytes > 100000;

[User] Find all documents that are larger than 5MB. Show the document ID, claim ID, file name, and file size in bytes.

[Assistant]
SELECT document_id, claim_id, file_name, file_size_bytes
FROM insurance.claim_documents
WHERE file_size_bytes > 5242880;

[User] For each claim, count the number of documents linked to it. Show claim_id and document_count for claims that have more than 3 documents.

[Assistant]
SELECT claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents
group by claim_id
HAVING COUNT(*) > 3;

[User] Please also show the incident date for those claims.

[Assistant]
SELECT c.claim_id, c.incident_date, COUNT(d.document_id) AS document_count
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
GROUP BY c.claim_id, c.incident_date
HAVING COUNT(d.document_id) > 3;

[User] Show policy numbers and product names for all policies that started in 2023.

[Assistant] SELECT p.policy_number, ip.product_name FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023

[User] Add the policy status and the product type to the list.

[Assistant] SELECT p.policy_number, ip.product_name, p.status, ip.product_type FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023

[User] Filter these policies to only include those where the product is currently active and the policy status is 'active'.

[Assistant] SELECT p.policy_number, ip.product_name, p.status, ip.product_type FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE date_part('year', p.start_date) = 2023 AND p.status = 'active' AND ip.is_active = TRUE

[User] List all insurance products that have a base premium greater than 1000 and are currently active, showing product name, type, and base premium.

[Assistant] SELECT product_name, product_type, base_premium FROM insurance.insurance_products WHERE base_premium > 1000 AND is_active = TRUE

[User] Now, find policies associated with these products that were issued in 2024, showing the policy number and its premium amount.

[Assistant] SELECT p.policy_number, p.premium_amount FROM insurance.policies AS p JOIN insurance.insurance_products AS ip ON p.product_id = ip.product_id WHERE ip.base_premium > 1000 AND ip.is_active = TRUE AND date_part('year', p.issued_at) = 2024

[User] Show the total file size in bytes for all documents uploaded with a MIME type of 'application/pdf'.

[Assistant] SELECT SUM(file_size_bytes) FROM insurance.claim_documents WHERE mime_type = 'application/pdf'

[User] How many beneficiaries exist for each relationship type in the policy_beneficiaries table? Return relationship and beneficiary_count, ordered by count descending.

[Assistant]
SELECT relationship, COUNT(*) AS beneficiary_count
FROM insurance.policy_beneficiaries
GROUP BY relationship
ORDER BY beneficiary_count DESC;

[User] Retrieve the policy_number, claim_id, incident_date, and document_type for all claims that have at least one "Damage Assessment" document. Sort the results by incident_date descending.

[Assistant]
SELECT p.policy_number, c.claim_id, c.incident_date, cd.document_type
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
JOIN insurance.policies p ON c.policy_id = p.policy_id
WHERE cd.document_type = 'Damage Assessment'
ORDER BY c.incident_date DESC;