SQL求助
sql吧
全部回复
仅看楼主
level 1
Visorwhatever 楼主
我有一个表单,是id和日期,想要求得每个id对应的最小日期。
规则如下:
先对比年,取最小年
同年,对比月,取最小月(只有年,保留最小年展示)
同月,对比日,取最小日(只有X年X月,保留最小X年X月展示)
仅有为空的日期保留空展示。
希望大神给与指点~~
id dtc (希望的取值)
abc 2018-01-12
abc 2015 √
abc
abc 2017-05
def √
ghi 2019
ghi 2019-06 √
jkl 2016-03
jkl 2016-03-10 √
2021年07月07日 08点07分 1
level 1
Visorwhatever 楼主
2021年07月07日 08点07分 2
level 1
分别截取年 月 日 字符串,如果为空 分别返回 年9999 月12 日 31 ,合并截取的三个字符串转化为日期格式后,再进行比较
2021年07月08日 02点07分 3
level 8
要先清洗数据才行
select id,日期,
left (日期,4) 年,
case len(日期)-len(replace(日期, '-', '')) when 1 then right(日期,2)
when 2 then left( right (日期,5 ) ,2)else '13' end 月,
case len(日期)-len(replace(日期, '-', '')) when 2 then right(日期,2)
else '32' end 日
into #temp2
from 表
where 日期<>''
select id,日期 from #temp2 a
where 日期= ( select top 1 日期 from #temp2 where id=a.id order by 年,月,日)
UNION ALL
select * from 表 a
where (select count(1) from 表 where id=a.id and 日期<>'')=0
and 日期=''
2021年07月10日 02点07分 4
1