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.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] Count the number of passengers in each month of the year 2024 based on their created_at date.

[Assistant]
SELECT EXTRACT(MONTH FROM created_at) AS month, COUNT(*) AS passenger_count
FROM transportation.passengers
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
GROUP BY EXTRACT(MONTH FROM created_at)
ORDER BY month;

[User] Now, only include months where the passenger_count exceeds 50.

[Assistant]
SELECT EXTRACT(MONTH FROM created_at) AS month, COUNT(*) AS passenger_count
FROM transportation.passengers
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'
GROUP BY EXTRACT(MONTH FROM created_at)
HAVING COUNT(*) > 50
ORDER BY month;

[User] I want to see how many passengers were created each month.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers GROUP BY month;

[User] Only include months after January 2021.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' GROUP BY month;

[User] Also exclude records where email is NULL.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' AND email IS NOT NULL GROUP BY month;

[User] Sort the results in descending order by passenger_count and limit to the top 6 months.

[Assistant] SELECT date_trunc('month', created_at) AS month, COUNT(*) AS passenger_count FROM transportation.passengers WHERE created_at >= '2021-01-01' AND email IS NOT NULL GROUP BY month ORDER BY passenger_count DESC LIMIT 6;

[User] Show each pair of passengers who share the same loyalty_program_id but have different registration times. Return p1.first_name AS earlier, p2.first_name AS later, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Actually, only include pairs where the earlier registration happened before '2023-01-01'.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.created_at < '2023-01-01';

[User] List each passenger's first_name, last_name along with another passenger's first_name and last_name who share the same loyalty_program_id. Label them as member and peer.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id;

[User] I only want pairs where the member registered before the peer and include their created_at timestamps.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at;

[User] Then sort the result by member_created ascending and peer_created descending.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at
ORDER BY p1.created_at ASC, p2.created_at DESC;

[User] List pairs of passengers where one registered before another, including both their first names, created_at timestamps, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Only include pairs where both passengers are in a loyalty_program and the time difference between their registrations is more than 30 days.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.loyalty_program_id IS NOT NULL
  AND p2.loyalty_program_id IS NOT NULL
  AND p2.created_at - p1.created_at > INTERVAL '30 days';

[User] Now also order the results by the time difference descending and limit to the top 5.

[Assistant]
SELECT p1.first_name AS earlier,
       p2.first_name AS later,
       p1.created_at AS earlier_created,
       p2.created_at AS later_created,
       p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.loyalty_program_id IS NOT NULL
  AND p2.loyalty_program_id IS NOT NULL
  AND p2.created_at - p1.created_at > INTERVAL '30 days'
ORDER BY (p2.created_at - p1.created_at) DESC
LIMIT 5;

[User] List the first and last names of passengers who share the same loyalty_program_id with at least one other passenger.

[Assistant]
SELECT DISTINCT p1.first_name, p1.last_name
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id AND p1.passenger_id <> p2.passenger_id
WHERE p1.loyalty_program_id IS NOT NULL;

[User] Now refine this list to only include passengers who joined after January 1, 2023.

[Assistant]
SELECT DISTINCT p1.first_name, p1.last_name
FROM transportation.passengers p1
JOIN transportation.passengers p2 ON p1.loyalty_program_id = p2.loyalty_program_id AND p1.passenger_id <> p2.passenger_id
WHERE p1.loyalty_program_id IS NOT NULL
  AND p1.created_at >= '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Index 'suppliers'. Mapping: { properties: { supplier_id: { type: 'keyword' }, supplier_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, address: { type: 'text' }, country: { type: 'keyword' }, contact_person: { type: 'text', index: false }, contact_email: { type: 'keyword' }, quality_rating: { type: 'float' }, certified_date: { type: 'date' } } }. Document _id can be supplier_id.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[Assistant] GET suppliers/_doc/{supplier_id}

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

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

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

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

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

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


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
Collection 'assembly_steps'. Document structure: { _id: <ObjectId (or step_id)>, step_id: String, line_id: String (reference), step_number: NumberInt, step_name: String, description: String, standard_duration_hours: Decimal128, required_skill_level: String, workstation: String }. Required: step_id, line_id, step_number, step_name. Index on line_id, step_number.
Collection 'employees'. Document structure: { _id: <ObjectId (or employee_id)>, employee_id: String, first_name: String, last_name: String, job_title: String, skill_certifications: [String], hire_date: ISODate, assigned_line_id: String (reference, optional), employment_status: String, supervisor_employee_id: String (reference, optional) }. Required: employee_id, first_name, last_name, job_title, hire_date, employment_status.

[User] 特定の職種の従業員情報を取得したいです。従業員ID、名前、職種、雇用日を表示してください。

[Assistant]
db.employees.find(
    { job_title: '<specific_job_title>' },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用日が2020年1月1日以降の従業員だけに絞り込むことはできますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') }
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 雇用ステータスが「Active」の従業員だけをさらに条件に加えられますか？

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] スキル認定情報も結果に含めてください。

[Assistant]
db.employees.find(
    {
        job_title: '<specific_job_title>',
        hire_date: { $gte: ISODate('2020-01-01') },
        employment_status: 'Active'
    },
    { employee_id: 1, first_name: 1, last_name: 1, job_title: 1, hire_date: 1, skill_certifications: 1, _id: 0 }
).sort({ hire_date: -1 })

[User] 特定の組み立てラインに関連するすべての手順を取得したいです。ラインIDと手順名、手順番号、必要なスキルレベルを含めてください。

[Assistant]
db.assembly_steps.find(
    { line_id: '<specific_line_id>' },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] さらに、必要なスキルレベルが「Senior Technician」以上の手順だけを表示できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 標準作業時間が3時間以上の手順も条件に追加できますか？

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 }
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 最後に、作業場所が「Workstation_B」の手順だけに絞り込んでください。

