如何使用 sql 查询序列化 2 个表

Posted

技术标签:

【中文标题】如何使用 sql 查询序列化 2 个表【英文标题】:How to serialise 2 table usinq sql query 【发布时间】:2018-02-10 14:06:50 【问题描述】:

我要序列化这 2 个表..

表 1 DOCINF

DOCSKI , APPUKI, DOCINF_TYPE, NUMCHARS, DATETM

11  , ABC1234, ACK , 256, 20180219

表2 UDINF

UID, DOCSKI, APPQUAL, APPVALUE

1 , 11, ABC, 1234
2 , 11, DEF, 5678
3 , 11, GHI, 9012

我如何进行查询以得出如下结果,

APPUKI, DOCINF_TYPE, NUMCHARS, DATETM, < APPVALUE >, <APPVALUE>, <APPVALUE>

ABC1234, ACK , 256, 20180219 ,1234 ,5678, 9012 

尝试了这么多查询但没有得到结果。

SELECT APPUKI,
  DOCINF_TYPE,
  NUMCHARS,
  DATETM,
  a.appvalue,
  b.appvalue,
  c.appvalue
FROM docinf
LEFT OUTER JOIN udinf a
ON docinf.docski = a.docski
LEFT OUTER JOIN sp_udinf b
ON docinf.docski = b.docski
LEFT OUTER JOIN sp_udinf c
ON docinf.docski = c.docski
AND a.uid   <> b.uid
AND c.uid   <> c.uid order BY docinf.docski ;

谢谢;

【问题讨论】:

什么是sp_udinf?你在找pivot吗? 【参考方案1】:

对于每一列,您可以使用 GROUP BYJOINMAX ( CASE block )

另一个选项是PIVOT - https://www.techonthenet.com/oracle/pivot.php

SQL Fiddle

Oracle 11g R2 架构设置

CREATE TABLE DOCINF
    (DOCSKI int, APPUKI varchar2(7), DOCINF_TYPE varchar2(3), NUMCHARS int, DATETM int)
;

INSERT ALL 
    INTO DOCINF (DOCSKI, APPUKI, DOCINF_TYPE, NUMCHARS, DATETM)
         VALUES (11, 'ABC1234', 'ACK', 256, 20180219)
SELECT * FROM dual
;

CREATE TABLE UDINF
    (UID_ int, DOCSKI int, APPQUAL varchar2(3), APPVALUE int)
;

INSERT ALL 
    INTO UDINF (UID_, DOCSKI, APPQUAL, APPVALUE)
         VALUES (1, 11, 'ABC', 1234)
    INTO UDINF (UID_, DOCSKI, APPQUAL, APPVALUE)
         VALUES (2, 11, 'DEF', 5678)
    INTO UDINF (UID_, DOCSKI, APPQUAL, APPVALUE)
         VALUES (3, 11, 'GHI', 9012)
SELECT * FROM dual
;

查询 1

 SELECT appuki,
       docinf_type,
       numchars,
       datetm,
       MAX (CASE
              WHEN appvalue = 1234 THEN appvalue
            END) AS APPVALUE_1,
       MAX (CASE
              WHEN appvalue = 5678 THEN appvalue
            END) AS APPVALUE_2,
       MAX (CASE
              WHEN appvalue = 9012 THEN appvalue
            END) AS APPVALUE_3
FROM   docinf a
       JOIN udinf b  -- or LEFT OUTER 
         ON a.docski = b.docski
GROUP  BY appuki,
          docinf_type,
          numchars,
          datetm

Results

|  APPUKI | DOCINF_TYPE | NUMCHARS |   DATETM | APPVALUE_1 | APPVALUE_2 | APPVALUE_3 |
|---------|-------------|----------|----------|------------|------------|------------|
| ABC1234 |         ACK |      256 | 20180219 |       1234 |       5678 |       9012 |

【讨论】:

以上是关于如何使用 sql 查询序列化 2 个表的主要内容,如果未能解决你的问题,请参考以下文章

如何提高 SQL 查询的性能以从 2 个表中进行选择

跨 2 个表的 Mysql SQL 查询 - 不知道如何正确执行

如果 sql 连接 2 个表,如何操作数据传输对象?

如何通过单个 sql 查询连接 3 个表?

带有 2 个表的 SQL Server GROUP BY

如何在2个表之间加入新表?