如何使用 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 BY
和 JOIN
和 MAX ( 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 个表的主要内容,如果未能解决你的问题,请参考以下文章