[Assistant]
db.assembly_steps.find(
    {
        line_id: '<specific_line_id>',
        required_skill_level: 'Senior Technician',
        standard_duration_hours: { $gte: 3 },
        workstation: 'Workstation_B'
    },
    { step_id: 1, line_id: 1, step_number: 1, step_name: 1, required_skill_level: 1, _id: 0 }
).sort({ step_number: 1 })

[User] 特定の組み立てラインに割り当てられた従業員とそのラインの手順情報を取得したいです。従業員ID、名前、職種と手順名、手順番号を含めてください。

[Assistant]
db.employees.aggregate([
    { $match: { assigned_line_id: '<specific_line_id>' } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 従業員の雇用ステータスが「Active」のデータだけに絞り込むことはできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 手順の必要なスキルレベルが「Junior Technician」以上のものだけを表示するようにできますか？

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { 'steps.step_number': 1 } }
])

[User] 最後に、従業員の雇用日も結果に含めて、雇用日順に並べ替えてください。

[Assistant]
db.employees.aggregate([
    { $match: {
        assigned_line_id: '<specific_line_id>',
        employment_status: 'Active'
    } },
    { $lookup: {
        from: 'assembly_steps',
        localField: 'assigned_line_id',
        foreignField: 'line_id',
        as: 'steps'
    } },
    { $unwind: '$steps' },
    { $match: { 'steps.required_skill_level': { $in: ['Junior Technician', 'Senior Technician'] } } },
    { $project: {
        employee_id: 1,
        first_name: 1,
        last_name: 1,
        job_title: 1,
        hire_date: 1,
        'steps.step_name': 1,
        'steps.step_number': 1,
        _id: 0
    } },
    { $sort: { hire_date: -1, 'steps.step_number': 1 } }
])


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.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )

[User] Show me the names, founding dates, and websites of all law firms whose name contains the word 'Legal' and were founded after the year 2005. Sort the results by their founding date.

[Assistant] SELECT firm_name, founded_date, website FROM legal_services.law_firms WHERE firm_name LIKE '%Legal%' AND founded_date > '2005-12-31' ORDER BY founded_date ASC;

[User] List pairs of law firms that are located at the same address. Display the names of both firms and the shared address, ensuring the address is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL;

[User] Only show pairs where both firms were founded before 2020.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.address
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.address = t2.address
WHERE
  t1.firm_id < t2.firm_id AND t1.address IS NOT NULL AND EXTRACT(YEAR FROM t1.founded_date) < 2020 AND EXTRACT(YEAR FROM t2.founded_date) < 2020;

[User] Show me the count of law firms grouped by the year they were founded. Include the founding year and the number of firms.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL
GROUP BY
  founding_year;

[User] Only include years where the firm count is greater than 3.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3;

[User] Also, restrict this count to only include firms that have a website listed.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL AND website IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3;

[User] Order the results by the founding year in ascending order.

[Assistant]
SELECT
  EXTRACT(YEAR FROM founded_date) AS founding_year,
  COUNT(firm_id) AS firm_count
FROM legal_services.law_firms
WHERE
  founded_date IS NOT NULL AND website IS NOT NULL
GROUP BY
  founding_year
HAVING
  COUNT(firm_id) > 3
ORDER BY
  founding_year ASC;

[User] Find all law firms that share the same address, listing each address and the two firm names.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id;

[User] Actually, only show addresses containing the word 'Street'.

[Assistant] SELECT f1.address, f1.firm_name AS firm1, f2.firm_name AS firm2 FROM law_firms f1 JOIN law_firms f2 ON f1.address = f2.address AND f1.firm_id < f2.firm_id WHERE f1.address LIKE '%Street%';

[User] List all pairs of law firms founded in the same year, showing the two firm names and the shared year.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id <> f2.firm_id;

[User] Actually, only include years after 2000.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id <> f2.firm_id WHERE EXTRACT(YEAR FROM f1.founded_date) > 2000;

[User] And ensure each pair only appears once.

[Assistant] SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS year FROM law_firms f1 JOIN law_firms f2 ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date) AND f1.firm_id < f2.firm_id WHERE EXTRACT(YEAR FROM f1.founded_date) > 2000;

[User] Find pairs of law firms that share the same managing partner. List the names of both firms and the managing partner ID, but only show pairs where the managing partner ID is not null.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id IS NOT NULL;

[User] Refine this to only include pairs where the managing partner ID starts with 'MPG_'.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id LIKE 'MPG_%';

[User] Further filter to only show pairs where both firms were founded after 2015.

[Assistant]
SELECT
  t1.firm_name AS firm1_name,
  t2.firm_name AS firm2_name,
  t1.managing_partner_id
FROM legal_services.law_firms AS t1
INNER JOIN legal_services.law_firms AS t2
  ON t1.managing_partner_id = t2.managing_partner_id
WHERE
  t1.firm_id < t2.firm_id AND t1.managing_partner_id LIKE 'MPG_%' AND EXTRACT(YEAR FROM t1.founded_date) > 2015 AND EXTRACT(YEAR FROM t2.founded_date) > 2015;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

[User] List all pairs of hashtags created on the same calendar date, showing both tag names and the creation date.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Also, only include each pair once by enforcing the first tag_name to be alphabetically before the second.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.tag_name < h2.tag_name;

[User] How many hashtags were created in each month of 2024?

[Assistant]
SELECT date_trunc('month', created_at) AS month, COUNT(*) AS count
FROM social_media.hashtags
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;

[User] List all pairs of hashtags that were created on the same date. Show both tag names and the creation date.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id;

[User] Actually, only include pairs where both tag names start with the letter 'S'.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id
WHERE a.tag_name LIKE 'S%'
  AND b.tag_name LIKE 'S%';

[User] Count the total number of hashtags.

[Assistant] SELECT COUNT(*) FROM social_media.hashtags;

[User] Show me the hashtag IDs and their names.

[Assistant] SELECT hashtag_id, tag_name FROM social_media.hashtags;

