查询具有条件的键 - 值对表

时间:2015-02-18 00:18:21

标签: sql oracle oracle11g

我一直对这个感到难过,并希望得到任何帮助。

这是表格的结构:

+----+-------------+-------------------+--+
| id |    name     |       value       |  |
+----+-------------+-------------------+--+
|  3 | email       | dsflkej@gmail.com |  |
|  3 | device_type | iOS               |  |
|  3 | text        | purchase          |  |
|  4 | email       | ueif@gmail.com    |  |
|  4 | device_type | iOS               |  |
|  5 | email       | tckjef@gmail.com  |  |
|  5 | device_type | Android           |  |
|  5 | text        | where can i pur   |  |
+----+-------------+-------------------+--+

我想要一个看起来像这样的结果:

╔════╦══════╦═════════════════╦══╦══╗
║ id ║ name ║      value      ║  ║  ║
╠════╬══════╬═════════════════╬══╬══╣
║  3 ║ text ║ purchase        ║  ║  ║
║  4 ║ text ║ Null            ║  ║  ║
║  5 ║ text ║ where can i pur ║  ║  ║
╚════╩══════╩═════════════════╩══╩══╝

由于k / v对中数据的结构,我很难找到正确的逻辑来获取唯一的id,然后找到name = text的行以及text的值。如果没有为id显示名称为text的行,我仍希望保留该ID,但表明它不存在。

2 个答案:

答案 0 :(得分:2)

SQL Fiddle

select id, 'text', min(decode(name, 'text',value)) 
  from table1 
group by id
order by 1 

<强> Results

| ID | 'TEXT' | MIN(DECODE(NAME,'TEXT',VALUE)) |
|----|--------|--------------------------------|
|  3 |   text |                       purchase |
|  4 |   text |                         (null) |
|  5 |   text |                where can i pur |

答案 1 :(得分:0)

一种选择是这样的。我从WITH子句中的表中获取了不同的ID值,然后返回到表中以获取数据。

WITH distinct_ids 
  AS( SELECT DISTINCT id
        FROM your_table )
SELECT ids.id,
       nvl(tbl.name,'text'),
       tbl.value
  FROM distinct_ids ids
       LEFT OUTER JOIN your_table tbl
         ON(     ids.id = tbl.id
             AND tbl.name = 'text' )
相关问题