SQL Query group by

时间:2011-05-26 07:36:42

标签: sql oracle plsql oracle10g

粘贴当前正在使用的sql查询,以从unix shell脚本生成报告。我想在下面的sql查询中添加一个COUNT(cdw.file_id)writeoffcnt列,显示 与mg_disp_status = 0和mig_disp_code = 3匹配的记录的计数。 现有字段COUNT(cdw.file_id)cnt应该具有匹配的记录计数  mg_disp_status = 1和mig_disp_code<> 2.我该如何修改查询?

 SELECT fs.file_id,
                 fs.file_id_serv,
                 fs.file_process_dt,
                 fs.file_name,
                 fs.total_records,
                 RTRIM (d.description_text) source,
                 SUM(amount),
                 COUNT (cdw.file_id) cnt
            FROM file_status fs,
                 dr_data_work cdw,
                 descriptions d,
                 contacts ec
           WHERE file_process_dt >= TO_DATE ('${START_DATE}', 'DD-MON-YYYY')
                 AND  file_process_dt < TO_DATE ('${END_DATE}', 'DD-MON-YYYY')
                 AND fs.ext_contact_id = ec.ext_contact_id
                 --
                 AND ec.description_code = d.description_code
                 AND cdw.file_id = fs.file_id
                 AND mg_disp_status = 1
                 AND mig_disp_code <> 2
        GROUP BY fs.file_id,
                 fs.file_id_serv,
                 fs.file_process_dt,
                 fs.file_name,
                 fs.total_records,
                 RTRIM (d.description_text);

2 个答案:

答案 0 :(得分:3)

我并不完全了解您的所有要求排列,但以下内容应该有效:

SELECT
.
.
.
SUM(CASE mg_disp_status=0 and mig_disp_code =3 THEN 1 ELSE 0 END) cnt1,
SUM(CASE mg_disp_status=1 and mig_disp_code <> 2 THEN 1 ELSE 0 END) cnt2,

答案 1 :(得分:0)

使用不同的别名加入两次并完成您的计数:

SELECT fs.file_id,
             fs.file_id_serv,
             fs.file_process_dt,
             fs.file_name,
             fs.total_records,
             RTRIM (d.description_text) source,
             SUM(amount),
             COUNT (cdw.file_id) cnt1, COUNT (cdw2.file_id) cnt2
        FROM file_status fs,
             dr_data_work cdw, dr_data_work cdw2,
             descriptions d,
             contacts ec
       WHERE file_process_dt >= TO_DATE ('${START_DATE}', 'DD-MON-YYYY')
             AND  file_process_dt < TO_DATE ('${END_DATE}', 'DD-MON-YYYY')
             AND fs.ext_contact_id = ec.ext_contact_id
             --
             AND ec.description_code = d.description_code
             AND cdw.file_id = fs.file_id AND cdw2.file_id = fs.file_id
             AND cdw.mg_disp_status = 1 AND cdw2.mg_disp_status = 0 
             AND cdw.mig_disp_code <> 2 AND cdw2.mg_disp_code = 3



    GROUP BY fs.file_id,
             fs.file_id_serv,
             fs.file_process_dt,
             fs.file_name,
             fs.total_records,
             RTRIM (d.description_text);