在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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/406356.html
標籤:
上一篇:在插入(SQL)中使用相同的值
