0

我在 SQL 列中有以下数据。列类型为字符串。当我从数据库中查询这些数据时,我更愿意对其进行排序,但我想在 SQL 查询完成后,它可以用一些 Ruby 魔法来组织。还有其他列被拉出,所以这只是需要排序的列之一。

Expenses
$3500/MONTH
$1,000.00
STANDARD CONTRACTOR
$5,000.00

数据不能更改,必须存储在同一列中(上面的示例只是测试数据)。

我想通过增加数量然后增加其余(字符串)值来组织数据。预期的结果应该是:

$1,000.00
$5,000.00
$3500/MONTH
STANDARD CONTRACTOR

或者

$1,000.00
$5,000.00
STANDARD CONTRACTOR
$3500/MONTH
4

3 回答 3

1

选项1(在这里小提琴)

select expenses from table1
order by
  replace(replace(expenses, "$", ""), ",", "") regexp "[0-9.]*" desc,
  case when replace(replace(expenses, "$", ""), ",", "") regexp "[0-9.]*"
    then cast(replace(replace(expenses, "$", ""), ",", "") as real)
    else 0
  end

选项2(在这里小提琴):

select expenses from (
    select expenses,
      replace(replace(expenses, "$", ""), ",", "") expensesNormalized
    from table1
) s
order by
  expensesNormalized regexp "[0-9.]*" desc,
  case when expensesNormalized regexp "[0-9.]*"
    then cast(expensesNormalized as real)
    else 0
  end

选择跑得更快的那个。

于 2012-11-19T01:06:02.293 回答
0

在 SQL Server 中,您可以执行以下操作:

order by (case when isnumeric(col) = 1 then 1 else 0 end) desc,
         (case when isnumeric(col) = 1 then cast(col as money) end),
         col

对于其他数据库,您可以使用正则表达式匹配而不是 isumeric 来确定哪些是数字。

由于您使用的是 SQLite,而且我似乎能够假设所有数字都以“$”开头,所以这样的事情几乎可以工作:

order by (case when substr(col, 1, 1) = '$' then 1 else 0 end) desc,
         (case when substr(col, 1, 1) = '$' then cast(col as numeric) end),
         col

问题是“3,500 美元/月”被视为一个数字。你可以用一个正则表达式来解决这个问题,如果你有的话。或者,如果“/”定义了这些情况,您可以使用特定的内容,例如:

order by (case when substr(col, 1, 1) = '$' and col not like '%/%' then 1 else 0 end) desc,
         (case when substr(col, 1, 1) = '$' and col not like '%/%' then cast(col as numeric) end),
         col
于 2012-11-19T00:04:17.253 回答
0

如果现有的答案在 SQLlite 中有效,那么也许它们会为您工作。因为数据非常……混乱……我倾向于尝试将其丑陋的部分封装在一个返回排序数组的方法中。

如果您有少量这样的行(例如少于 500 行),那么更简洁的排序方法是包含 Comparable 并编写一个自定义比较器,正如在这个 SO answer 中很好地记录的那样

于 2012-11-19T02:03:32.260 回答