SQL:从单个列创建多个列

时间:2015-12-21 16:21:58

标签: sql oracle

输入数据: enter image description here

输入数据的查询 -

CREATE TABLE CustTable
(CustNum NUMBER(5), 
CntYear NUMBER(4),
TotalBill NUMBER(4));

INSERT INTO CustTable (CustNum, CntYear, TotalBill)
VALUES (101, 2013, 800);
INSERT INTO CustTable (CustNum, CntYear, TotalBill)
VALUES (101, 2015, 700);
INSERT INTO CustTable (CustNum, CntYear, TotalBill)
VALUES (102, 2013, 900);
INSERT INTO CustTable (CustNum, CntYear, TotalBill)
VALUES (102, 2015, 1000);

我想获得以下输出 -

enter image description here

谢谢。

2 个答案:

答案 0 :(得分:1)

这个怎么样?

select a.custnum, a.cntyear CurrContractYear, a.totalbill CurrBill, 
    b.cntyear NextContractYear, b.totalbill NextBill
from CustTable a inner join CustTable b
    on a.CustNum = b.CustNum
where b.CntYear > a.CntYear;

答案 1 :(得分:1)

此版本适用于特定客户的合约年数超过2个的情况。它也更有效率。

select * from (
select a.custnum, a.cntyear CurrContractYear, a.totalbill CurrBill, 
    lead(a.cntyear,1) over ( partition by a.custnum order by a.cntyear) NextContractYear, 
    lead(a.totalbill,1) over ( partition by a.custnum order by a.cntyear)  NextBill
from CustTable a
)
where nextcontractyear is not null
order by 1,2;