[User] I also want to see when each hashtag was created.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags;

[User] Filter the list to only show hashtags whose name starts with the letter 'S'.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE tag_name LIKE 'S%';

[User] I need all pairs of hashtags that start with the same first two letters. Show both tag names.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Please filter these pairs to include only those created in the same year.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND EXTRACT(YEAR FROM h1.created_at) = EXTRACT(YEAR FROM h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Now also include the year in the output.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, EXTRACT(YEAR FROM h1.created_at) AS year
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND EXTRACT(YEAR FROM h1.created_at) = EXTRACT(YEAR FROM h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// db.createCollection('stations')
// Optional: Add unique index: db.stations.createIndex({ station_id: 1 }, { unique: true })
{
  _id: ObjectId(), // Auto-generated MongoDB ID
  station_id: "station_xyz", // String (unique identifier, corresponds to SQL PK)
  station_name: "Grand Central Terminal", // String
  city: "New York", // String
  state_province: "NY", // String
  country_code: "USA", // String
  address: "89 E 42nd St, New York, NY 10017", // String
  timezone: "America/New_York", // String
  number_of_platforms: 44, // Int32
  created_at: ISODate("2023-01-15T10:00:00Z"), // Date
  last_updated_at: ISODate("2023-10-28T15:30:00Z") // Date
}
// db.createCollection('trains')
// Optional: db.trains.createIndex({ train_id: 1 }, { unique: true })
// Optional: db.trains.createIndex({ train_number: 1 }, { unique: true })
{
  _id: ObjectId(),
  train_id: "train_789", // String (unique)
  train_number: "Acela 2151", // String (unique)
  model: "Siemens Velaro", // String
  manufacturer: "Siemens", // String
  year_manufactured: 2010, // Int32
  capacity: 304, // Int32
  status: "Active", // String ('Active', 'Maintenance', 'Retired')
  last_maintenance_date: ISODate("2023-09-15"), // Date (Date part only relevant)
  next_maintenance_date: ISODate("2024-03-15") // Date (Date part only relevant)
}
// db.createCollection('bookings')
// Optional: db.bookings.createIndex({ booking_id: 1 }, { unique: true })
// Optional: db.bookings.createIndex({ passenger_id: 1 })
// Optional: db.bookings.createIndex({ schedule_id: 1 })
{
  _id: ObjectId(),
  booking_id: "book_zyx", // String (unique)
  passenger_id: "pass_pqr", // String (references passengers.passenger_id)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  booking_datetime: ISODate("2024-04-15T14:30:00Z"), // Date
  status: "Confirmed", // String ('Confirmed', 'Cancelled', 'Pending')
  total_price: 150.75, // Decimal128 or Double
  currency_code: "USD", // String
  special_requests: "Wheelchair assistance required at origin" // String
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}

[User] Can you help me count the total number of active staff members in the database?

[Assistant] db.staff.countDocuments({ is_active: true });

[User] Can you assist me in finding all staff members assigned to a specific station with station_id 'station_xyz', including the station details and their roles?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            'primary_station_id': 'station_xyz'
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 1
        }
    }
]);

[User] I noticed that some staff might not have a primary station assigned. Can you revise the query to include staff who might be associated with the station in other ways, if possible?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            $or: [
                { 'primary_station_id': 'station_xyz' },
                { 'primary_station_id': null }
            ]
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 1
        }
    }
]);

[User] Can you help me retrieve the details of all bookings for a specific station with station_id 'station_xyz', including the associated schedule and passenger information?

[Assistant]
db.bookings.aggregate([
    {
        $lookup: {
            from: 'schedules',
            localField: 'schedule_id',
            foreignField: 'schedule_id',
            as: 'schedule_details'
        }
    },
    {
        $lookup: {
            from: 'passengers',
            localField: 'passenger_id',
            foreignField: 'passenger_id',
            as: 'passenger_details'
        }
    },
    {
        $lookup: {
            from: 'stations',
            localField: 'schedule_details.origin_station_id',
            foreignField: 'station_id',
            as: 'origin_station'
        }
    },
    {
        $match: {
            'origin_station.station_id': 'station_xyz'
        }
    },
    {
        $project: {
            booking_id: 1,
            booking_datetime: 1,
            status: 1,
            total_price: 1,
            'schedule_details.schedule_id': 1,
            'schedule_details.departure_datetime': 1,
            'passenger_details.first_name': 1,
            'passenger_details.last_name': 1,
            'origin_station.station_name': 1
        }
    }
]);

[User] Can you modify the query to include only bookings with a status of 'Pending'?

[Assistant]
db.bookings.aggregate([
    {
        $lookup: {
            from: 'schedules',
            localField: 'schedule_id',
            foreignField: 'schedule_id',
            as: 'schedule_details'
        }
    },
    {
        $lookup: {
            from: 'passengers',
            localField: 'passenger_id',
            foreignField: 'passenger_id',
            as: 'passenger_details'
        }
    },
    {
        $lookup: {
            from: 'stations',
            localField: 'schedule_details.origin_station_id',
            foreignField: 'station_id',
            as: 'origin_station'
        }
    },
    {
        $match: {
            'origin_station.station_id': 'station_xyz',
            status: 'Pending'
        }
    },
    {
        $project: {
            booking_id: 1,
            booking_datetime: 1,
            status: 1,
            total_price: 1,
            'schedule_details.schedule_id': 1,
            'schedule_details.departure_datetime': 1,
            'passenger_details.first_name': 1,
            'passenger_details.last_name': 1,
            'origin_station.station_name': 1
        }
    }
]);

[User] Can you help me get the total number of operational platforms across all stations?

[Assistant] db.platforms.countDocuments({ status: 'Operational' });


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
Use Hashes. Key pattern: 'inv:<inventory_record_id>'. Example: HSET inv:INVREC500 component_id "component:WINGBOLT" quantity 5000 location_warehouse "WH3" batch_number "BCH778899" ... Consider Sorted Set by expiry date: ZADD component_expiry:<component_id> <expiry_timestamp> <inventory_record_id>.

