简体   繁体   English

SQL DB2为多个ID实例选择多个列值

[英]SQL DB2 Select multiple columns values for multiple instances of IDs

Here is my data: 这是我的数据:

| ID | FIELD1 | FIELD2 | FIELD3 |
|-------------------------------|
| 1  |  NULL  | value1 | value2 |
|-------------------------------|
| 2  |  NULL  | value3 |  NULL  |
|-------------------------------|
| 3  | value4 |  NULL  |  NULL  |
|-------------------------------|
| 4  | value5 | value6 | value7 |
|-------------------------------|
| .. |  ...   |  ....  |  ....  |

Here is what I need to select: 这是我需要选择的:

| ID | ID2 | FIELDX |
|-------------------|
| 1  | 10  | value1 |
| 1  | 10  | value2 |
| 2  | 20  | value3 |
| 3  | 30  | value4 |
| 4  | 40  | value5 |
| 4  | 40  | value6 |
| 4  | 40  | value7 |
| .. | ..  |  ....  |

The order of the data doesn't really matter. 数据的顺序并不重要。 What matters is that each ID appears once for every associated FIELD1,2,3... value. 重要的是,每个ID对于每个关联的FIELD1,2,3 ...值都会出现一次。 Please note that there are many fields. 请注意,有很多字段。 I just chose to use these three as an example. 我只是选择使用这三个示例。

My attempt at the solution was this query: 我对解决方案的尝试是以下查询:

SELECT x.ID, a.ID2, x.FIELDX
FROM (
SELECT t.ID, t.FIELD1
FROM SCHEMA1.TABLE1 t
UNION ALL
SELECT t.ID, t.FIELD2
FROM SCHEMA1.TABLE1 t
UNION ALL
SELECT t.ID, t.FIELD3
FROM SCHEMA1.TABLE1 t
) x
JOIN SCHEMA2.TABLE2 a ON x.ID = a.ID
WHERE x.FIELDX != NULL
WITH UR;

While this does do the job, I would rather not have to add a new inner select statement for each additional field. 尽管这样做确实可行,但我不想为每个其他字段添加新的内部选择语句。 Moreover, I feel as though there is a more efficient way to do it. 而且,我觉得似乎有一种更有效的方法。

Please advise. 请指教。

DB2 doesn't have an explicit unpivot and your method is fine. DB2没有明确的unpivot ,您的方法很好。 A more efficient method is probably to do: 一种更有效的方法可能是:

SELECT id, id2, fieldx
FROM (SELECT x.ID, a.ID2,
             (case when col = 'field1' then field1
                   when col = 'field2' then field2
                   when col = 'field3' then field3
              end) as FIELDX
      FROM SCHEMA1.TABLE1 x join
           SCHEMA2.TABLE2 a
           on x.ID = a.ID cross join
           (select 'field1' as col from sysibm.sysdummy1 union all
            select 'field2' from sysibm.sysdummy1 union all
            select 'field3' from sysibm.sysdummy1
           ) c
     ) x
WHERE x.FIELDX is not NULL;

This doesn't necessarily simplify the code. 这并不一定简化代码。 It does make it easier for DB2 to optimize the joins. 它确实使DB2更容易优化连接。 And it only requires reading table1 once instead of one time for each column. 它只需要读取一次table1 ,而不需要为每一列读取一次。

As a note: you should use fieldx is not null rather than fieldx != null . 注意:您应该使用fieldx is not null而不是fieldx != null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM