SQL Sum与group by无法正常工作

时间:2016-11-16 20:49:30

标签: sql oracle reporting-services

我正在编写Oracle SQL以获取详细报告和摘要报告。我的详细报告已完成,示例输出行将是:

  domain name, student name, completed

  Domain Name, Student Name, Y 
  Domain Name, Student Name, N

注意完成的列是“Y”或“N”。

问题在于我的总结报告。我按域名进行分组,并将详细报告列“已完成”的“Y”和“N”拆分为“完成”和“不完整”的摘要列。我将“Y”更改为1或0,将“N”更改为1或0,然后将每个列更改为SUM。

我的详细报告返回17k行,我的摘要报告返回174行但总和不正确。摘要报告的示例输出是三种类型之一:“域名,1,0”或“域名,1,1”或“域名,0,0”。这些行应该包含“Domain Name,254,110”等数字

任何有关代码的帮助或指导都将不胜感激。

SELECT inner_clause.dmn_id,
    SUM(decode(status_remday,'Y',1,0)) COMPLETED,
    SUM(decode(status_remday,'N',1,0)) INCOMPLETED
    FROM
    (SELECT DISTINCT q.qual_id,
        q.qual_title,
        s.dmn_id,
        SUBSTR(pkg_student.get_delm_stud_qual_stat_rmday(sq.stud_id, sq.qual_id, sq.qual_id),1,1) AS status_remday
        FROM pa_stud_qual sq,
            pa_student s,
            pa_user_preference userPref,
            pa_qual q
        WHERE sq.stud_id = s.stud_id
            AND s.stud_id = userPref.user_id(+)
            AND userPref.user_type(+)='S'
            AND sq.qual_id = q.qual_id
            /** and q.qual_id in [CurriculumSearch] */
            /** and s.stud_id in [UserSearch] */
            /** and s.notactive = [UserStatus] */
            /** and [security:pa_student s] */          
    ) inner_clause
GROUP BY inner_clause.dmn_id
ORDER BY inner_clause.dmn_id

1 个答案:

答案 0 :(得分:0)

内部子句需要DISTINCT结果的更多字段。最终的解决方案是:

SELECT inner_clause.dmn_id,
       inner_clause.qual_title,
       SUM(decode(status_remday,'Y',1,0)) AS COMPLET,
       SUM(decode(status_remday,'N',1,0)) AS INCOMPLET,
       COUNT(decode(status_remday,'Y',1,'N',1)) AS TOTAL,
       SYSDATE AS CURRENTDATETIME
       FROM
       (SELECT DISTINCT q.qual_id,
             q.qual_title,
             sq.stud_id,
             s.lname,
             s.fname,
             s.mi,
             s.dmn_id,
             sq.assgn_dte,
             sq.qual_id,
             NVL(userPref.preferred_timezone,pkg_state.get_default_timezone()) AS preferred_timezone,
             DECODE(S.NOTACTIVE,'Y','label.NotActive', 'N','label.Active') AS NOTACTIVE,
             s.email_addr,
             SUBSTR(pkg_student.get_delm_stud_qual_stat_rmday(sq.stud_id, sq.qual_id, sq.qual_id),1,1) AS status_remday
             FROM pa_stud_qual sq,
                    pa_student s,
                    pa_user_preference userPref,
                    pa_qual q
             WHERE sq.stud_id = s.stud_id
             AND s.stud_id = userPref.user_id(+)
             AND userPref.user_type(+) = 'S'
             AND sq.qual_id = q.qual_id
             /** and q.qual_id in [CurriculumSearch] */
             /** and s.stud_id in [UserSearch] */
             /** and s.notactive = [UserStatus] */
             /** and [security:pa_student s] */
             ORDER BY 1
       ) inner_clause     
GROUP BY inner_clause.dmn_id, inner_clause.qual_title
ORDER BY inner_clause.dmn_id