带有(from)别名的SQL子查询

时间:2015-08-25 17:40:21

标签: sql oracle subquery alias

我需要select子句中的子查询帮助。我有桌子:员工(EMPLOYEE_ID,EMPLOYEE_NAME,EMPLOYEE_GROUP)和活动(ACTIVITY_DATE,ACTIVITY_STATUS,EMPLOYEE_ID)。我需要为'W'集团的员工选择一些活动。

不幸的是我不能使用CREATE TABLE / VIEW函数,所以我试过这个,但是它没有用。

SELECT DISTINCT

TB1.EMPLOYEE_NAME,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'START' AND TB1.ACTIVITY_NUMBER = 1) AS FIRST_START,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'START' AND TB1.ACTIVITY_NUMBER = 2) AS SECOND_START,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'STOP' AND TB1.ACTIVITY_NUMBER = 1) AS FIRST_STOP,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'STOP' AND TB1.ACTIVITY_NUMBER = 2) AS SECOND_STOP

FROM( 

     SELECT DISTINCT

     A.EMPLOYEE_NAME,        
     B.ACTIVITY_DATE,
     B.ACTIVITY_STATUS,
     ROW_NUMBER() OVER (PARTITION BY A.EMPLOYEE_NAME,B.ACTIVITY_STATUS 
       ORDER BY B.ACTIVITY_DATE ASC) ACTIVITY_NUMBER

     FROM 
     (SELECT * FROM EMPLOYEES WHERE EMPLOYEE_GROUP ='W')  A

     LEFT JOIN ( SELECT * FROM ACTIVITIES  WHERE ACTIVITY_STATUS IN ('START','STOP','PAUSE') )B
      ON A.EMPLOYEE_ID = B.EMPLOYEE_ID

  ) TB1

你知道任何函数,我可以用它来从带有别名的表中选择数据吗?

1 个答案:

答案 0 :(得分:0)

我不确定您的Oracle版本是否支持它,但您必须将TB1定义为CTE(公用表表达式):

WITH TB1 AS ( 

     SELECT DISTINCT

     A.EMPLOYEE_NAME,        
     B.ACTIVITY_DATE,
     B.ACTIVITY_STATUS,
     ROW_NUMBER() OVER (PARTITION BY A.EMPLOYEE_NAME,B.ACTIVITY_STATUS 
       ORDER BY B.ACTIVITY_DATE ASC) ACTIVITY_NUMBER

     FROM 
     (SELECT * FROM EMPLOYEES WHERE EMPLOYEE_GROUP ='W')  A

     LEFT JOIN ( SELECT * FROM ACTIVITIES  WHERE ACTIVITY_STATUS IN ('START','STOP','PAUSE') )B
      ON A.EMPLOYEE_ID = B.EMPLOYEE_ID

  )
SELECT DISTINCT

TB1.EMPLOYEE_NAME,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'START' AND TB1.ACTIVITY_NUMBER = 1) AS FIRST_START,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'START' AND TB1.ACTIVITY_NUMBER = 2) AS SECOND_START,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'STOP' AND TB1.ACTIVITY_NUMBER = 1) AS FIRST_STOP,
(SELECT TB1.ACTIVITY_DATE FROM TB1 
WHERE TB1.ACTIVITY_STATUS = 'STOP' AND TB1.ACTIVITY_NUMBER = 2) AS SECOND_STOP

FROM TB1

或者,老式的方式是复制粘贴" TB1"的每个实例的定义。 (是的,真的,这就是我们以前的做法。)