帮助查询 - SQL

时间:2011-07-08 19:29:47

标签: tsql

我真的在努力解决下面这个问题并需要一些帮助......我找到了一些答案,但没有以正确的方式引导我......

表1

 sub-id  ref-id    Name
    1       1         Project 1
    2       1         Project 2  
    3       2         Project 3
    4       2         Project 4-

表2

 sub-id  ref-id    log_stamp      Recepient      log_type
    ----------------------------------------------------
    1     1       06/06/2011     person A       1
    1     1       06/14/2011     person B       2
    1     1       06/16/2011     person C       2
    1     1       06/17/2011     person D       3
    2     1       06/18/2011     person E       2
    2     1       06/19/2011     person F       2

    3     2       06/20/2011     person G       1
    4     2       06/23/2011     person H       3

结果

Name        ref-id    start_date    Recepient     latest_comment Recepient completion_date  Receipient
Project1    1         06/06/2011    person A      06/19/2011     person F      06/17/2011   person D
Project3    2         06/20/2011    person G      NULL           NULL          06/23/2011   person H
  

log_type为1代表start_date   log_type为2代表   latest_comment log_type of 3 stand   对于completion_date我们需要   日期列中的max_date   显示每个log_type。名字   该项目的名称只是   同一组中最顶层的名字   ref-id现在试过这个

1 个答案:

答案 0 :(得分:1)

对于SQL Server 2005 +:

WITH cteMaxDates AS (
    SELECT sub_id, ref_id, log_type, MAX(log_stamp) AS MaxDate
        FROM Table2
        GROUP BY sub_id, ref_id, log_type
),
cteRecipient AS (
    SELECT md.sub_id, md.ref_id, md.log_type, md.MaxDate, t2.Recipient
        FROM cteMaxDates md
            INNER JOIN Table2 t2
                ON md.sub_id = t2.sub_id 
                    AND md.ref_id = t2.ref_id
                    AND md.log_type = t2.log_type
                    AND md.MaxDate = t2.log_stamp
)
SELECT t1.Name, t1.ref_id, 
       start.MaxDate AS start_date,
       start.Recipient AS start_recipient,
       comment.MaxDate AS latest_comment,
       comment.Recipient AS comment_recipient,
       complete.MaxDate AS completion_date,
       complete.Recipient AS completion_recipient
    FROM Table1 t1
        LEFT JOIN cteRecipient start
            ON t1.sub_id = start.sub_id
                AND t1.ref_id = start.ref_id
                AND start.log_type = 1
        LEFT JOIN cteRecipient comment
            ON t1.sub_id = comment.sub_id
                AND t1.ref_id = comment.ref_id
                AND comment.log_type = 2
        LEFT JOIN cteRecipient complete
            ON t1.sub_id = complete.sub_id
                AND t1.ref_id = complete.ref_id
                AND complete.log_type = 3