如何用另一个表中的sum更新表?

时间:2016-09-19 02:30:13

标签: sql sql-server

我有3个表data_kabupaten,master_data和kampus

data_kabupaten
+--------------+----------+----------+---------+
|kota/kabupaten|perbulan  |j_penduduk|rata-rata|
+--------------+----------+----------+---------+
|makassar      |2016-06-31|          |         |
|makassar      |2016-07-31|          |         |
|makassar      |2016-08-31|          |         |
|...           |...       |          |         |
+--------------+----------+----------+---------+

master data                 kampus
+--------------+-------+    +---------+-------+
|kota/kabupaten|id_kota|    |nim      |kota_id|
+--------------+-------+    +---------+-------+
|makassar      |m012   |    |238011003|m012   |
|makassar      |m012   |    |...      |...    |
|makassar      |m012   |    +---------+-------+
|...           |...    |
+--------------+-------+

如何使用

更新我的data_kabupaten表
  

j_penduduk = count(distinct [nim])

2 个答案:

答案 0 :(得分:2)

使用以下查询。

    UPDATE kp
       SET kp.J_penduduk=t.cntNim
     FROM data_kabupaten kp
      JOIN master_data md 
        on kp.[kota/kabupaten] = md.[kota/kabupaten]
       JOIN (SELECT kota_id,Count( distinct Nim) CntNim
                  FROM Kampus k
                  GROUP BY kota_id)t
            On md.id_kota= t.kota_id

答案 1 :(得分:0)

;with cte as(
    select [kota/kabupaten], count(distinct nim) as CountNim from kampus as a
    inner join master_data as b on a.kota_id = b.id_kota
    group by [kota/kabupaten]
)
update data_kabupaten
    set j_penduduk = cte.CountNim
from cte
where data_kabupaten.[kota/kabupaten] = cte.[kota/kabupaten]

这里使用公用表表达式cte来获取每个[kota / kabupaten]值的不同计数。然后从cte。

更新data_kabupaten表