MS SQL:查询多个表

时间:2015-09-08 13:35:04

标签: sql-server

考虑具有以下结构和条目的三个表:

project
-------
projectGuid | projectName | emailEmployer | emailEmployee
________________________________________________________
AB          | tiger       | xyz@mail.com  | NULL
CD          | snake       | NULL          | abc@mail.com


projectHistory
--------------
historyGuid | projectGuid | historyTimestamp | statusId
_______________________________________________________
ST          | AB          | 2015-08-11 15:18:09.047 | 1
UV          | AB          | 2015-08-16 15:20:10.100 | 2
WX          | CD          | 2015-07-12 15:04:03.018 | 1


status
------
statusId | statusDisplay
________________________
1        | created
2        | start

查询如何实现以下输出:

projectGuid | projectName | emailEmployer | emailEmployee | historyTimestamp | statusId | statusDisplay
_______________________________________________________________________________________________________
AB          | tiger       | xyz@mail.com  | NULL          | 2015-08-16 15:20:10.100 | 2 | start
CD          | snake       | NULL          | abc@mail.com  | 2015-07-12 15:04:03.018 | 1 | created

鉴于属性emailEmployer OR emailEmployee,我只想要项目的最后historyTimestamp

2 个答案:

答案 0 :(得分:1)

您可以使用CTEsubquery来执行此操作:

<强>子查询:

DECLARE @email varchar(255);

SELECT p.projectguid
    ,p.projectname
    ,p.emailEmployer
    ,p.emailEmployee
    ,ph.historyTimestamp
    ,ph.statusid
    ,s.statusDisplay
FROM project p
INNER JOIN (
    SELECT projectguid
        ,max(historyTimestamp) AS historyTimestamp
        ,max(statusid) AS statusid
    GROUP BY projectguid
    ) ph ON ph.projectguid = p.projectguid
INNER JOIN [status] s ON s.statusid = ph.statusid
WHERE (p.emailEmployer = @email OR p.emailEmployee = @email)

<强> CTE:

DECLARE @email varchar(255);

;with ph as
 (SELECT projectguid
        ,max(historyTimestamp)
        ,max(statusid) AS statusid AS historyTimestamp
    GROUP BY projectguid
  )
SELECT p.projectguid
    ,p.projectname
    ,p.emailEmployer
    ,p.emailEmployee
    ,ph.historyTimestamp
    ,ph.statusid
    ,s.statusDisplay
FROM project p
INNER JOIN ph ON ph.projectguid = p.projectguid
INNER JOIN [status] s ON s.statusid = ph.statusid
WHERE (p.emailEmployer = @email OR p.emailEmployee = @email)

答案 1 :(得分:0)

根据这一点,应该可以解决这个问题:

SELECT p.projectGuid
     , p.projectName
     , p.emailEmployer
     , p.emailEmployee
     , ph.historyTimestamp
     , s.statusId
     , s.statusDisplay
  FROM project p
  JOIN (SELECT projectGuid
             , MAX(historyTimestamp) AS historyTimestamp
             , MAX(statusId) AS statusId
          FROM projectHistory           
      GROUP BY projectGuid) ph
    ON p.projectGuid = ph.projectGuid
  JOIN status s
    ON ph.statusId = s.statusId
 WHERE (p.emailEmployer = @email OR p.emailEmployee = @email)

@email是电子邮件属性的参数。