SQL 用计数更新多列

SQL Update Multiple columns with counts

我们目前有 SQL 更新语句可以满足我们的需要并更新 tbl_rprt table。下面是一些更新查询,还有其他几个类似的查询。我想知道是否有另一种方法可以完成此操作,也许可以将所有这些组合成一个 SQL 语句。 #tbl_rprtwrk_tbl_flgs 中每个 class 和房间 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

更新 wrk_tbl_flgs 有 student_id 和特定标志

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

就目前而言,您可以使用如下条件和来合并为一个:

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;