Help with a query - TSQL
I am really struggling with the issue below and need some help...I have found few responses but not leading me the right way...
Table1
sub-id ref-id Name
1 1 Project 1
2 1 Project 2
3 2 Project 3
4 2 Project 4-
Table2
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
Result
Name ref-id start_date Recepient latest_comment Recepient completion_date Receipient
Project1 1 06/06/2011 person A 06/19/20开发者_开发技巧11 person F 06/17/2011 person D
Project3 2 06/20/2011 person G NULL NULL 06/23/2011 person H
log_type of 1 stands for start_date log_type of 2 stands for latest_comment log_type of 3 stands for completion_date we need to max_date in the date column to be displayed for each log_type. The Name of the project is just the name of the top-most name in the same group of ref-id have tried this for now
For 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
精彩评论