如何编写此查询以显示包含其他字段的COUNT

时间:2010-07-15 18:50:29

标签: sql

我有以下两个表:

Person {PersonId, FirstName, LastName,Age .... } 
Photo {PhotoId,PersonId, Size, Path}

显然,Photo表中的PersonId是一个引用Person表的FK。

我想写一个查询来显示一个人的所有字段,以及他/她在照片表中的照片数量。

结果的一行看起来像

24|Ryan|Smith|28|6

如何在tsql中编写这样的查询?

谢谢,

5 个答案:

答案 0 :(得分:3)

您需要一个子查询,以避免在group by子句中重复Person中的所有列。

SELECT
  p.PersonId,
  p.FirstName,
  p.LastName,
  p.Age,
  coalesce(ph.PhotoCount, 0) as Photocount
FROM
  Person p
  LEFT OUTER JOIN 
     (SELECT PersonId, 
      COUNT(PhotoId) as PhotoCount 
      FROM Photo 
      GROUP BY PersonId) ph
  ON p.PersonId = ph.PersonId 

答案 1 :(得分:2)

    SELECT 
       p.PersonId, 
       p.FirstName, 
       p.LastName, 
       p.Age,
       CASE WHEN 
            t.ThePhotoCount IS NULL THEN 0 ELSE t.ThePhotoCount END AS TheCount
       --the above line could also use COALESCE
   FROM 
       Person p 
   LEFT JOIN
         (SELECT 
             PersonId,
             COUNT(*)  As ThePhotoCount
         FROM 
             Photo 
         GROUP BY PersonId) t
    ON t.PersonId = p.PersonID

答案 2 :(得分:1)

SELECT P.PersonId, FirstName, LastName,Age, COUNT(PhotoId) AS Num
FROM Person P 
     LEFT OUTER JOIN PHOTO PH ON P.PersonId =  PH.PersonId
GROUP BY P.PersonId, FirstName, LastName,Age

答案 3 :(得分:0)

select Person.*, count(PhotoId) from Person left join Photo on Person.PersonId = Photo.PersonId

答案 4 :(得分:0)

IMO GROUP BY应该是解决方案,即使使用其他表连接,这样的东西也适用于我:

SELECT meetings.id, meetings.location, meetings.date, COUNT( users.id ) AS attendees
FROM  `meetings`
LEFT JOIN users ON meetings.id = users.meeting_id
WHERE meetings.moderator_id =  'XXX'
GROUP BY meetings.id