2016-07-14 58 views
1

我正在尋找如何在SQLite中選擇每個組的第一條記錄的選項,其中組的排序是通過組合鍵。SQLite - 第一組 - 每個組合 - 排序和反對排序

示例表:

Key_1 | Sort1 | Sort2 | Val_1 | Val_2 
-------+-------+-------+-------+------- 
    1 | 1 | 3 | 0 | 2 
    1 | 1 | 2 | 2 | 4 
    1 | 1 | 1 | 4 | 6 
    1 | 2 | 2 | 6 | 8 
    1 | 2 | 1 | 8 | 1 
    2 | 1 | 2 | 0 | 5 
    2 | 1 | 1 | 1 | 6 
    2 | 2 | 3 | 2 | 7 
    2 | 2 | 2 | 3 | 8 
    2 | 2 | 1 | 4 | 9 

目的:
- 由Key_1 ASC, Sort1 ASC, Sort2 DESC
排序的數據 - 選擇每個獨特Key_1

Key_1 | Sort1 | Sort2 | Val_1 | Val_2 
-------+-------+-------+-------+------- 
    1 | 1 | 3 | 0 | 2 
    2 | 1 | 2 | 0 | 5 

解析函數法第一條記錄...

SELECT 
    * 
FROM 
(
    SELECT 
     *, 
     ROW_NUMBER() OVER (PARTITION BY Key_1 
           ORDER BY Sort1, 
             Sort2 DESC 
         ) 
           AS group_ordinal 
    FROM 
     table 
) 
    sorted 
WHERE 
    group_ordinal = 1 

費力ANSI-92的辦法......

SELECT 
    table.* 
FROM 
    table 
INNER JOIN 
(
    SELECT 
     table.Key1, table.Sort1, MAX(table.Sort2) AS Sort2 
    FROM 
     table 
    INNER JOIN 
    (
     SELECT 
      Key_1, MIN(Sort1) 
     FROM 
      table 
     GROUP BY 
      Key_1 
    ) 
     first_Sort1 
      ON table.Key_1 = first_Sort1.Key_1 
      AND table.Sort1 = first_Sort1.Sort1 
    GROUP BY 
     table.Key1, table.Sort1 
) 
    first_Sort1_last_Sort2 
     ON table.Key_1 = first_Sort1_last_Sort2.Key_1 
     AND table.Sort1 = first_Sort1_last_Sort2.Sort1 
     AND table.Sort2 = first_Sort1_last_Sort2.Sort2 

這涉及到很多嵌套和自我聯接。當涉及到兩列分類時,這非常麻煩。

我的實際例子有六個排序列。

我也想避免像以下任何東西,因爲它是(據我所知)保障/確定性...

SELECT 
    table.* 
FROM 
    table 
GROUP BY 
    table.Key_1 
ORDER BY 
    MIN(table.Sort1), 
    MAX(table.Sort2) 

是否有任何其他選項,我只是沒有看到?

回答

1

我相信,這將在SQLite的工作:

select t.* 
from table t 
where exists (select 1 
       from (select t2.* 
        from table t2 
        where t2.id = t.id 
        order by t2.sort1 asc, t2.sort2 desc 
        limit 1 
        ) t2 
       where t2.sort1 = t.sort1 and t2.sort2 = t.sort2 
      ); 

我擔心的是SQLite的是否允許在嵌套子查詢相關引用。如果沒有,你可以只使用=並連接所有的值加在一起:

select t.* 
from table t 
where (sort1 || ':' || sort2) = 
      (select (sort1 || ':' || sort2) 
      from table t2 
      where t2.id = t.id 
      order by sort1 asc, sort2 desc 
      limit 1 
     ); 
+0

尼斯,這兩個查詢給'WHERE(A,B)=(選擇A,B從X)',但作爲SQLite的兼容。我會給他們一個去,然後讓我的大腦在哪個選項是最不混淆的*(因爲無論可憐的開發者已經處理它是一年的時間)*。 – MatBailie

+0

@MatBailie。 。 。儘管我對第二種解決方案並不滿意,但第一次閱讀查詢的人可能會更清楚。 –

+0

與第一個一起去避免隱式類型轉換的問題。然後在分析函數中通過類似於分區和排序的方式添加關於相關性和順序的明智評論。基金有一個有趣的限制。外部查詢的字段可以在WHERE子句中引用,但不能在ORDER BY中引用。不確定這是否意味着這是不受支持的功能。另一天會深入挖掘。 – MatBailie