SQL查询 - 选择超过特定年龄的客户

时间:2016-01-07 09:55:22

标签: sql oracle

我正在尝试SELECT年龄超过65岁的客户,并且余额超过5000.

我无法弄清楚如何在我的WHERE条款中成功计算出他们的年龄。

这是我的代码:

SELECT 
    Customer.ID, Customer.lastName, Customer.firstName
FROM 
    CUSTOMER
INNER JOIN 
    has ON has.ID = CUSTOMER.ID
INNER JOIN 
    Account ON Account.ACCNUMBER = has.ACCNUMBER
WHERE 
    Account.BALANCE > 5000 
    AND ((DATEDIFF(DAY, CUSTOMER.DATEOFBIRTH, GETDATE()) / 365.25) > 65)
ORDER BY 
    CUSTOMER.LASTNAME;

我哪里错了?

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    Customer.ID, Customer.lastName, Customer.firstName
FROM 
    CUSTOMER
INNER JOIN 
    has ON has.ID = CUSTOMER.ID
INNER JOIN 
    Account ON Account.ACCNUMBER = has.ACCNUMBER
WHERE 
    Account.BALANCE > 5000 
    AND Customer.DateOfBirth <= DATEADD(YEAR, -65, SYSDATETIME()) 
ORDER BY 
    CUSTOMER.LASTNAME;

DATEADD从当前系统日期减去65年(从&#34;今天&#34;),然后选择DateOfBirth之前的所有客户那个截止日期。

答案 1 :(得分:0)

如果您使用的是SQL Server数据库,则可以使用此WHERE子句:

WHERE 
    Account.balance > 5000
    AND Customer.dateofbirth <= DATEADD(yy, -65, GETDATE())

答案 2 :(得分:0)

年龄是最简单的部分,只需在DateOfBirth中添加65年并检查它是否已过去。 您的查询具有可疑的内部联接。这一切都是1对1吗?你会知道它的细节,但至少我会把那部分写成一个存在的查询:

SELECT  ID, lastName, firstName
FROM    CUSTOMER
WHERE   DATEADD(YEAR, 65, DATEOFBIRTH) < getdate() AND
        EXISTS ( SELECT *
                 FROM   has
                 INNER JOIN Account ON Account.ACCNUMBER = has.ACCNUMBER
                 WHERE  has.ID = CUSTOMER.ID AND
                        Account.BALANCE > 5000 )
ORDER BY LASTNAME;

哦,你没有使用MS SQL服务器而是Oracle,希望你在你的问题中指明:

SELECT  ID, lastName, firstName
FROM    CUSTOMER
WHERE   ADD_MONTHS(DATEOFBIRTH, 65*12) < SYSDATE AND
        EXISTS ( SELECT *
                 FROM   has
                 INNER JOIN Account ON Account.ACCNUMBER = has.ACCNUMBER
                 WHERE  has.ID = CUSTOMER.ID AND
                        Account.BALANCE > 5000 )
ORDER BY LASTNAME;