[User] Can you help me fetch the inventory records for components stored in a specific warehouse, along with their expiry dates?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter this to show only records for a specific component ID?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] What if I want to exclude records with quantities below a certain threshold, like 100?

[Assistant]
HGETALL inv:<inventory_record_id>
ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES
# Note: Filtering by quantity would require additional scripting or client-side processing as Redis does not support direct filtering on hash field values.

[User] Can you also sort the results by expiry date in descending order?

[Assistant]
HGETALL inv:<inventory_record_id>
ZREVRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you help me retrieve the inventory details for a specific component ID, including the quantity and warehouse location?

[Assistant] HGETALL inv:<inventory_record_id>

[User] Can you also include the batch number for that inventory record?

[Assistant] HGETALL inv:<inventory_record_id>

[User] If I want to check the expiry date for this component, how can I retrieve that information?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES

[User] Can you filter the results to show only inventory records with an expiry date after a specific timestamp?

[Assistant] ZRANGEBYSCORE component_expiry:<component_id> <specific_timestamp> +inf WITHSCORES

[User] I need to get the inventory quantity and location for a specific batch number. Can you help with that?

[Assistant] HGETALL inv:<inventory_record_id>

[User] Can you also show me the component ID associated with this batch?

[Assistant] HGETALL inv:<inventory_record_id>

[User] If I want to retrieve multiple inventory records for the same component ID, how can I do that?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1

[User] Can you sort those records by expiry date in ascending order?

[Assistant] ZRANGE component_expiry:<component_id> 0 -1 WITHSCORES


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )

[User] Show me all transactions along with the related account IDs where the transaction type is 'Transfer'.

[Assistant] SELECT transaction_id, account_id, related_account_id, transaction_type, amount, currency, transaction_date, status FROM financial_services.transactions WHERE transaction_type = 'Transfer';

[User] Further, only include transactions where the currency is 'USD'.

[Assistant] SELECT transaction_id, account_id, related_account_id, transaction_type, amount, currency, transaction_date, status FROM financial_services.transactions WHERE transaction_type = 'Transfer' AND currency = 'USD';

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

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

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

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

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

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

[User] Give me the total transaction amount and the total count of transactions per day for each currency.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency;

[User] Exclude days where the summed amount is less than 50000.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000;

[User] Sort the results by the total_amount descending and limit to the top 5 records.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000
ORDER BY total_amount DESC
LIMIT 5;

[User] I want to find pairs of transactions where one transaction’s related_account_id matches the other’s account_id, indicating reciprocal transfers between accounts.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id;

[User] Actually, limit these transactions to those that occurred in the last 90 days.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id
WHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days';

[User] And make sure both transactions use the same currency.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id
WHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
  AND t1.currency = t2.currency;

[User] Finally, order the output by the outgoing transaction date descending.

[Assistant]
SELECT t1.transaction_id AS outgoing_txn, t2.transaction_id AS incoming_txn, t1.account_id, t1.related_account_id, t1.transaction_date AS outgoing_date, t2.transaction_date AS incoming_date, t1.currency
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.related_account_id = t2.account_id
 AND t2.related_account_id = t1.account_id
WHERE t1.transaction_date >= CURRENT_DATE - INTERVAL '90 days'
  AND t1.currency = t2.currency
ORDER BY t1.transaction_date DESC;

[User] I want to see the total sum of transaction amounts and their average amount for each transaction_type along with the total number of transactions, grouped by currency.

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions GROUP BY transaction_type, currency;

[User] Can you filter out transactions where the status is not 'SUCCESSFUL' or 'PENDING'?

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions WHERE status IN ('SUCCESSFUL', 'PENDING') GROUP BY transaction_type, currency;

[User] Also, show only the results where the total_amount is greater than 10000.

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions WHERE status IN ('SUCCESSFUL', 'PENDING') GROUP BY transaction_type, currency HAVING SUM(amount) > 10000;

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

[Assistant] SELECT transaction_type, currency, COUNT(*) AS total_transactions, SUM(amount) AS total_amount, AVG(amount) AS average_amount FROM financial_services.transactions WHERE status IN ('SUCCESSFUL', 'PENDING') GROUP BY transaction_type, currency HAVING SUM(amount) > 10000 ORDER BY average_amount ASC;

[User] Show the total incoming and outgoing amounts for each account_id, along with the number of transactions for each type (incoming and outgoing). An incoming transaction is when the account_id appears as related_account_id.

[Assistant] SELECT account_id, SUM(CASE WHEN related_account_id IS NOT NULL THEN amount ELSE 0 END) AS outgoing_amount, COUNT(CASE WHEN related_account_id IS NOT NULL THEN 1 END) AS outgoing_transactions, SUM(CASE WHEN account_id IN (SELECT DISTINCT related_account_id FROM financial_services.transactions WHERE related_account_id IS NOT NULL) THEN 0 ELSE amount END) AS incoming_amount, COUNT(CASE WHEN account_id IN (SELECT DISTINCT related_account_id FROM financial_services.transactions WHERE related_account_id IS NOT NULL) THEN NULL ELSE 1 END) AS incoming_transactions FROM financial_services.transactions GROUP BY account_id;

[User] The query did not give the correct incoming transactions. Please show incoming amounts where the account_id is equal to related_account_id.

[Assistant] SELECT account_id, SUM(CASE WHEN account_id = related_account_id THEN amount ELSE 0 END) AS incoming_amount, COUNT(CASE WHEN account_id = related_account_id THEN 1 END) AS incoming_transactions, SUM(CASE WHEN account_id <> related_account_id THEN amount ELSE 0 END) AS outgoing_amount, COUNT(CASE WHEN account_id <> related_account_id THEN 1 END) AS outgoing_transactions FROM financial_services.transactions GROUP BY account_id;

