Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查询帮助-TSQL_Tsql - Fatal编程技术网

查询帮助-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

别再想了…紧张会消失的。。。当怀疑如何帮助…哲学是最好的工具:)对不起,我的修改是错误的,请放弃我的修改。你原来的帖子是正确的。我已经测试过了,它工作正常