Microsoft SQL Server中的排序和自定义排序

时间:2016-11-05 09:41:15

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

我有一个包含数字和字符串值的表。我需要应用如下所述的自定义排序: -

CREATE TABLE [dbo].[TEST]
(
    [Tag] [nvarchar](max) NULL,
    [Category] [nvarchar](max) NULL,
    [LE] [nvarchar](max) NULL,
    [Description] [nvarchar](max) NULL,
    [Row_Id] [int] NOT NULL,

    CONSTRAINT [PK_testsirius_TEST_0_Row_Id] 
       PRIMARY KEY CLUSTERED ([Row_Id] ASC)
)

Insert into TEST values (1,'Area','EMR','A',199)
Insert into TEST values (2,'Area','EMR','B',200)
Insert into TEST values (3,'Area','EMR','C',201)
Insert into TEST values (201,'Area','EMR','1',399)
Insert into TEST values (202,'Area','EMR','2',400)
Insert into TEST values (203,'Area','EMR','3',401)

例外输出:

select * 
from TEST 
order by asc

输出:

1
2
3
A
B
C

当前输出:

C
B
A
3
2
1

要求:

  • 如果排序方向为[↑],则首先将所有数值从最小值排序到最大值,然后将所有时间值从最旧值排序到最新值,然后将所有文本值从A到Z排序
  • 如果排序方向为[↓],则首先将所有文本值从Z排序到A,然后将所有时间值从最新到最旧排序,然后将所有数值从最大值排序到最小值
  • 排序时,务必将空白单元格放在底部。

3 个答案:

答案 0 :(得分:4)

SELECT *
FROM TEST
ORDER BY CASE WHEN Description NOT LIKE '%[^0-9]%' THEN 0 ELSE 1 END,
         LEN(Description),
         Description

答案 1 :(得分:1)

您可以使用isNumeric()。

query = query.Union(x=> x.fool == "clown");  // ??

- 对于降序,您可以使用数学思想-1 *数字保持幅度但反转顺序......

select * 
from TEST
order by CASE WHEN isNumeric(Description) = 1 THEN Cast([Description] as int) ELSE 2147483647 END
,   Description

- 使用12345的额外测试用例

select * 
from TEST
order by CASE WHEN isNumeric(Description) = 1 THEN Cast([Description] as int) *     -1  ELSE -2147483648 END
,   Description desc

- 降序

CREATE TABLE [dbo].[TEST]
(
    [Tag] [nvarchar](max) NULL,
    [Category] [nvarchar](max) NULL,
    [LE] [nvarchar](max) NULL,
    [Description] [nvarchar](max) NULL,
    [Row_Id] [int] NOT NULL,

    CONSTRAINT [PK_testsirius_TEST_0_Row_Id] 
       PRIMARY KEY CLUSTERED ([Row_Id] ASC)
)

Insert into TEST values (1,'Area','EMR','A',199)
Insert into TEST values (2,'Area','EMR','B',200)
Insert into TEST values (3,'Area','EMR','C',201)
Insert into TEST values (201,'Area','EMR','1',399)
Insert into TEST values (202,'Area','EMR','2',400)
Insert into TEST values (203,'Area','EMR','3',401)
Insert into TEST values (204,'Area','EMR','12345',402)

select * 
from TEST
order by CASE WHEN isNumeric(Description) = 1 THEN Cast([Description] as int) ELSE 2147483647 END
,   Description


-- example output

Tag Category    LE  Description Row_Id
201 Area    EMR 1   399
202 Area    EMR 2   400
203 Area    EMR 3   401
204 Area    EMR 12345   402
1   Area    EMR A   199
2   Area    EMR B   200
3   Area    EMR C   201

答案 2 :(得分:0)

你试过这个:

control.disable({onlySelf: true});