Oracle Query从具有不同条件的单个表中获取两个值

时间:2018-07-23 17:55:10

标签: sql oracle11g

我在下表中有此表格。我正在尝试获取以下信息:

第一个条件:从出现“电话”的第一个实例时,从表中获取除TAG信息外的所有故障单详细信息。

第二个条件:将最新的最新标签信息与第一个条件一起获取。

Here is the sample data:
    +----------+-----------+--------------+--------------+-------------------+----------------+-------------------+
    | TICKETID | SUBTICKET |  DEPARTMENT  | CUSTOMER REP | COMMUNICATIONTYPE |      TAG       | COMMUNICATIONDATE |
    +----------+-----------+--------------+--------------+-------------------+----------------+-------------------+
    | A112421  |       323 | FOOD PROCESS | ANDY         | NOTES             | SATISFIED      | 5/21/18 9:30 AM   |
    | A112421  |       324 | FOOD PROCESS | ANDY         | NOTES             | AVERAGE        | 5/22/18 7:10 AM   |
    | A112421  |       325 | FOOD PROCESS | ANDY         | TELEPHONE         | AVERAGE        | 5/24/18 4:10 PM   |
    | A112421  |       326 | KITCHEN      | ALEX         | NOTES             | SATISFIED      | 5/25/18 6:10 AM   |
    | A112421  |       327 | KITCHEN      | ALEX         | EMAIL             | NOT SATISFIED  | 5/25/18 7:15 AM   |
    | A112421  |       328 | KITCHEN      | SAM          | EMAIL             | AVERAGE        | 5/26/18 5:25 PM   |
    | A112421  |       329 | KITCHEN      | SAM          | TELEPHONE         | ABOVE AVERAGE  | 5/26/18 5:45 PM   |
    | A112421  |       330 | TRANSPORT    | RAHUL        | NOTES             | VERY SATISFIED | 5/27/18 6:25 AM   |
    +----------+-----------+--------------+--------------+-------------------+----------------+-------------------+

The results I am looking for as follows:

    +----------+-----------+--------------+--------------+-------------------+----------------+--------------------+
    | TICKETID | SUBTICKET |  DEPARTMENT  | CUSTOMER REP | COMMUNICATIONTYPE |      TAG       | COMMUNICATION DATE |
    +----------+-----------+--------------+--------------+-------------------+----------------+--------------------+
    | A112421  |       325 | FOOD PROCESS | ANDY         | TELEPHONE         | VERY SATISFIED | 5/24/18 4:10 PM    |
    +----------+-----------+--------------+--------------+-------------------+----------------+--------------------+

非常感谢您的帮助。

谢谢。

1 个答案:

答案 0 :(得分:0)

尝试一下?我正在使用SQL

    DECLARE @FIRSTCOMMDATE DATETIME =(SELECT MIN (communicationdate)  from table) 

DECLARE @MOSTRECENTCOMMDATE DATETIME =(SELECT MAX (communicationdate)  from table) 
;WITH MOSTRECENTCOMMDATE AS

(
     SELECT  TICKETID, TAG, COMMDATE, SUBTICKET 
    FROM TABLE_NAME (NOLOCK) 
    WHERE communicationdate =@MOSTRECENTCOMMDATE

) 


     SELECT  TICKETID, SUBTICKET, DEPARTMENT, CUSTOMER_REP, REC.TAG,COMMUNICATIONTYPE, COMMDATE
    FROM TABLE_NAME  t1 (NOLOCK) 
INNER JOIN MOSTRECENTCOMMDATE rec on rec.ticketid =t1.ticketid and rec.substicket=t1.subticket 
    WHERE communicationdate =@FIRSTCOMMDATE