0

我有这 2 个需要加入的 SQL 查询。

Query1(显示条目列表):

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 但不知道该怎么做。任何帮助是极大的赞赏。

4

2 回答 2

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;
于 2013-05-13T06:57:53.713 回答
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;
于 2013-05-13T06:54:54.780 回答