简体   繁体   English

Sql 服务器 - 如何排序非字母数字

[英]Sql Server - How to sort other than alphanumeric

In Sql Server 2008 I have a DB table, and the data includes a field that indicates a time period in the form: 2d, 1w, 4y, where "d" = day, "w" = week, "y" = year.在 Sql Server 2008 中,我有一个 DB 表,数据包含一个字段,该字段以如下形式指示时间段:2d、1w、4y,其中“d”= 日,“w”= 周,“y”= 年。 What is the best way to sort based on this field so that they are in time order (eg "3w" before "1y")?基于此字段排序的最佳方法是什么,以便它们按时间顺序排列(例如“3w”在“1y”之前)?

Thanks谢谢

I guess you're lucky that d is before w and w is also before y so you could do我想你很幸运 d 在 w 之前并且 w 也在 y 之前所以你可以这样做

ORDER BY RIGHT(MyField, 1), CONVERT(int, LEFT(Field, LEN(Field) - 1))

However this is not going to put 1w before 8d for example.但是,例如,这不会将 1w 放在 8d 之前。

So an alternative (more complicated) solution could be所以一个替代(更复杂)的解决方案可能是

ORDER BY 
   CASE RIGHT(Field, 1)
       WHEN 'd' THEN LEFT(Field, LEN(Field) - 1)
       WHEN 'w' THEN 7*LEFT(Field, LEN(Field) - 1)
       ELSE 356 * LEFT(Field, LEN(Field) - 1)
   END 

It makes assumptions about your data (eg only d, w, and y are going to be there) and doesn't take account of leap years (if that matters).它对您的数据做出假设(例如,只有 d、w 和 y 将在那里)并且不考虑闰年(如果这很重要)。

You may have different periods over time.随着时间的推移,您可能会有不同的时期。 So i would put this periods in a new table with ID, time period and sort order (or no. of days).所以我会把这些时间段放在一个带有 ID、时间段和排序顺序(或天数)的新表中。 In the initial table replace the field with time_period_id and make a join in your query and use it in SORT BY.在初始表中将字段替换为 time_period_id 并在您的查询中进行连接并在 SORT BY 中使用它。

Replace your characters with string numbers and convert to integer before sorting, Like:用字符串数字替换您的字符并在排序之前转换为 integer ,例如:

convert(int, replace(replace(replace(myField,'d',''),'w','0')'y','00'))

So your 3d is 3, 2w is 20 and 4y is 400.所以你的 3d 是 3,2w 是 20,4y 是 400。


after thinking about a bit, it's gonna better to calculate the real values through a case expression.想了想,还是通过case表达式来计算实际值会更好。 eg to get 14 for 2w which is less than 13d.例如,2w 得到 14,小于 13d。

My approach would be to write a function that parses your duration string and normalizes it in the smallest possible units that can be expressed (I'm assuming that it's days, but if you can have hours or some smaller unit expressed, use that).我的方法是编写一个 function 来解析您的持续时间字符串并以可以表示的最小可能单位对其进行规范化(我假设它是天,但如果您可以用小时或更小的单位表示,请使用它)。 Then, have a computed column that is the value of that function called against your column.然后,有一个计算列,它是针对您的列调用的 function 的值。 At that point, it's just a matter of comparing the numbers.在这一点上,这只是比较数字的问题。 Of course, the devil's in the details... I don't relish trying to parse text from T-SQL though.当然,魔鬼在细节中……虽然我不喜欢尝试从 T-SQL 解析文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM