选择客户的第一份合同以计算当时COUNT岁的年龄?

时间:2019-09-26 06:56:02

标签: sql postgresql

我正尝试生成多年(例如2000年至2019年)的客户摘要。

为此,我想列出每个年龄段的客户数量,并试图计算每个客户从我们那里收到的第一份合同起的年龄。

我在弄清楚如何获取{DATE_I_NEED}

时遇到了麻烦

我尝试了MIN(contract.contract_received),但它没有让我“嵌套聚合函数”。

SELECT
    COUNT(DISTINCT customer.id) "customers",
    COUNT(DISTINCT CASE WHEN customer.form_of_address = 'Mr.' THEN customer.id END) "male",
    COUNT(DISTINCT CASE WHEN customer.form_of_address = 'Mr.'
        AND EXTRACT(YEAR FROM AGE({DATE_I_NEED}, customer.day_of_birth)) BETWEEN 1 AND 24
        THEN customer.id END) "male_1_24"
FROM contract
INNER JOIN customer ON contract.customer = customer.id
WHERE contract.partner = '123'
AND contract.archived = false

样本数据:

contract.received | customer.id | customer.form_of_address | customer.day_of_birth
  '2018-06-13'          12345               'Mr.'                 '1998-07-27'
  '2014-06-13'          12345               'Mr.'                 '1998-07-27'

^计算年龄需要从2014年开始

预期输出:

customers | male | male_1_24
   300       161       27

1 个答案:

答案 0 :(得分:0)

我想您可以先获取最低的contract_received,然后再将customer表加入其中。还可以假设您已经具有一个年龄函数,该函数具有2个参数来计算年龄-

SELECT
    COUNT(DISTINCT customer.id) "customers",
    COUNT(DISTINCT CASE WHEN customer.form_of_address = 'Mr.' THEN customer.id END) "male",
    COUNT(DISTINCT CASE WHEN customer.form_of_address = 'Mr.'
        AND EXTRACT(YEAR FROM AGE(contract_received, customer.day_of_birth)) BETWEEN 1 AND 24
        THEN customer.id END) "male_1_24"
FROM (SELECT customer, partner, archived, MIN(contract_received) contract_received
      FROM contract
      GROUP BY customer, partner, archived) c
INNER JOIN customer ON c.customer = customer.id
WHERE c.partner = '123'
AND c.archived = 'false'