将两行合并为一行

时间:2014-12-10 06:21:26

标签: sql database plsql oracle-sqldeveloper

我从图01所示的查询中得到以下输出。每个员工都有两条记录显示其工作地点和有效日期。当前标志显示由'Y'表示的当前记录。 现在我想将此输出转换为如图02所示的以下格式。此处员工只有一行。它显示了员工当前的记录和转移日期,以前的位置和新位置。

Figure 01

Figure 02

你能告诉我怎么做吗?

4 个答案:

答案 0 :(得分:2)

试试这个:

--PREVIOUSRESULT will be your existing result.

SELECT A.EMPLOYEENO, A.NAME, A.CURRENTFLAG, 
   (SELECT B.LOCATION FROM PREVIOUSRESULT B
    WHERE B.EMPLOYEENO = A.EMPLOYEENO AND B.CURRENTFLAG IS NULL) AS FROMVALUE, 
    A.Location AS ToValue, A.TRANSFERDATE AS EFFECTIVEDATE 
 FROM PREVIOUSRESULT A 
 WHERE A.CURRENTFLAG = 'Y'

--Result

答案 1 :(得分:1)

还有一个答案:

select a.empno, a.ename, a.cflag, 
(select b.location from empdetails b where b.empno=a.empno and b.cflag is null) "From",
a.location "To", a.transfer_date from empdetails a where a.cflag is not null;

选中此sqlfiddle

答案 2 :(得分:0)

SELECT [Employee No]
, [Name]
, MAX([Current Flag]) as [Current Flag]
, CASE WHEN [Current Flag] IS NULL THEN LOCATION ELSE NULL END AS [FROM]
, CASE WHEN [Current Flag] = 'Y' THEN LOCATION ELSE NULL END AS [TO]
, CASE WHEN [Current Flag] = 'Y' THEN [TRANSFER DATE] ELSE NULL END AS [EFFECTIVE DATE]
FROM Table1
GROUP BY [Employee No]
, [Name]
, CASE WHEN [Current Flag] IS NULL THEN LOCATION ELSE NULL END
, CASE WHEN [Current Flag] = 'Y' THEN LOCATION ELSE NULL END
, CASE WHEN [Current Flag] = 'Y' THEN [TRANSFER DATE] ELSE NULL END

答案 3 :(得分:0)

严格地给出每个员工的两条记录,我希望这个记录更快 - 只有一个表扫描,没有嵌套的循环连接。

select 
empno, 
ename, 
max(cflag) cflag, 
max(location) keep(dense_rank first order by transfer_date) "from",
max(location) keep(dense_rank last  order by transfer_date) "to",
max(transfer_date) transfer_date
from empdetails
group by empno, ename;

fiddle