根据日期将列转换为行oracle 1.5.5版

时间:2018-02-08 00:45:31

标签: sql oracle

我的样本表如下:

Date            Product  Member_code
01/01/2015      ABC       1A
01/02/2016      BBB       1A
12/04/2013      SCC       2C
12/04/2014      AQQ       2C

预期结果

Member_code   Old_product       New_product
 1A             ABC               BBB
 2C             SCC               AQQ

感谢您的帮助 欢呼声

2 个答案:

答案 0 :(得分:2)

捕获product列中最旧和最新值的最有效方法是使用first / last聚合函数。 (个人观察:由于我不理解的原因,有许多从业人员,甚至是高级人员,他们都避免这种综合功能。)

使用Kaushik Nayak的设置(CREATE TABLEINSERT声明):

select   member_code,
         min(product) keep (dense_rank first order by p_date) as old_product,
         min(product) keep (dense_rank last  order by p_date) as new_product
from     yourtable
group by member_code
;

MEMBER_CODE  OLD_PRODUCT  NEW_PRODUCT
-----------  -----------  -----------
1A           ABC          BBB
2C           SCC          AQQ

答案 1 :(得分:1)

一种方法是使用SELF JOIN

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE yourtable
    (p_Date varchar2(10), Product varchar2(3), Member_code varchar2(2))
;

INSERT ALL 
    INTO yourtable (p_Date, Product, Member_code)
         VALUES ('2015-01-01', 'ABC', '1A')
    INTO yourtable (p_Date, Product, Member_code)
         VALUES ('2016-02-01', 'BBB', '1A')
    INTO yourtable (p_Date, Product, Member_code)
         VALUES ('2013-04-12', 'SCC', '2C')
    INTO yourtable (p_Date, Product, Member_code)
         VALUES ('2014-04-12', 'AQQ', '2C')
SELECT * FROM dual
;

查询1

 SELECT t1.member_code,
       t1.product old_product,
       t2.product new_product
FROM   yourtable t1
       join yourtable t2
         ON t1.member_code = t2.member_code
            AND t1.p_date < t2.p_date

<强> Results

| MEMBER_CODE | OLD_PRODUCT | NEW_PRODUCT |
|-------------|-------------|-------------|
|          1A |         ABC |         BBB |
|          2C |         SCC |         AQQ |