[User] Now, show only accounts with more than 5 incoming transactions.

[Assistant] SELECT account_id, SUM(CASE WHEN account_id = related_account_id THEN amount ELSE 0 END) AS incoming_amount, COUNT(CASE WHEN account_id = related_account_id THEN 1 END) AS incoming_transactions, SUM(CASE WHEN account_id <> related_account_id THEN amount ELSE 0 END) AS outgoing_amount, COUNT(CASE WHEN account_id <> related_account_id THEN 1 END) AS outgoing_transactions FROM financial_services.transactions GROUP BY account_id HAVING COUNT(CASE WHEN account_id = related_account_id THEN 1 END) > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] Show me all service orders for spa services in the last month, including the guest name and staff who delivered the service.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month';

[User] Now, include only orders with a total price over $100.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100;

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

[Assistant] SELECT so.order_id, g.first_name, g.last_name, p.property_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id JOIN hospitality_technology.properties p ON so.property_id = p.property_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100;

[User] Actually, I need to see the reservation ID and check-in date for these orders too, and order by total price in descending order.

[Assistant] SELECT so.order_id, g.first_name, g.last_name, p.property_name, s.service_name, st.first_name AS staff_first_name, st.last_name AS staff_last_name, r.reservation_id, r.check_in_date, so.order_timestamp, so.total_price FROM hospitality_technology.service_orders so JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id JOIN hospitality_technology.services s ON so.service_id = s.service_id JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id JOIN hospitality_technology.properties p ON so.property_id = p.property_id JOIN hospitality_technology.reservations r ON so.reservation_id = r.reservation_id WHERE s.category = 'spa' AND so.order_timestamp >= NOW() - INTERVAL '1 month' AND so.total_price > 100 ORDER BY so.total_price DESC;

[User] Show me all staff members along with their positions and the names of the properties they work at.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.position, p.property_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id;

[User] Only include staff who are not currently active.

[Assistant]
SELECT s.staff_id, s.first_name, s.last_name, s.position, p.property_name
FROM hospitality_technology.staff s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_active = FALSE;

[User] For each reservation, show the guest's first and last name, the property name, and the names of all services ordered during that reservation.

[Assistant]
SELECT r.reservation_id, g.first_name, g.last_name, p.property_name, s.service_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id
JOIN hospitality_technology.staff g ON r.guest_id = g.staff_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id;

[User] Only include reservations where at least 3 different services were ordered, and sort by the guest's last name ascending.

[Assistant]
SELECT r.reservation_id, g.first_name, g.last_name, p.property_name, GROUP_CONCAT(DISTINCT s.service_name) AS services_ordered
FROM hospitality_technology.reservations r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON r.reservation_id = so.reservation_id
JOIN hospitality_technology.staff g ON r.guest_id = g.staff_id
JOIN hospitality_technology.services s ON so.service_id = s.service_id
GROUP BY r.reservation_id, g.first_name, g.last_name, p.property_name
HAVING COUNT(DISTINCT s.service_id) >= 3
ORDER BY g.last_name ASC;

[User] For each room, list the room number, property name, and the type name of the room.

[Assistant]
SELECT r.room_number, p.property_name, rt.type_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id;

[User] Only include rooms located on floor 1 or 2 with the feature 'Sea View'.

[Assistant]
SELECT r.room_number, p.property_name, rt.type_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.floor IN (1, 2) AND r.features ILIKE '%Sea View%';

[User] The SQL failed because 'ILIKE' is not supported. Please replace it with an alternative.

[Assistant]
SELECT r.room_number, p.property_name, rt.type_name
FROM hospitality_technology.rooms r
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.floor IN (1, 2) AND LOWER(r.features) LIKE '%sea view%';

[User] Show me the count of rooms by status.

[Assistant]
SELECT status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY status;

[User] Actually, I need that breakdown by property as well.

[Assistant]
SELECT property_id,
       status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY property_id, status
ORDER BY property_id, status;

[User] Get me a list of all public reviews along with the guest's full name and the staff member who responded, including the overall rating and review date.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE;

[User] Filter those to only include reviews with an overall rating above 4.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE
  AND rev.rating_overall > 4;

[User] Also sort the results by review_date in ascending order.

[Assistant]
SELECT rev.review_id,
       g.first_name || ' ' || g.last_name AS guest_name,
       rev.rating_overall,
       rev.review_date,
       s.first_name || ' ' || s.last_name AS responder_name
FROM hospitality_technology.reviews rev
LEFT JOIN hospitality_technology.guests g ON rev.guest_id = g.guest_id
LEFT JOIN hospitality_technology.staff s ON rev.response_staff_id = s.staff_id
WHERE rev.is_public = TRUE
  AND rev.rating_overall > 4
ORDER BY rev.review_date ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )

[User] Count the number of logs for each action type.

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

[User] For each user, retrieve their most recent log entry, including the action and timestamp.

[Assistant] SELECT l.user_id, l.action, l.logged_at FROM trading_platform.logs l JOIN (SELECT user_id, MAX(logged_at) AS max_time FROM trading_platform.logs GROUP BY user_id) m ON l.user_id = m.user_id AND l.logged_at = m.max_time;

[User] Exclude any logs where the action contains the word 'error'.

[Assistant] SELECT l.user_id, l.action, l.logged_at FROM trading_platform.logs l JOIN (SELECT user_id, MAX(logged_at) AS max_time FROM trading_platform.logs GROUP BY user_id) m ON l.user_id = m.user_id AND l.logged_at = m.max_time WHERE l.action NOT ILIKE '%error%';

[User] Count the number of logs for each distinct action type.

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

[User] Get the total number of logs per user for July 2024.

[Assistant]
SELECT user_id,
       COUNT(*) AS log_count
FROM trading_platform.logs
WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
GROUP BY user_id;

[User] Only include users who have at least 20 logs in that period.

