如何在sql server上对数据进行这样的排序

时间:2013-10-01 06:54:47

标签: sql sql-server sql-server-2008

我的数据看起来像这样

| FormCode | Description          | MenuPath    |
+----------+----------------------+-------------+
|   PY     | Payroll              |             |
|   PD     | Personal Development |             | 
|   EM     | EmployeeMaster       |     PY      |
|   EB     | EmployeeBank         |     PY      |
|   ED     | EmployeeData         |     PY      |
| Report   | Report               |     PY      |
|  Badge   | Badge Report         |  PY/Report  |
| Process  | Process              |     PY      |
|  Bonus   | Bonus Component      |    PY/ED    | 
|Preference| Preference           |     PY      |
|   Tax    | Tax Result           |    PY/ED    |
|FinalBonus| FinalBonus           | PY/ED/Bonus |
| Annual   | Annual Process       | PY/Process  |
|BonusbyCC | Bonus by Cost Centre | PY/ED/Bonus |
| Period   | Period               |PY/Preference|

我希望此数据排序如下所示。

| FormCode | Description          | MenuPath    |
+----------+----------------------+-------------+
|   PY     | Payroll              |             |
|   EB     | EmployeeBank         |     PY      |
|   ED     | EmployeeData         |     PY      |
|  Bonus   | Bonus Component      |    PY/ED    |
|BonusbyCC | Bonus by Cost Centre | PY/ED/Bonus |
|FinalBonus| FinalBonus           | PY/ED/Bonus |
|   Tax    | Tax Result           |    PY/ED    |
|   EM     | EmployeeMaster       |     PY      |
|Preference| Preference           |     PY      |
| Period   | Period               |PY/Preference|
| Process  | Process              |     PY      |
| Annual   | Annual Process       | PY/Process  |
| Report   | Report               |     PY      |
|  Badge   | Badge Report         |  PY/Report  |
|   PD     | Personal Development |             | 

这是排序的结果

Explanation : 

我会尝试解释排序。首先我们看一下formcode。它将把PY放在第一行。之后,将有MenuPath为PY的行(按描述中的alphabeth排序)。在这种情况下,EmployeeBank首先显示。如果它没有任何子路径,则下一行将是EmployeeData。之后,EmployeeData有一个孩子就像我们可以看到下一行的Bonus组件(按说明排序)。之后,如果它没有任何子项,则下一行将是Tax Result,但正如您所看到的,Bonus Component仍然有一个子项(按成本中心和FinalBonus奖励),因此这2个数据将出现在Bonus Component之后。税务结果将出现在下一个。这个过程将一直保持到数据结束。

很抱歉,如果我的英语搞砸了,我的解释一点都不好。如果有人理解我的意思并且可以解释我的英语解释,请执行此操作

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

绝对没有逻辑可以按照你向我们展示的方式进行排序..但是你可以通过为你的领域分配某种ID然后对其进行排序来实现这一目标

答案 1 :(得分:0)

SELECT * FROM Table1
ORDER BY CASE [FormCode]
WHEN 'PY' THEN 1
WHEN 'EM' THEN 2
WHEN 'EB' THEN 3
WHEN 'ED' THEN 4
WHEN 'Bonus' THEN 5
WHEN 'BonusbyCC' THEN 6
WHEN 'FinalBonus' THEN 7
WHEN 'Tax' THEN 8
WHEN 'Preference' THEN 9
WHEN 'Period' THEN 10
WHEN 'Process' THEN 11
WHEN 'Annual' THEN 12
WHEN 'Report' THEN 13
WHEN 'Badge' THEN 14
WHEN 'PD' THEN 15
END;

<强> SAMPLE FIDDLE