拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 在where子句中计算年龄

在where子句中计算年龄

白鹭 - 2022-01-26 1966 0 0

users表中我有birth_date列。我只想选择 18 岁以下的用户。

我尝试使用别名

select 
    *, 
    age = case
              when datediff(year, getdate(), birth_date) > 0 
                  then year(getdate()) - year(birth_date) - 1 
                  else year(getdate()) - year(birth_date)
          end 
from 
    users
where 
    age < 18

但显然我不能在哪里使用别名。

所以我尝试使用案例,但它也行不通

select * 
from users 
where 
    case 
        when datediff(year, getdate(), birth_date) > 0 
            then year(getdate()) - year(birth_date) - 1 < 18
            else year(getdate()) - year(birth_date) < 18

在这种情况下我该怎么办?我不想使用存盘程序。

uj5u.com热心网友回复:

利用 cte

WITH cte AS
(
  SELECT *,
      CASE
        WHEN DATEDIFF(year, getdate(), birth_date) > 0 
          THEN year(getdate()) - year(birth_date) - 1
        ELSE year(getdate()) - year(birth_date) 
      END AS age
  FROM users 
)
SELECT *
FROM cte
WHERE age < 18

db<>fiddle 中的演示

uj5u.com热心网友回复:

这样做正确方法是根本不使用DATEDIFF它会不太准确(因为它使用日期边界)并且更慢(它不能使用索引)。

而是DATEADD针对当前日期使用,不要针对列使用函式

SELECT *
FROM dbo.users
WHERE birth_date > DATEADD(year, -18, GETUTCDATE())

db<>小提琴

uj5u.com热心网友回复:

简单用这个!

SELECT * FROM dbo.users WHERE DATEDIFF(day,birth_date,GETDATE()) < 6570

uj5u.com热心网友回复:

我认为您只是在寻找有关如何在列中使用别名/CASE 陈述句的方向?

如果这是正确的,那么你只需要用括号括起来你的别名。

select *
      ,case
           when datediff(year, getdate(), birth_date) > 0 
           then year(getdate()) - year(birth_date) - 1 
           else year(getdate()) - year(birth_date)
       end as age
from users
where age < 18

uj5u.com热心网友回复:

以下是计算闰日和其他复杂性的年龄的一种方法。这将计算 yyyymmdd 整数值的差异,然后除以 10000 以仅评估年份差异。

SELECT *
FROM users
WHERE
    (CAST(FORMAT(GETDATE(), 'yyyyMMdd') AS int) -
     CAST(FORMAT(birth_date, 'yyyyMMdd') AS int)) / 10000 < 18;
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *