Skip to content
Advertisement

SQL Update Multiple columns with counts

We currently have SQL update statements that works for our needs and updates the tbl_rprt table. Below are some of the update queries, there are several others like them. I was wondering if there was another way to get this done, maybe combining all of them into one SQL statement. #tbl_rprt is a report of all the counts of specific flags in wrk_tbl_flgs for each class and room rm.

    UPDATE #tbl_rprt
    SET a_count = a.a_count
    FROM (SELECT COUNT(*) a_count, new_c1, new_c2 FROM wrk_tbl_flgs WHERE a_flg = 'Y' GROUP BY new_c1, new_c2) a
    WHERE a.new_c1 = #tbl_rprt.class AND a.new_c2 = #tbl_rprt.rm

    UPDATE #tbl_rprt
    SET b_count = a.b_count
    FROM (SELECT COUNT(*) b_count, new_c1, new_c2 FROM wrk_tbl_flgs WHERE b_flg = 'Y' GROUP BY new_c1, new_c2) a
    WHERE a.new_c1 = #tbl_rprt.class AND a.new_c2 = #tbl_rprt.rm

    UPDATE #tbl_rprt
    SET c_count = a.c_count
    FROM (SELECT COUNT(*) c_count, new_c1, new_c2 FROM wrk_tbl_flgs WHERE c_flg = 'Y' GROUP BY new_c1, new_c2) a
    WHERE a.new_c1 = #tbl_rprt.class AND a.new_c2 = #tbl_rprt.rm

    UPDATE #tbl_rprt
    SET d_count = a.d_count
    FROM (SELECT COUNT(*) d_count, new_c1, new_c2 FROM wrk_tbl_flgs WHERE d_flg = 'Y' GROUP BY new_c1, new_c2) a
    WHERE a.new_c1 = #tbl_rprt.class AND a.new_c2 = #tbl_rprt.rm

    UPDATE #tbl_rprt
    SET e_count = a.e_count
    FROM (SELECT COUNT(*) e_count, new_c1, new_c2 FROM wrk_tbl_flgs WHERE e_flg = 'Y' GROUP BY new_c1, new_c2) a
    WHERE a.new_c1 = #tbl_rprt.class AND a.new_c2 = #tbl_rprt.rm

Update wrk_tbl_flgs has student_id and specific flags

student_id, class, rm, a_flg, b_fl, c_flg ....

Advertisement

Answer

As it stands you can combine into one, using conditional sums as follows:

UPDATE R SET
    a_count = a.a_count
    , b_count = a.b_count
    --... repeat for all columns
FROM #tbl_rprt R
INNER JOIN (
    SELECT
        new_c1, new_c2
        , SUM(CASE WHEN a_flg = 'Y' THEN 1 ELSE 0 END) a_count
        , SUM(CASE WHEN b_flg = 'Y' THEN 1 ELSE 0 END) b_count
        --, ... repeat for all flags
    FROM wrk_tbl_flgs
    GROUP BY new_c1, new_c2
) a ON a.new_c1 = R.class AND a.new_c2 = R.rm;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement