SQL Multiple sorting and grouping

↘锁芯ラ 提交于 2019-12-11 08:53:51

问题


EDIT: I'm using DQL

I'm looking for help with an SQL query.

My table has a list of movies, each with a title, seriesName and seriesNumber. Is it possible to order them so the Titles are listed A-Z, but when a series occurs, that series is grouped together, with the seriesName being placed alphabetically as if it were inthe movieTitle column, and the entries in a series ordered by seriesNumber.

Bad explanation, but basically what I want is this:

MovieTitle                  SeriesName          SeriesNumber
Blade Runner                NULL                NULL
District 9                  NULL                NULL
Hot Fuzz                    NULL                NULL
I am Legend                 NULL                NULL
Fellowship of the Ring      Lord of the Rings   1
Two Towers, The             Lord of the Rings   2
Return of the King          Lord of the Rings   3
Lost in Translation         NULL                NULL
Matrix, The                 Matrix              1
Matrix Reloaded, The        Matrix              2
Matrix Revolutions, The     Matrix              3
Requiem for a Dream         NULL                NULL
This is Spinal Tap          NULL                NULL
Zodiac                      NULL                NULL

Thanks in advance.


回答1:


SELECT * FROM x
ORDER BY CASE 
   WHEN SeriesName is NOT NULL THEN SeriesName ELSE MovieTitle  END
   , SeriesNumber

You may have to do it this way

SELECT * FROM(
  SELECT *, CASE WHEN SeriesName is NOT NULL THEN SeriesName ELSE MovieTitle END SortOrder  FROM x
)
ORDER BY SortOrder,SeriesNumber


来源:https://stackoverflow.com/questions/10826299/sql-multiple-sorting-and-grouping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!