SQLite数据库查询有序结果

时间:2013-11-13 15:40:02

标签: sql database sqlite

HY, 我有一个与此类似的sqllite表:

nr. | Name  
 4  | And  
 1  | Osd  
 6  | Edf  
 7  | Osd  
 6  | And  
 2  | Edf  
 3  | And  

我需要按名称对数据进行排序,以便它们成组,然后根据该组中的第一个nr对每个组进行排序。所以在查询之后结果应如下所示:

nr. | Name  
 1  | Osd  ->First goup, it has nr =  1  
 7  | Osd  
 2  | Edf  ->Second goup, it has nr =  2  
 6  | Edf  
 3  | And  ->Third goup, it has nr = 3  
 4  | And  
 6  | And  

2 个答案:

答案 0 :(得分:2)

这样做:

SELECT nr, Name FROM (
  SELECT nr, Name, (
    SELECT MIN(nr) FROM _table_ AS _ WHERE Name=_table_.Name
  ) AS _min FROM _table_
) ORDER BY _min, nr

http://sqlfiddle.com/#!7/674bf/5中查看。

编辑:如果_table_实际上是表的联合,则有3个选项:

1)创建一个视图,这样查询仍然有效:

CREATE VIEW _table_ AS SELECT * FROM _table1_ UNION ALL SELECT * FROM _table2_

2)将以前的查询中的_table_替换为表union:

SELECT nr, Name FROM (
  SELECT nr, Name, (
    SELECT MIN(nr) FROM (
      SELECT * FROM _table1_ UNION ALL SELECT * FROM _table2_
    )  AS _ WHERE Name=_table_.Name
  ) AS _min FROM (
    SELECT * FROM _table1_ UNION ALL SELECT * FROM _table2_
  ) AS _table_
) ORDER BY _min, nr

3)可能有一些优化(我说也许!):

SELECT _un.* FROM (
  SELECT * FROM _table1_
  UNION ALL
  SELECT * FROM _table2_
) AS _un
JOIN (
  SELECT Name, MIN(nr) AS _min FROM (
    SELECT * FROM _table1_
    UNION ALL
    SELECT * FROM _table2_
  ) GROUP BY Name
) AS _min ON _un.Name=_min.Name
ORDER BY _min, _un.nr

答案 1 :(得分:1)

SELECT NAME, ID
FROM TABLE
ORDER BY  NAME, ID