错误地计算列SQL

时间:2013-12-09 11:55:24

标签: sql sql-server count

我遇到问题,为什么我正在编写的查询正在计算页面的整体视图而不是每个组织,它应该是19和8,但是当我运行查询时它出现为27页面查看每个查询的其余部分似乎工作正常。有谁知道为什么?谢谢 托马斯

SELECT orgID, orgName, 
    (SELECT COUNT (rvSessionKey)
    FROM tblReport
        LEFT OUTER JOIN tblReportView  ON rptID = rv_rptID
    WHERE rpt_orgID IN (1002,1047)  
            AND rvEmail NOT LIKE '%support%' 
            AND rpt_qtrID IN (1)) AS [Page View],
    COUNT( DISTINCT rvSessionKey ) AS [Views], COUNT(DISTINCT rsShareKey) AS [Users],   
    ISNULL(ROUND(AVG(CAST(pfRating AS FLOAT)), 1), 0)  AS [Avg Page Rating] 
FROM tblReport 
     LEFT OUTER JOIN tblReportView  ON rptID = rv_rptID
     INNER JOIN tblReportShare ON rs_rptID = rptID
     LEFT OUTER JOIN tblPageFeedback ON pfEmail = rsEmail
     INNER JOIN PMaster.dbo.tblOrganisation ON orgID = rpt_orgID
WHERE rvEmail NOT LIKE '%support%' 
    AND orgID IN (1002,1047) 
    AND rpt_qtrID IN (1) 
    AND rvPage NOT LIKE 'Arts'
GROUP BY orgID, orgName
ORDER BY orgName

2 个答案:

答案 0 :(得分:2)

您可能想出一种不必执行子查询的方法,但为了使其工作,您必须在[Page View]子查询的orgID和主查询中的orgID之间添加相关性。由于您没有为所有列名设置别名,因此有点难以给您一个完整的示例,但[Page View]子查询中的类似内容应使其有效:

SELECT COUNT (rvSessionKey)
FROM tblReport tt
LEFT OUTER JOIN tblReportView  ON rptID = rv_rptID
WHERE rpt_orgID IN (1002,1047)  
  AND tt.rpt_orgID = tblReport.orgID --Correlation to the outside query
  AND rvEmail NOT LIKE '%support%' 
  AND rpt_qtrID IN (1)) AS [Page View],

答案 1 :(得分:1)

完全删除子查询。 COUNT(rvSessionKey)将为您提供分组组织所选集合中的条目数。我猜这会给你页数,而COUNT(DISTINCT rvSessionKey)会给你一些会话数:

SELECT orgID, orgName, 
    COUNT (rvSessionKey) AS [Page View],
    COUNT( DISTINCT rvSessionKey ) AS [Views], 
    COUNT(DISTINCT rsShareKey) AS [Users],   
    ISNULL(ROUND(AVG(CAST(pfRating AS FLOAT)), 1), 0)  AS [Avg Page Rating]
FROM
    .......