[Assistant]
SELECT user_id,
       COUNT(*) AS log_count
FROM trading_platform.logs
WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
GROUP BY user_id
HAVING COUNT(*) >= 20;

[User] Also include the earliest log date for each of those users.

[Assistant]
SELECT t.user_id,
       t.log_count,
       e.first_log
FROM (
    SELECT user_id,
           COUNT(*) AS log_count
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
    HAVING COUNT(*) >= 20
) t
JOIN (
    SELECT user_id,
           MIN(logged_at) AS first_log
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
) e ON t.user_id = e.user_id;

[User] Sort by log_count descending and limit to top 5 users.

[Assistant]
SELECT t.user_id,
       t.log_count,
       e.first_log
FROM (
    SELECT user_id,
           COUNT(*) AS log_count
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
    HAVING COUNT(*) >= 20
) t
JOIN (
    SELECT user_id,
           MIN(logged_at) AS first_log
    FROM trading_platform.logs
    WHERE logged_at BETWEEN '2024-07-01' AND '2024-07-31'
    GROUP BY user_id
) e ON t.user_id = e.user_id
ORDER BY t.log_count DESC
LIMIT 5;

[User] For each user, list all the distinct actions they have performed along with the count of each action.

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

[User] Now, only show users who have performed more than 5 distinct actions.

[Assistant] SELECT user_id FROM trading_platform.logs GROUP BY user_id HAVING COUNT(DISTINCT action) > 5 ORDER BY user_id;

[User] Show the earliest and latest timestamp recorded in the logs table.

[Assistant] SELECT MIN(logged_at), MAX(logged_at) FROM trading_platform.logs;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )

[User] List the order ID, type, and quantity for all orders placed using the wallet with ID 'wallet123'.

[Assistant] SELECT order_id, order_type, quantity FROM orders WHERE wallet_id = 'wallet123'

[User] Also include the creation date of the wallet that placed the order.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T1.wallet_id = 'wallet123'

[User] Actually, ignore the specific wallet ID. Show the same information for all orders, but only include orders placed using wallets created before '2023-12-31'.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at < '2023-12-31'

[User] Filter that list further to only show 'sell' orders.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at < '2023-12-31' AND T1.order_type = 'sell'

[User] Show the number of wallets created each month in 2024, showing the year and month.

[Assistant] SELECT EXTRACT(YEAR FROM created_at) AS year, EXTRACT(MONTH FROM created_at) AS month, COUNT(*) FROM wallets WHERE EXTRACT(YEAR FROM created_at) = 2024 GROUP BY 1, 2 ORDER BY 1, 2

[User] List all orders, showing order ID, type, quantity, and price, that were placed using a wallet created after '2024-01-01'.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T1.price FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at > '2024-01-01'

[User] From that list, only show orders with 'completed' status.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T1.price FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at > '2024-01-01' AND T1.status = 'completed'

[User] Count the number of orders in each status.

[Assistant]
SELECT status, COUNT(*) AS order_count
FROM trading_platform.orders
GROUP BY status;

[User] For each user, calculate the total value of 'buy' and 'sell' orders (quantity * price).

[Assistant]
SELECT b.user_id,
       b.total_buy_value,
       s.total_sell_value
FROM (
  SELECT user_id,
         SUM(quantity * price) AS total_buy_value
  FROM trading_platform.orders
  WHERE order_type = 'buy'
  GROUP BY user_id
) b
JOIN (
  SELECT user_id,
         SUM(quantity * price) AS total_sell_value
  FROM trading_platform.orders
  WHERE order_type = 'sell'
  GROUP BY user_id
) s
  ON b.user_id = s.user_id;

[User] Include users who have only buys or only sells, showing missing values as zero.

[Assistant]
SELECT COALESCE(b.user_id, s.user_id) AS user_id,
       COALESCE(b.total_buy_value, 0) AS total_buy_value,
       COALESCE(s.total_sell_value, 0) AS total_sell_value
FROM (
  SELECT user_id,
         SUM(quantity * price) AS total_buy_value
  FROM trading_platform.orders
  WHERE order_type = 'buy'
  GROUP BY user_id
) b
FULL OUTER JOIN (
  SELECT user_id,
         SUM(quantity * price) AS total_sell_value
  FROM trading_platform.orders
  WHERE order_type = 'sell'
  GROUP BY user_id
) s
  ON b.user_id = s.user_id;

[User] Also add the count of completed orders per user.

[Assistant]
SELECT u.user_id,
       u.total_buy_value,
       u.total_sell_value,
       COALESCE(c.completed_count, 0) AS completed_count
FROM (
  SELECT COALESCE(b.user_id, s.user_id) AS user_id,
         COALESCE(b.total_buy_value, 0) AS total_buy_value,
         COALESCE(s.total_sell_value, 0) AS total_sell_value
  FROM (
    SELECT user_id,
           SUM(quantity * price) AS total_buy_value
    FROM trading_platform.orders
    WHERE order_type = 'buy'
    GROUP BY user_id
  ) b
  FULL OUTER JOIN (
    SELECT user_id,
           SUM(quantity * price) AS total_sell_value
    FROM trading_platform.orders
    WHERE order_type = 'sell'
    GROUP BY user_id
  ) s
    ON b.user_id = s.user_id
) u
LEFT JOIN (
  SELECT user_id,
         COUNT(*) AS completed_count
  FROM trading_platform.orders
  WHERE status = 'completed'
  GROUP BY user_id
) c
  ON u.user_id = c.user_id;

[User] Order results by total_buy_value descending and limit to 10.

[Assistant]
SELECT u.user_id,
       u.total_buy_value,
       u.total_sell_value,
       COALESCE(c.completed_count, 0) AS completed_count
