以日历格式显示查询结果

时间:2015-03-23 05:55:07

标签: sql oracle calendar

我有四个表CUSTOMERS,PRODUCTS,CALENDAR,ORDERS,数据为 -

1)客户[CUST是PK]

CUST
----
ABC Inc
XYZ Corporation

2)产品[PID为PK]

PID     PRODUCT
---     -------
101     Chair
102     Table
103     Sofa
104     Cot

3)日历[日期为PK] - 用于存储日期和日期的简单日历表

DATE        DAY
----        ---
2015-01-01  THU
2015-01-02  FRI
....
2015-06-30  TUE

4)ORDERS [OID是PK] - 存储订单信息

OID     CUST     DATE        PID     QUANTITY
---     ----     ----        ---     --------
1       ABC Inc  2015-02-17  101     2
2       ABC Inc  2015-02-17  102     5
3       ABC Inc  2015-02-18  102     1
4       ABC Inc  2015-02-18  103     8
5       ABC Inc  2015-02-18  104     6

请帮助我使用SQL / PLSQL为ABC Inc客户提取订单详情,该客户应以日历格式(一周5个工作日)显示PRODUCT和QUANTITY作为 -

PRODUCT     2015-02-16  2015-02-17  2015-02-18  2015-02-19  2015-02-20
-------     ----------  ----------  ----------  ----------  ----------
Chair       (null)      2           (null)      (null)      (null)
Table       (null)      5           1           (null)      (null)
Sofa        (null)      (null)      8           (null)      (null)
Cot         (null)      (null)      6           (null)      (null)

所有产品都应显示在第1栏中。本周的开始和结束工作日期应由sysdate决定。

1 个答案:

答案 0 :(得分:0)

您可以使用PIVOT

   WITH pvt AS (
           SELECT p.product, o.quantity, o.date
           FROM   Orders o
           JOIN Products p on o.pid=p.pid
           )
   SELECT *
   FROM   pvt
   PIVOT (
          quantity                    
          FOR date
          IN  ('2015-02-16','2015-02-17','2015-02-18', '2015-02-19','2015-02-20')   
         );