0

我需要按字母顺序(按 CustomerName)对我的 SQL 存储过程记录集(如下所示)进行排序,但还要保持 RecordID 的顺序(意味着 RecordID 2 相对于 ParentID 和 ID 字段高于 RecordID 3)。有什么建议么?

ID           ParentID         RecordID        CustomerName
53445347        5344        2                 Witt - 47
534453475345    53445347    3                 Witt - 45
534453475346    53445347    3                 Witt - 46
53445351        5344        2                 Sjob - 51
534453515348    53445351    3                 Sjob - 48
534453515349    53445351    3                 Sjob - 49
534453515350    53445351    3                 Sjob - 50
53445357        5344        2                 Hal - 57
534453575355    53445357    3                 Hal - 55
534453575356    53445357    3                 Hal - 56
534453577252    53445357    3                 Hal - 52
53446852        5344        2                 Boston, - 52
534468526850    53446852    3                 Boston, - 50
534468526851    53446852    3                 Boston, - 51
534468527205    53446852    3                 Boston, - 05
53447884        5344        2                 Agri - 84
534478847883    53447884    3                 Agri - 83
534478847957    53447884    3                 Agri - 57

预期的输出如下:

53447884        5344        2                 Agri - 84
534478847883    53447884    3                 Agri - 83
534478847957    53447884    3                 Agri - 57
53446852        5344        2                 Boston, - 52
534468526850    53446852    3                 Boston, - 50
534468526851    53446852    3                 Boston, - 51
534468527205    53446852    3                 Boston, - 05
53445357        5344        2                 Hal - 57
534453575355    53445357    3                 Hal - 55
534453575356    53445357    3                 Hal - 56
534453577252    53445357    3                 Hal - 52
53445351        5344        2                 Sjob - 51
534453515348    53445351    3                 Sjob - 48
534453515349    53445351    3                 Sjob - 49
534453515350    53445351    3                 Sjob - 50
53445347        5344        2                 Witt - 47
534453475345    53445347    3                 Witt - 45
534453475346    53445347    3                 Witt - 46
4

1 回答 1

3

如果您的所有客户名称都按照您的示例形成:

ORDER BY SUBSTRING( CustomerName, 0, CHARINDEX( '-', CustomerName)), RecordID

顺便说一句,如果您有机会更改模型,请将 CustomerName 的 alpha 和数字部分拆分为两个字段,您的生活会更好,世界会合而为一。

如果您可以在没有客户姓名的情况下使用-

不如试试

ORDER BY  CASE WHEN CHARINDEX('-', CustomerName) = 0 
               THEN CustomerName
               ELSE SUBSTRING( CustomerName, 0, CHARINDEX( '-', CustomerName))
            END,
            RecordID
于 2012-10-05T20:53:57.587 回答