FROM (
  SELECT COALESCE(b.user_id, s.user_id) AS user_id,
         COALESCE(b.total_buy_value, 0) AS total_buy_value,
         COALESCE(s.total_sell_value, 0) AS total_sell_value
  FROM (
    SELECT user_id,
           SUM(quantity * price) AS total_buy_value
    FROM trading_platform.orders
    WHERE order_type = 'buy'
    GROUP BY user_id
  ) b
  FULL OUTER JOIN (
    SELECT user_id,
           SUM(quantity * price) AS total_sell_value
    FROM trading_platform.orders
    WHERE order_type = 'sell'
    GROUP BY user_id
  ) s
    ON b.user_id = s.user_id
) u
LEFT JOIN (
  SELECT user_id,
         COUNT(*) AS completed_count
  FROM trading_platform.orders
  WHERE status = 'completed'
  GROUP BY user_id
) c
  ON u.user_id = c.user_id
ORDER BY u.total_buy_value DESC
LIMIT 10;

[User] Show each order with its previous order timestamp for the same user.

[Assistant]
SELECT o.order_id, o.user_id, o.created_at AS current_time, MAX(prev.created_at) AS previous_time
FROM trading_platform.orders o
LEFT JOIN trading_platform.orders prev
  ON o.user_id = prev.user_id
  AND prev.created_at < o.created_at
GROUP BY o.order_id, o.user_id, o.created_at
ORDER BY o.user_id, o.created_at;

[User] Filter to include only those orders where the gap between current_time and previous_time exceeds one day.

[Assistant]
SELECT *
FROM (
  SELECT o.order_id,
         o.user_id,
         o.created_at AS current_time,
         MAX(prev.created_at) AS previous_time
  FROM trading_platform.orders o
  LEFT JOIN trading_platform.orders prev
    ON o.user_id = prev.user_id
    AND prev.created_at < o.created_at
  GROUP BY o.order_id, o.user_id, o.created_at
) t
WHERE t.current_time - t.previous_time > INTERVAL '1 day'
ORDER BY t.user_id, t.current_time;


System:
You are an expert in writing database language and you can refuse the user's question if the question is not related to the table structure. 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 manufacturing.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, skill_certifications text, hire_date date, assigned_line_id text, employment_status text, supervisor_employee_id text )

[User] What is the total number of vacation days taken by employee with ID 'EMP101' in the past year?

[Assistant] I'm sorry, but I can't provide information on the vacation days taken by an employee as this data is not stored in the current table structure.

[User] What is the current address of the employee with ID 'EMP234'?

[Assistant] I'm sorry, but I can't provide the current address of an employee as this information is not stored in the database table.

[User] What is the reason for the termination of employee with ID 'EMP789'?

[Assistant] I'm sorry, but I can't provide information on the reason for an employee's termination as it is not stored in the current database table.

[User] What is the performance review score for employee with ID 'EMP456' for the last quarter?

[Assistant] I'm sorry, but I can't assist with information about performance review scores as this data is not included in the employees table.

[User] What is the current salary of employee with ID 'EMP123'?

[Assistant] I'm sorry, but I can't provide information about an employee's salary as it is not included in the data available in the 'employees' table.


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 healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )

[User] Show all prescriptions with prescription_id, patient_id, medication_id, quantity_dispensed, and refills_allowed.

[Assistant] SELECT prescription_id, patient_id, medication_id, quantity_dispensed, refills_allowed FROM healthcare.prescriptions;

[User] Filter this list to include only prescriptions where the quantity dispensed is greater than 20 and refills allowed is 0.

[Assistant] SELECT prescription_id, patient_id, medication_id, quantity_dispensed, refills_allowed FROM healthcare.prescriptions WHERE quantity_dispensed > 20 AND refills_allowed = 0;

[User] List appointments including ID, patient ID, doctor ID, time, and duration, where the reason is 'follow-up'.

[Assistant] SELECT appointment_id, patient_id, doctor_id, appointment_time, duration_minutes FROM healthcare.appointments WHERE reason = 'follow-up';

[User] Only show those appointments where the duration is greater than 30 minutes.

[Assistant] SELECT appointment_id, patient_id, doctor_id, appointment_time, duration_minutes FROM healthcare.appointments WHERE reason = 'follow-up' AND duration_minutes > 30;

[User] Also include the doctor's first and last name in the result and sort by appointment time.

[Assistant] SELECT T1.appointment_id, T1.patient_id, T1.doctor_id, T2.first_name, T2.last_name, T1.appointment_time, T1.duration_minutes FROM healthcare.appointments AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id WHERE T1.reason = 'follow-up' AND T1.duration_minutes > 30 ORDER BY T1.appointment_time;

[User] Show me all doctors who have prescribed medications along with the count of prescriptions they've made, ordered by the count in descending order.

[Assistant] SELECT d.doctor_id, d.first_name, d.last_name, COUNT(p.prescription_id) AS prescription_count FROM healthcare.doctors d JOIN healthcare.prescriptions p ON d.doctor_id = p.doctor_id GROUP BY d.doctor_id, d.first_name, d.last_name ORDER BY prescription_count DESC;

[User] Show all doctors whose license number starts with 'MD', including their ID, first name, and last name.

[Assistant] SELECT doctor_id, first_name, last_name FROM healthcare.doctors WHERE license_number LIKE 'MD%';

[User] Now, also include their specialty and phone number in the result.

[Assistant] SELECT doctor_id, first_name, last_name, specialty, phone_number FROM healthcare.doctors WHERE license_number LIKE 'MD%';

[User] Show all diagnoses, including the diagnosis ID, description, diagnosis date, and the full name of the doctor who made the diagnosis.

[Assistant] SELECT T1.diagnosis_id, T1.description, T1.diagnosis_date, T2.first_name, T2.last_name FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id;

[User] Refine this list to only include diagnoses where the diagnosis_date is in the year 2023 and the doctor's specialty is 'Cardiology'.

[Assistant] SELECT T1.diagnosis_id, T1.description, T1.diagnosis_date, T2.first_name, T2.last_name FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id WHERE T2.specialty = 'Cardiology' AND EXTRACT(YEAR FROM T1.diagnosis_date) = 2023;

