如何在1中合并2个查询

时间:2013-05-13 06:49:34

标签: sql sql-server sql-server-2008

我需要加入这两个SQL查询。

Query1(显示Entiries列表):

SELECT
  E.EntityId
  ,E.EntityNo 
  , E.Name
  , E.ShortName
FROM [xx].[xx].[Entities] E
WHERE
  E.Type = 'A'  
  AND E.YearEndMonth = 6

Query2(显示联系人列表):

SELECT P.Firstname,P.LastName, P.Email
FROM [xxx].[xx].[People] P
WHERE P.PeopleId= (
  SELECT TOP 1 A.PeopleId
  FROM [xxx].[xx].[EntityAttentions] A
  WHERE A.EntityId = ?
  ORDER BY A.EntityAttentionTypeId ASC
)

我的目标是提供实体和联系人的综合列表。

我试过这个但是有一个错误(当没有用EXISTS引入子查询时,只能在选择列表中指定一个表达式)

SELECT
  E.EntityId
  ,E.EntityNo 
  , E.Name
  , E.ShortName
  ,
  (SELECT P.Firstname,P.LastName, P.Email
  FROM [xxx].[xx].[People] P
  WHERE P.PeopleId= (
      SELECT  TOP 1 A.PeopleId
      FROM [xxx].[xx].[EntityAttentions] A
      WHERE A.EntityId = E.EntityId
      ORDER BY A.EntityAttentionTypeId ASC
      )
  )
FROM [xxx].[xx].[Entities] E
WHERE
  E.Type = 'A'  
  AND E.YearEndMonth = 6;

我想我必须使用某种JOIN,但不知道该怎么做。 非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

试试这个 -

SELECT
    E.EntityId
  , E.EntityNo 
  , E.Name
  , E.ShortName
  , P.*
FROM [xxx].[xx].[Entities] E
OUTER APPLY (
    SELECT P.Firstname,P.LastName, P.Email
    FROM [xxx].[xx].[People] P
    WHERE P.PeopleId = (
      SELECT TOP 1 A.PeopleId
      FROM [xxx].[xx].[EntityAttentions] A
      WHERE A.EntityId = E.EntityId
      ORDER BY A.EntityAttentionTypeId
    )
) P
WHERE E.Type = 'A'  
  AND E.YearEndMonth = 6;

答案 1 :(得分:1)

试试这个,

SELECT
  E.EntityId
  ,E.EntityNo 
  , E.Name
  , E.ShortName  
  , B.Firstname,B.LastName, B.Email
FROM [xxx].[xx].[Entities] E
CROSS APPLY
(     SELECT P.Firstname,P.LastName, P.Email
      FROM [xxx].[xx].[People] P
      WHERE P.PeopleId= 
        (
          SELECT  TOP 1 A.PeopleId
          FROM [xxx].[xx].[EntityAttentions] A
          WHERE A.EntityId = E.EntityId
          ORDER BY A.EntityAttentionTypeId ASC
        )
 ) B
WHERE
  E.Type = 'A'  
  AND E.YearEndMonth = 6;