MS SQL:第一列不同且无序,第二列排序

时间:2018-02-08 11:11:22

标签: sql-server

对不起第一个版本:(  请参阅下面的真实示例:

    SELECT FilterName,FilterOption
    FROM(
      SELECT FilterName,FilterOption, ROW_NUMBER() OVER( PARTITION BY FilterName,FilterOption  ORDER BY FilterOption) AS rn 
    FROM   @myTable
   )A 
   WHERE rn = 1
   ORDER BY (2)

问题是如果可能的话,SQL查询以插入顺序返回FilterNames作为第一列,而在第二列中int所有过滤器选项都排序为A-Z? OUTPUT EXAMPLE

我正在使用以下查询:

{{1}}

2 个答案:

答案 0 :(得分:0)

尝试此查询

{1994: 474732,
 1995: 459580,
 1996: 456261,
 1997: 450840,
 1998: 453776,
 1999: 449985,
 2000: 469794,
 2001: 453928,
 2002: 445770,
 2003: 447445}

答案 1 :(得分:0)

如果我理解你的问题,我相信你想要一个自定义排序。其中一种方法是使用案例陈述

DECLARE @T TABLE (FilterName VARCHAR(10),   FilterOption VARCHAR(10))
INSERT INTO @T VALUES
('XX', 'ccc'),
('XX', 'ccc'),
('XX', 'acc'),
('XX', 'bbx'),
('XX', 'ccc'),
('AA', 'fff'),
('AA', 'bbb'),
('AA', 'fff'),
('AA', 'acd'),
('UU', 'uff'),
('UU', 'acf'),
('UU', 'uff'),
('BB', 'bff'),
('BB', 'bff'),
('BB', 'aff'),
('BB', 'aff'),
('BB', 'xff'),
('BB', 'xff'),
('BB', 'aff');

;WITH SORTING AS (SELECT DISTINCT
*,
CASE 
WHEN FilterName='XX' THEN 1
WHEN FilterName='AA' THEN 2
WHEN FilterName='UU' THEN 3
WHEN FilterName='BB' THEN 4
ELSE 5 END AS SORT
FROM @T
)
SELECT
FilterName, FilterOption
FROM SORTING
ORDER BY  SORT, FilterOption 

输出

FilterName  FilterOption
XX  acc
XX  bbx
XX  ccc
AA  acd
AA  bbb
AA  fff
UU  acf
UU  uff
BB  aff
BB  bff
BB  xff