【问题标题】:Calculate integer sort index column from column consisting of numbers and alphanumeric values从由数字和字母数字值组成的列计算整数排序索引列
【发布时间】:2022-11-02 19:44:00
【问题描述】:

我有一个包含以下数据的表,我需要为 TSQL 中的每一行计算一个排序索引(整数)

type code
Fruit 030
Fruit 040
Fruit Banana
Fruit Apple 1
Fruit Apple 2
Soda 050
Soda 1
Soda 054
Soda Sprite
Soda Fanta

下面的 sort_index 列应按类型(每种类型从 1 开始)和可解析整数代码始终优先于字母数字代码的代码计算:

type code sort_index
Fruit 030 1
Fruit 040 2
Fruit Apple 1 3
Fruit Apple 2 4
Fruit Banana 5
Soda 1 1
Soda 050 2
Soda 054 3
Soda Fanta 4
Soda Sprite 5

任何帮助将不胜感激。

【问题讨论】:

  • 数据/规则太乱了。在将数据导入 SQL Server 之前,您应该定义 sort_index
  • 不幸的是,我真的无法做到这一点。在我发布这个问题后,我找到了答案。您可以在下面查看它 - 也许它会使问题更有意义。

标签: sql tsql


【解决方案1】:

设法找到我搜索的答案。

使用 row_number() 根据条件生成整数行号。

分区依据重置每种类型的行号。

按可解析值对行号进行排序。对于不可解析的值,我们使用最高整数值,确保它们始终高于最高可解析值。最后按代码排序以使不可解析的值按字母顺序排序。

SELECT
[type],
[code],
row_number() OVER (PARTITION BY [type] ORDER BY CASE WHEN try_parse(code AS INT) IS NOT NULL THEN CAST(code AS INT) ELSE 2147483647 END, code) AS [sort_index]
FROM
dbo.test_table

【讨论】:

  • 更好的答案提供了一些解释,而不仅仅是解决手头问题的代码。也就是说,OP 应该accept and/or upvote 这个答案。 ;-)
【解决方案2】:

尝试这个

ROW_NUMBER() over (PARTITION BY code Order by type) as sort_index

【讨论】:

  • dbfiddle 说这不是 OP 所要求的。
猜你喜欢
  • 2014-05-05
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 2018-07-29
  • 2021-06-25
  • 1970-01-01
相关资源
最近更新 更多