我试图获取存储在两个表(父/子关系)中的数据,并根据特定供应商的规范生成格式化的XML。我花了很多时间学习Oracle XML函数,并将查询深入到最后一部分。 XML的页脚需要包含总数。由于某种原因,我无法像在查询中其他位置进行管理那样使子查询在这里工作。
以下是一些设置数据:
create table chk_hdr (hdr_id number(4,0), chk_no number(3,0), chk_date date, chk_net_amt number(7,2), constraint pk_chk_hdr primary key (hdr_id));
create table chk_dtl (hdr_id number(4,0), dtl_id number(4,0), descr varchar2(30), descr2 varchar2(30), net_amt number(7,2), constraint pk_chk_dtl primary key (dtl_id), constraint fk_hdr_id foreign key (hdr_id) references chk_hdr(hdr_id));
insert into chk_hdr values (1000, 15, to_date('1/31/2019','MM/DD/YYYY'), 23.43);
insert into chk_hdr values (1001, 16, to_date('1/31/2019','MM/DD/YYYY'), 159.75);
insert into chk_dtl values (1000, 7000, 'Example 1.1', 'Example 1.1a', 10.01);
insert into chk_dtl values (1000, 7001, 'Example 1.2', 'Example 1.2a', 13.42);
insert into chk_dtl values (1001, 7002, 'Example 2.1', 'Example 2.1a', 65.12);
insert into chk_dtl values (1001, 7003, 'Example 2.2', 'Example 2.2a', 84.36);
insert into chk_dtl values (1001, 7004, 'Example 2.3', 'Example 2.3a', 10.27);
除了页脚/“ Trailer”之外,这里的查询与我预期的一样工作:
SELECT dbms_xmlgen.convert(xmlserialize(document
xmlelement("PrintChecks",
xmlelement("Header",
xmlforest('test' AS "FileID",
'description' AS "FileDescription",
to_char(SYSDATE, 'YYYY-MM-DD') AS "FileGenDate",
to_char(SYSDATE, 'HH24:MI:SS') AS "FileGenTime")),
xmlelement("Checks",
xmlagg(xmlelement("Check",
xmlforest(h.hdr_id AS "CheckID",
h.chk_no AS "CheckNumber",
h.chk_date AS "CheckDate",
h.chk_net_amt AS "CheckAmount"),
xmlelement("InvoiceLines",
(SELECT xmlagg(xmlelement("InvoiceLine",
d.descr || ' | ' ||
d.descr2 || ' | ' ||
d.net_amt)
ORDER BY d.descr)
FROM chk_dtl d
WHERE h.hdr_id = d.hdr_id))))),
xmlelement("Trailer",
xmlforest('test' AS "FileID",
'123' AS "TotalChecks",
'123' AS "TotalAmount"))) version '1.0'),
1) xdoc
FROM chk_hdr h
WHERE h.chk_date = '31-JAN-2019';
我还尝试了如下设置“ Trailer”部分的格式,该部分也适用:
xmlelement("Trailer",
xmlelement("FileID", 'FileID Test'),
xmlelement("TotalChecks", 123),
xmlelement("TotalAmount", 123.45))) version '1.0'),
在“ Trailer”部分中,我需要获取头表中的记录数和chk_net_amt字段的总和。我尝试了各种方法,但始终会遇到以下错误:ORA-00937:不是单组分组函数。我什至尝试将页脚包装在SELECT FROM DUAL语句中,而没有实际选择任何内容,仍然出现错误。
以下是我尝试过的示例:
(select xmlelement("Trailer",
xmlelement("FileID", 'FileID Test'),
xmlelement("TotalChecks", count(h1.hdr_id)),
xmlelement("TotalAmount", sum(h1.chk_net_amt)))
from chk_hdr h1 where h1.chk_date=h.chk_date )) version '1.0'),
也失败,并出现相同的错误:
(select xmlelement("Trailer",
xmlelement("FileID", 'FileID Test'),
xmlelement("TotalChecks", 123),
xmlelement("TotalAmount", 123.45))
from dual)) version '1.0'),
使用Oracle 12.1