SQLite:如何组合子查询结果

时间:2017-02-09 04:40:45

标签: sqlite

我有一张这样的表

    id  |   inventory_id    |   serial_type |   serial
------------------------------------------------------
    38  |       5892        |       1       |   9502
    39  |       5895        |       1       |   i95054-1
    40  |       5895        |       2       |   m95054-1
    41  |       5895        |       1       |   i95054-2
    42  |       5895        |       2       |   m95054-2
    43  |       5895        |       1       |   i95054-3
    44  |       5895        |       2       |   m95054-3
    45  |       5895        |       1       |   i95054-4
    46  |       5895        |       2       |   m95054-4

我有两个来自同一个表的子查询,如

SELECT inventory_id, serial as type_one_serial
FROM serials
WHERE serial_type = 1
AND inventory_id = 5895

和另一个

SELECT inventory_id, serial as type_two_serial
FROM serials
WHERE serial_type = 2
AND inventory_id = 5895

如何将这些结合起来得到像

这样的结果
inventory_id | type_one_serial | type_two_serial
------------------------------------------------
5895         |  i95054-1       |    m95054-1
5895         |  i95054-2       |    m95054-2
5895         |  i95054-3       |    m95054-3
5895         |  i95054-4       |    m95054-4

编辑: 我修改了源表以包含另一列sl

    sl  |   id  |   inventory_id    |   serial_type |   serial
 ----------------------------------------------------------------
    0   |   38  |       5892        |       1       |   9502
    0   |   39  |       5895        |       1       |   i95054-1
    0   |   40  |       5895        |       2       |   m95054-1
    1   |   41  |       5895        |       1       |   i95054-2
    1   |   42  |       5895        |       2       |   m95054-2
    2   |   43  |       5895        |       1       |   i95054-3
    2   |   44  |       5895        |       2       |   m95054-3
    3   |   45  |       5895        |       1       |   i95054-4
    3   |   46  |       5895        |       2       |   m95054-4

2 个答案:

答案 0 :(得分:3)

您正在寻找透视查询:

SELECT inventory_id,
       MAX(CASE WHEN serial_type = 1 THEN 'i' || SUBSTR(serial, 2) END) AS type_one_serial,
       MAX(CASE WHEN serial_type = 2 THEN 'm' || SUBSTR(serial, 2) END) AS type_two_serial
FROM serials
WHERE serial_type IN (1, 2) AND      -- the WHERE clause may be optional
      inventory_id = 5895            -- depending on what you want
GROUP BY inventory_id,
         SUBSTR(serial, 2)

<强>更新

考虑新的sl列,我们可以使用它来区分给定inventory_id的两种类型的连续出版物。在这种情况下,我们可以编写以下查询:

SELECT inventory_id,
       MAX(CASE WHEN serial_type = 1 THEN serial END) AS type_one_serial,
       MAX(CASE WHEN serial_type = 2 THEN serial END) AS type_two_serial
FROM serials
GROUP BY inventory_id,
         sl

答案 1 :(得分:0)

@Tim Biegeleisen编辑的答案对我来说非常合适。基于此,我做了一些修改。不确定它会有任何改进,只需在此处发布以供参考:

SELECT inventory_id, MAX(CASE WHEN serial_type = 1 THEN serial END) AS type_one_serial, MAX(CASE WHEN serial_type = 2 THEN serial END) AS type_two_serial FROM serials WHERE inventory_id = 5895 GROUP BY sl