SQL子查询计数错误

时间:2016-05-06 00:48:20

标签: sql tsql

我有一个查询来查找每个员工生产的总数。当我运行查询时,outCount的结果是错误的。我不太确定我错了什么。任何建议都会很棒。

SELECT
  r1.RegionID,
  r1.rDate,
  r1.tCount,
  r1.sCount,
  r1.outCount,
  r1.cm,
  r1.sCalc + r1.oCalc + r1.tCalc + r1.cmCalc AS dayScore,
  r1.createPID
FROM (SELECT
  q1.RegionID,
  ROUND(q1.tCount * 0.363636364, 9) AS tCalc,
  ROUND(q1.sCount * 0.181818182, 9) AS sCalc,
  ROUND(q1.outCount * 0.090909091, 9) AS oCalc,
  ROUND(q1.cm * 0.363636364, 9) AS cmCalc,
  q1.rDate,
  q1.tCount,
  q1.sCount,
  q1.outCount,
  q1.cm,
  q1.createPID
FROM (SELECT
  q1.RegionID,
  q1.rDate,
  q1.tCount,
  q1.sCount,
  q1.outCount,
  q1.cm,
  q1.createPID
FROM (SELECT
  SecurityPrincipal.RegionID,
  CONVERT(NVARCHAR, Ticket.dtCreate, 107) AS rDate,
  COUNT(Ticket.ticketID) AS tCount,
  COUNT(SRO.SROID) AS sCount,
  COUNT(o.NoteID) AS outCount,
  COUNT(cm.NoteID) AS cm,
  Ticket.createPID
FROM CDOC.rpt.Ticket
LEFT OUTER JOIN CDOC.rpt.SRO
  ON SRO.ticketID = Ticket.ticketID
LEFT OUTER JOIN (SELECT
  Notes.NoteID,
  Notes.ticketID,
  Notes.noteCategoryID
FROM CDOC.rpt.Notes
WHERE Notes.noteCategoryID = '24') o
  ON o.ticketID = Ticket.ticketID
LEFT OUTER JOIN (SELECT
  Notes.NoteID,
  Notes.ticketID
FROM CDOC.rpt.Notes
WHERE Notes.noteSubCategoryID = '13'
OR Notes.noteSubCategoryID = '16'
OR Notes.noteCategoryID = '22') cm
  ON cm.ticketID = Ticket.ticketID
INNER JOIN CDOC.rpt.SecurityPrincipal
  ON SecurityPrincipal.pid = Ticket.createPID
GROUP BY CONVERT(NVARCHAR, Ticket.dtCreate, 107),
         SecurityPrincipal.RegionID,
         Ticket.createPID) q1) q1) r1

1 个答案:

答案 0 :(得分:1)

这个逻辑:

  COUNT(Ticket.ticketID) AS tCount,
  COUNT(SRO.SROID) AS sCount,
  COUNT(o.NoteID) AS outCount,
  COUNT(cm.NoteID) AS cm,

非常可疑。如果id不为null,则它们都将返回相同的值。请记住:count()计算非NULL值的数量。

我想你只想要COUNT(DISTINCT)

  COUNT(DISTINCT Ticket.ticketID) AS tCount,
  COUNT(DISTINCT SRO.SROID) AS sCount,
  COUNT(DISTINCT o.NoteID) AS outCount,
  COUNT(DISTINCT cm.NoteID) AS cm,