[User] List the medical record ID and record date for all medical records that are linked to an appointment whose duration was longer than the average duration of all appointments.

[Assistant] SELECT T1.record_id, T1.record_date FROM healthcare.medical_records AS T1 JOIN healthcare.appointments AS T2 ON T1.appointment_id = T2.appointment_id WHERE T2.duration_minutes > (SELECT AVG(duration_minutes) FROM healthcare.appointments);


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[User] Count the number of posts that have a media URL but no textual content.

[Assistant] SELECT COUNT(*) FROM social_media.posts AS T1 WHERE T1.media_url IS NOT NULL AND (T1.content IS NULL OR T1.content = '');


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.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )

[User] List all available services along with the property name where they are offered.

[Assistant]
SELECT s.service_id, s.service_name, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_available = true;

[User] Show me each department in each property, along with the total number of available services and their combined price.

[Assistant] SELECT property_id, department, COUNT(*) AS service_count, SUM(price) AS total_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, department;

[User] Give me a breakdown of available services by unit, with the count of services and the average price, grouped by property.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit;

[User] I only want results where the average price is above 50.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit HAVING AVG(price) > 50;

[User] Actually, also include the department for each unit in the result.

[Assistant] SELECT property_id, unit, department, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit, department HAVING AVG(price) > 50;

[User] List all properties and the count of their available services in the 'Activities' category.

[Assistant] SELECT T2.property_name, COUNT(T1.service_id) AS available_activities_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE AND T1.category = 'Activities' GROUP BY T2.property_id, T2.property_name;

[User] Now, only show properties with more than 3 available 'Activities' services.

[Assistant] SELECT T2.property_name, COUNT(T1.service_id) AS available_activities_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE AND T1.category = 'Activities' GROUP BY T2.property_id, T2.property_name HAVING COUNT(T1.service_id) > 3;

[User] Sort the results by the count of services descending.

[Assistant] SELECT T2.property_name, COUNT(T1.service_id) AS available_activities_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE AND T1.category = 'Activities' GROUP BY T2.property_id, T2.property_name HAVING COUNT(T1.service_id) > 3 ORDER BY available_activities_count DESC;

[User] List all services provided by the property named 'Grand Plaza Hotel' and include their category and price.

[Assistant] SELECT T1.service_name, T1.category, T1.price FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.property_name = 'Grand Plaza Hotel';

[User] Only show available services from the 'Spa' department at 'Grand Plaza Hotel'.

[Assistant] SELECT T1.service_name, T1.category, T1.price FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.property_name = 'Grand Plaza Hotel' AND T1.is_available = TRUE AND T1.department = 'Spa';

[User] For each property, show the property name, average price of available services, and the maximum price of available services.

[Assistant]
SELECT p.property_name,
       AVG(s.price) AS avg_price,
       MAX(s.price) AS max_price
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_available = true
GROUP BY p.property_name;

[User] Actually, I also need the service_name of the highest priced available service per property.

[Assistant]
SELECT t.property_name,
       t.avg_price,
       s_high.service_name AS highest_priced_service,
       t.max_price
FROM (
    SELECT s.property_id,
           p.property_name,
           AVG(s.price) AS avg_price,
           MAX(s.price) AS max_price
    FROM hospitality_technology.services s
    JOIN hospitality_technology.properties p ON s.property_id = p.property_id
    WHERE s.is_available = true
    GROUP BY s.property_id, p.property_name
) t
JOIN hospitality_technology.services s_high
  ON s_high.property_id = t.property_id
 AND s_high.price = t.max_price
 AND s_high.is_available = true;

[User] Now, only include properties where the average price is above 75 and sort the results by avg_price descending.

[Assistant]
SELECT t.property_name,
       t.avg_price,
       s_high.service_name AS highest_priced_service,
       t.max_price
FROM (
    SELECT s.property_id,
           p.property_name,
           AVG(s.price) AS avg_price,
           MAX(s.price) AS max_price
    FROM hospitality_technology.services s
    JOIN hospitality_technology.properties p ON s.property_id = p.property_id
    WHERE s.is_available = true
    GROUP BY s.property_id, p.property_name
    HAVING AVG(s.price) > 75
) t
JOIN hospitality_technology.services s_high
  ON s_high.property_id = t.property_id
 AND s_high.price = t.max_price
 AND s_high.is_available = true
ORDER BY t.avg_price 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.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 )

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

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

[User] Show me product_id, product_name, and base_premium for products created after '2023-01-01'.

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01';

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

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000;

[User] Can you also order the results by base_premium descending and limit to the top 5?

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
ORDER BY base_premium DESC
LIMIT 5;

[User] Now, I need the total number of such products per product_type.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
GROUP BY product_type;

[User] List all pairs of insurance products that share the same product_type but have differing active statuses. Return both product_ids, the product_type, and each is_active flag.

[Assistant]
SELECT p1.product_id AS product_id_1, p2.product_id AS product_id_2, p1.product_type, p1.is_active AS is_active_1, p2.is_active AS is_active_2
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.is_active <> p2.is_active
WHERE p1.product_id < p2.product_id;

[User] Which insurance products have 'comprehensive' in their coverage details? Show the product_id and product_name.

[Assistant] SELECT product_id, product_name FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Can you also add the product_type to the output?

[Assistant] SELECT product_id, product_name, product_type FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Give me the product name and description of all insurance products that have been updated in the last 30 days.

[Assistant] SELECT product_name, description FROM insurance.insurance_products WHERE updated_at >= NOW() - INTERVAL '30 days';

[User] Retrieve the count of active insurance products for each product_type and order the results by the count descending.

[Assistant]
SELECT product_type,
       COUNT(*) AS active_count
FROM insurance.insurance_products
WHERE is_active = TRUE
GROUP BY product_type
ORDER BY active_count DESC;