Значение ORDER BY < конкретное множественное число >

Ниже код работал для меня для создания и загрузки текстового файла.

@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDownloadData() throws Exception {

    String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
    byte[] output = regData.getBytes();

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("charset", "utf-8");
    responseHeaders.setContentType(MediaType.valueOf("text/html"));
    responseHeaders.setContentLength(output.length);
    responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");

    return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);
}
1
задан eyllanesc 16 January 2019 в 06:39
поделиться

2 ответа

Вы можете узнать и узнать подробности из запроса ниже. Множественный столбец OrderBy полезен, когда аналогичные значения присутствуют в таблице.

Create Table Orders (Id int, ProdName Varchar(20))
insert into Orders Values (1, 'A'), (4, 'C'), (2, 'B'), (3, 'E'), (4, 'G'), (5, 'D'), (6, 'F'), (7, 'G')

Select * from Orders
order by 1 -- Order By Id Ascending

Select * from Orders
order by 1 desc -- Order By Id Descending

Select * from Orders
order by 2 -- Order By Name Ascending

Select * from Orders
order by 2 desc -- Order By Name Descending

Select * from Orders
order by 1, 2 -- Order By Id first and then Name Ascending. 
-- It will come same Id first and same name later

Select * from Orders
order by 1 asc, 2 desc --First priority of Id ascending then Name in descending order

Select * from Orders
order by 1, 2 desc

Вы можете найти живое демо Live Demo Здесь

0
ответ дан Suraj Kumar 16 January 2019 в 06:39
поделиться

В SQL ORDER BY - это ключевое слово, используемое для упорядочения набора результатов на основе значений конкретного столбца или столбцов в порядке возрастания или убывания.

ORDER BY дается как последнее утверждение в SELECT.

Синтаксис:

SELECT
    <List of Columns>
    FROM <Table Name>
    <Filter Conditions > -- Optional
    <Group By and Having> - Optional
    ORDER BY 
    <Column 1> <ASC or DESC>,
    <Column 2> <ASC or DESC>,
    .......
    <Column N> <ASC or DESC>,

Вы можете либо дать имена столбцов, либо порядковую позицию столбца в списке выбора.

Например:

SELECT
    EmpId,
    FirstName,
    LastName,
    Age,
    ContactNumber
    FROM Employee
        ORDER BY 
            FirstName,
            Age

Также можно записать как

SELECT
    EmpId,
    FirstName,
    LastName,
    Age,
    ContactNumber
    FROM Employee
        ORDER BY 
            2,4

во втором, я задаю Порядковый номер столбцов FirstName и Age вместо указания Название столбца.

Этот подход более полезен, когда в вашем наборе результатов есть 2 столбца с одинаковым именем.

Пример:

SELECT
    EmpId,
    *
    ContactNumber
    FROM Employee
        ORDER BY 
            EmpId

Выше приведено следующее сообщение об ошибке

Msg 209, Уровень 16, Состояние 1, Строка 5 Неоднозначное имя столбца 'EmpId .

Так что вместо этого вы можете сказать

  SELECT
    EmpId,
    *
    ContactNumber
    FROM Employee
        ORDER BY 
            1
0
ответ дан Jayasurya Satheesh 16 January 2019 в 06:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: