我需要查询帮助,并开发了简短的例子。
Table1
-------------------------------
ref-id Name
1 Project 1
Table2
---------------------------
ref-id log_stamp log_type
1 06/06/2011 1
1 06/14/2011 2
1 06/15/2011 2
1 06/16/2011 2
1 06/18/2011 3
------------------------------------------------------
Result
--------------------------------------------------------
ref-id start_date latest_comment completion_date
1 06/06/2011 06/16/2011 06/18/2011
So we join Table1 with table2 on ref-id column.
Log_type of 1 - links to start_date
Log_Type of 2 - links to comments...we get the latest date for log_type of 2
Log_type of 3 - link to completion date.
答案 0 :(得分:1)
你可以转动;
;with T as (select
Table1.[ref-id],
log_stamp,
case log_type
when 1 then 'start_date'
when 2 then 'latest_comment'
when 3 then 'completion_date'
end as title
from
Table1 inner join Table2 on Table1.[ref-id] = Table2.[ref-id]
)
select * from T
pivot (
max(log_stamp)
for title IN ([start_date],[latest_comment],[completion_date])
) pvt
答案 1 :(得分:0)
执行三个单独的查询,每个日志类型一个,并将它们组合在一起。您可以使用虚拟占位符列,以使数据类型对齐。
答案 2 :(得分:0)
类似的东西:
select ref_id,
startdate.log_stamp as start_date,
max(comment.log_stamp) as latest_comment,
completeddate.log_stamp as completion_date
from table1 t,
table2 startdate,
table2 comment,
table2 completeddate
where startdate.ref_id = t.ref_id
and comment.ref_id = t.ref_id
and completed_date.ref_id = t.ref_id
and startdate.log_type = 1
and comment.log_type = 2
and completeddate.log_type = 3
group by
ref_id,
startdate.log_stamp,
completeddate.log_stamp
如果这些值并非总是存在,您可能需要在completeddate上进行外部联接并发表评论......