Oracle:将一些结果用作列标题

时间:2017-11-06 10:31:32

标签: sql oracle

我有一个包含两个表格的数据库:
表一:

Petition - Date


表二:

Petition - Item - Count

所以数据显示为:

00000001 - 20171106

00000001 - Apple  - 2
00000001 - Orange - 3

问题是我想查询以这种方式格式化数据:

Petition - Date     - Apple - Orange
00000001 - 20171106 - 2     - 3


我只能以这种方式制作一个向我显示数据:

Petition - Date     - Item   - Count
00000001 - 20171106 - Apple  - 2
00000001 - 20171106 - Orange - 3

1 个答案:

答案 0 :(得分:2)

使用PIVOT

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE one ( petition, "Date" ) AS
SELECT '00000001', DATE '2017-11-06' FROM DUAL;

CREATE TABLE two ( petition, item, "Count" ) AS
SELECT '00000001', 'Apple', 2 FROM DUAL UNION ALL
SELECT '00000001', 'Orange', 3 FROM DUAL;

查询1

SELECT p.*
FROM   (
  SELECT o.petition,
         o."Date",
         t.item,
         t."Count"
  FROM   one o
         INNER JOIN two t
         ON ( o.petition = t.petition )
)
PIVOT ( SUM( "Count" ) FOR item IN (
  'Apple'  AS Apple,
  'Orange' AS Orange
) ) p

<强> Results

| PETITION |                 Date | APPLE | ORANGE |
|----------|----------------------|-------|--------|
| 00000001 | 2017-11-06T00:00:00Z |     2 |      3 |