MS SQL使用通过联合获取的值对记录进行排序

时间:2018-08-14 07:43:40

标签: sql sql-server sql-server-2012

我有一个具有MS SQL值的记录表,例如

ID, Type, Name, Amount 
----------------------
1, 1, abc, 100
2, 1, xyz, 200
3, 1, aaa, 500
null, 1, 'Total', 800
4, 2, bbb, 100
5, 2, bbc, 200
6, 2, bbx, 400
null, 2, 'Total', 700
7, 4, ccc, 400
8, 4, cde, 200
9, 4, fgh, 400
null, 4, 'Total', 1000

现在,我想对这些值进行排序,例如应该以1000排在第一,以800排在第二,这样id 4的所有行也应该排在其他记录之前。

我的查询为:

从表中选择ID,类型,名称,金额 全部合并 按类型从表组中选择空,类型,“总计”,sum(Amount)

4 个答案:

答案 0 :(得分:0)

您的order by

中有两个条件
  1. id 4也应排在其他记录之前。
  2. 我想对这些值进行排序,例如应该先输入1000,然后再输入800,然后

您可以尝试使用CASE WHEN和多个order by

CREATE TABLE T(
    ID INT,
    Type INT,
    Name VARCHAR(50),
    Amount INT
);

INSERT INTO T VALUES (1, 1, 'abc', 100        );
INSERT INTO T VALUES (2, 1, 'xyz', 200        );
INSERT INTO T VALUES (3, 1, 'aaa', 500        );
INSERT INTO T VALUES (null, 1, 'Total', 800 );
INSERT INTO T VALUES (4, 2, 'bbb', 100        );
INSERT INTO T VALUES (5, 2, 'bbc', 200        );
INSERT INTO T VALUES (6, 2, 'bbx', 400        );
INSERT INTO T VALUES (null, 2, 'Total', 700 );
INSERT INTO T VALUES (7, 4, 'ccc', 400        );
INSERT INTO T VALUES (8, 4, 'cde', 200        );
INSERT INTO T VALUES (9, 4, 'fgh', 400        );
INSERT INTO T VALUES (null, 4, 'Total', 1000);

查询1

SELECT * 
FROM T
ORDER BY 
(CASE WHEN ID = 4 THEN 0 ELSE 1 END),
Amount DESC

Results

|     ID | Type |  Name | Amount |
|--------|------|-------|--------|
|      4 |    2 |   bbb |    100 |
| (null) |    4 | Total |   1000 |
| (null) |    1 | Total |    800 |
| (null) |    2 | Total |    700 |
|      3 |    1 |   aaa |    500 |
|      9 |    4 |   fgh |    400 |
|      7 |    4 |   ccc |    400 |
|      6 |    2 |   bbx |    400 |
|      5 |    2 |   bbc |    200 |
|      8 |    4 |   cde |    200 |
|      2 |    1 |   xyz |    200 |
|      1 |    1 |   abc |    100 |

答案 1 :(得分:0)

SELECT [ID]
      ,[Type]
      ,[Name]
      ,[Amount]
  FROM [T]
  Group by [Type],[Amount],[Name],[ID]
  Order by [Type] desc, [Amount] desc

这是我的结果。我想你是说按类型而不是ID排序

ID  Type    Name    Amount
NULL    4   Total   1000
7   4   ccc 400
9   4   fgh 400
8   4   cde 200
NULL    2   Total   700
6   2   bbx 400
5   2   bbc 200
4   2   bbb 100
NULL    1   Total   800
3   1   aaa 500
2   1   xyz 200
1   1   abc 100

答案 2 :(得分:0)

如果我理解正确,则希望按总金额最大的类型对行进行排序。您可以使用窗口功能:

order by max(case when name = 'Total' then amount end) over (partition by type) desc,  -- put the types with the largest totals first
         type,  -- keep all types together
         id desc    -- canonically order within each type

答案 3 :(得分:0)

我会使用窗口功能:

order by max(amount) over (partition by type) desc,
         amount desc,
         id;