前幾天去面試,面試官問到了一道題,如何找到7天內需要過生日的記錄,一時蒙住了,看來這兩年來一直做管理,資料庫基本的東西真是丟掉了不少,非常慚愧,導致後面的面試也砸了。
回來一想,這個問題其實很簡單,關鍵的一點就是找到當前日期和生日的月、日之間的差距在7天內的記錄,有點繞的地方是記錄的年份哪年的都有,怎麼處理這個年是個小技巧,繞過了這點其他的很簡單。
其實年的處理可以找到和現在的年份的差異,給記錄的年份增加這個差異;或者構造乙個當前年+記錄月+記錄日的日期進行比較。
**如下:1--
建立測試庫
2create
database mytempdb3go
4use mytempdb5go
6--建立測試表
7create
table t1
8 (9 id int
identity(1,1),
10 dbirth datetime
11 )
12go
1314
--select * from t1
15--
插入測試資料
16insert
into t1
17select
'2011-2-28
'union
all18
select
'2001-3-2
'union
all19
select
'2011-3-7'20
21--
方法二22
select
*,convert(datetime,convert(nvarchar(4),year(getdate()))+'-
'+convert(nvarchar(4),month(dbirth))+'-
'+convert(nvarchar(4),day(dbirth))) as newbirth
23from t1
24where
convert(datetime,convert(nvarchar(4),year(getdate()))+'-
'+convert(nvarchar(4),month(dbirth))+'-
'+convert(nvarchar(4),day(dbirth))) >=
getdate()
25and
convert(datetime,convert(nvarchar(4),year(getdate()))+'-
'+convert(nvarchar(4),month(dbirth))+'-
'+convert(nvarchar(4),day(dbirth))) <=
getdate() +726
27--
方法一28
select
*from t1
29where
dateadd(year,year(getdate())-
year(dbirth),dbirth)
30between
convert(varchar(10),getdate(),120)
31and
convert(varchar(10),getdate()+
7,120)
,當初怎麼沒想到啊,看來得積攢點這些原先玩的東西,難道自己老了?
返回未來30天內將要過生日的客戶的sql
建立測試環境 create table test idint,birthdayvarchar 10 插入資料 insert test values 1,1981 12 26 insert test values 2,1977 02 26 insert test values 3,1978 07 05...
sql 統計7天內 每天的總數量
說到統計,首先想到 group by 7天之內,資料庫資料的時間 2020 04 22 18 27 29.000 這樣肯定不行,那就格式化時間 select convert varchar 100 getdate 23 2020 08 03 這樣就好統計了 然後在計算7天之前的方法 select c...
SQL 查詢今天 昨天 7天內 30天的資料
今天的所有資料 select from 表名 where datediff dd,datetime型別字段,getdate 0 昨天的所有資料 select from 表名 where datediff dd,datetime型別字段,getdate 1 7天內的所有資料 select from 表...