【问题标题】:Take the distinct values based on the most recent date根据最近的日期获取不同的值
【发布时间】:2021-07-01 09:40:24
【问题描述】:

我正在尝试根据最近的日期获取不同的结果。如果我的 id 字段有小数,那么我希望小数点后的数字被截断。我的 id 字段是 ntext 格式。

输入:

name id date1 date2
a 2 12/25/2020 12/15/2021
b 3R 10/08/2019 11/18/2019
ab 2.0 12/26/2020 12/16/2021
c 4 01/11/2018 10/06/2019
ck 4.4 04/01/2020 04/05/2021
ad 2.999 04/02/2021 04/05/2021

输出:

name id date1 date2
ad 2 04/02/2021 04/05/2021
b 3R 10/08/2019 11/18/2019
ck 4 04/01/2020 04/05/2021

我尝试去除小数点后的所有数字,但没有奏效。

substring('2.2', 0 , charindex('.','2.2'))

编辑:我的 ID 字段也包含字母。

【问题讨论】:

  • 请提供您的完整查询。
  • 我试过了,但我在剥离十进制和非小数 ID 时遇到了困难,而且在获取每个 ID 的最新日期时也遇到了困难。
  • ntext 自 2005 年以来已被弃用。为什么现在使用它? round() function 可以截断 - 如果您可以安全地(可能不太可能)假设您的列包含有效的数值,这似乎是您所需要的。
  • CAST(id as int) 可以帮助您进行转换吗?

标签: sql sql-server


【解决方案1】:

你可以这样做,我假设 id 是十进制或数字类型

select * from 
   (
    select * , ROW_NUMBER() over (partition by id - id % 1 order by date1 desc) rn
    from yourtable
   )
where rn = 1

如果 id 是字符串,则将其转换为 int:

select name,convert(numeric(38, 0), id) id , date1, date2 from 
   (
    select * , ROW_NUMBER() over (partition by convert(numeric(38, 0), id) as int) order by date1 desc) rn
    from yourtable
    where isnumeric(id) = 1
   )
where rn = 1

如果你也想包含非数字:

select name,convert(numeric(38, 0), id) id , date1, date2 from 
   (
    select * , ROW_NUMBER() over (partition by case when isnumeric(id) = 1 then convert(numeric(38, 0), id) else id end order by date1 desc) rn
    from yourtable     
   )
where rn = 1

【讨论】:

  • 嘿,谢谢!但它说“将 nvarchar 值转换为数据类型 int 时转换失败”
  • hmm.. id 列中是否有任何非数值?
  • 有一个类似“G566 006”的id
  • 那么我假设您想过滤掉它们,请参阅我更新的 asnwer
  • 那是另一个问题,根据您的问题,这是解决方案,但如果还有更多问题,您应该将其包含在您的问题中
【解决方案2】:

我建议转换为数字:

select convert(numeric(38, 0), id)

如果您的列中有无效数字,您可能真的想要try_convert()

如果它是一个字符串,您还可以使用字符串函数获取第一个 '.' 之前的所有内容:

select left(id, charindex('.', id + '.') - 1)

注意+ '.'。这样可以防止没有小数点时出现任何错误。

【讨论】:

  • Thx Gordon,这仍然给了我十进制值“988.00”。我想去掉小数点后的尾随值
  • @New_here 。 . .我调整了第二个,但两者都完全按照您的意图工作:dbfiddle.uk/….
猜你喜欢
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多