Помогите с запросом - TSQL - PullRequest
0 голосов
/ 15 июня 2011

Мне нужна помощь с запросом и разработан короткий пример.

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.

Ответы [ 3 ]

1 голос
/ 15 июня 2011

Вы можете поворачиваться;

;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
0 голосов
/ 15 июня 2011

что-то вроде:

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

Вам может потребоваться внешнее объединение по завершенной дате и комментарий, если эти значения не всегда присутствуют ...

0 голосов
/ 15 июня 2011

Выполните три отдельных запроса, по одному для каждого типа журнала, и объедините их вместе.Вы можете использовать фиктивные столбцы-заполнители для выравнивания типов данных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...