简体   繁体   中英

In SQL Joins - one to many select one column multiple times based upon context

I have two tables, one containing records, and one logging date time stamps on when operations have been performed. Example:

CREATE TABLE MyRecord(
  RecNumber INT IDENTITY(1,1) PRIMARY KEY
  ,TaskDetail NVARCHAR(200)
)

CREATE TABLE MyLOG(
  LogID INT IDENTITY(1,1) PRIMARY KEY
  ,DTStamp DATETIME2(2)
  ,TaskName NVARCHAR(10)
  ,RecNumber
  ,FOREIGN KEY ( RecNumber ) references MyRecord(RecNumber ) 
)

So for example if I had

|RecNumber|TaskDetail
| 1       | Some Task

|LogID|DTStamp                |TaskName  |RecNumber|
| 1   | 2014-11-11 00:00:00.00|StartTask | 1       |
| 2   | 2014-11-11 00:01:00.00|EndTask   | 1       |

I would like a query to return:

|RecNumber|TaskDetail| Start Time             | End Time              |
| 1       | Some Task| 2014-11-11 00:00:00.00 | 2014-11-11 00:01:00.00|

Now I know I could do this with nested select statements to get the start and end time. Using a join I could get the start time OR the end time. How do I get both without using nested SQL? OR - is nested select statements the best way to do this?

Maybe I am going about this all wrong.

Another way is conditional aggregation:

select r.recnumber,
       r.taskdetail,
       max(case when l.taskname = 'StartTask' then l.dtstamp end) as start_time,
       max(case when l.taskname = 'EndTask' then l.dtstamp end) as end_time
  from myrecord r
  join mylog l
    on r.recnumber = l.recnumber
group by r.recnumber,
         r.taskdetail

You can do this in various ways. Here is a way just using join s, assuming there is at most one matching row of each type:

select r.*, ls.DTStamp as StartTask, le.DTStamp as EndTask
from MyRecord r left join
     MyLog ls
     on r.recNumber = ls.recNumber and ls.TaskName = 'StartTask' left join
     MyLog le
     on r.recNumber = le.recNumber and le.TaskName = 'EndTask;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM