查询帮助-TSQL
我需要查询方面的帮助,并开发了简短的示例查询帮助-TSQL,tsql,Tsql,我需要查询方面的帮助,并开发了简短的示例 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
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.
执行三个单独的查询,每种日志类型一个,并将它们合并在一起。您可以使用虚拟占位符列,以便数据类型对齐。类似于:
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上进行外部联接,如果这些值不总是存在,则需要进行注释…您可以透视
;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
别再想了…紧张会消失的。。。当怀疑如何帮助…哲学是最好的工具:)对不起,我的修改是错误的,请放弃我的修改。你原来的帖子是正确的。我已经测试过了,它工作正常