0

我正在尝试获取至少在记录中授权的人的所有记录的计数。基本上,一条记录可以有多个与之关联的人。我想返回 Total Records 的计数、至少 1 人获得授权的 Authorized Records 总数,以及未授权与记录关联的人的 NotAuthorized 记录总数。一个人是否被授权每条记录或是否有 3 人被授权该记录并不重要,这应该在授权计数器上加 1。

当前查询为每条记录添加的每个人增加 Auth 和 Non auth,而不是每条记录增加一个。如果没有人被分配到也应该计入 Not Auth 的记录中。

SELECT Count(DISTINCT Record.RecordID) AS TotalRecords,
SUM(CASE WHEN People.PersonLevel = 1 THEN 1 ELSE 0 END) AS Authorized,
SUM(CASE WHEN People.PersonLevel <> 1 THEN 1 ELSE 0 END) AS NotAuthorized
FROM Record
LEFT OUTER JOIN RecordPeople ON Record.RecordID = RecordPeople.RecordID
LEFT OUTER JOIN People ON RecordPeople.PersonID = People.PersonID
4

1 回答 1

0

像这样的东西看起来很丑(未经测试),但应该更好。

由于您必须按记录求和(至少 1 个授权或未求和),我认为没有子查询就无法获得它...

SELECT
  COUNT(a.record) AS TotalRecords, 
  SUM(a.authorizedRecord), 
  SUM(a.nonAuthorizedRecord) FROM
    (SELECT
        r.RecordId AS record, 
        CASE WHEN SUM(CASE WHEN p.PersonLevel = 1 THEN 1 ELSE  0 END) >= 1 THEN 1 ELSE 0 END  AS authorizedRecord,
        CASE WHEN SUM(CASE WHEN COALESCE(p.PersonLevel, 0) <> 1 THEN 1 ELSE 0)>=1 THEN 1 ELSE 0 END AS nonAuthorizedRecord
     FROM Record r
     LEFT OUTER JOIN RecordPeople ON Record.RecordID = RecordPeople.RecordID
     LEFT OUTER JOIN People ON RecordPeople.PersonID = People.PersonID
     GROUP BY r.RecordId
     ) AS a
于 2012-06-28T15:12:41.840 回答