0

嗨,我有一个与此类似的 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  
4

2 回答 2

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_用表联合替换先前的查询:

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
于 2013-11-13T16:10:21.130 回答
1
SELECT NAME, ID
FROM TABLE
ORDER BY  NAME, ID
于 2013-11-13T18:17:37.857 回答