使用案例条款更新

时间:2018-08-10 20:04:49

标签: sql sql-server

如何在SQL Management Studio中使用基于SQL的以下查询,使用case子句执行更新:

SELECT 
CASE WHEN t1.building is null THEN 0
ELSE t1.building END AS Building,
t1.id, 
CASE WHEN t1.building is null THEN 0
ELSE t2.count END AS Count
FROM table t1
JOIN (SELECT building, COUNT(*) as count 
  FROM table 
  GROUP BY building) AS t2 ON t2.building = t1.building OR (t2.building is 
  null AND t1.building is null)

以下内容无效:

Update table
Set count=(Select count from table where count in( 
SELECT 
CASE WHEN t1.building is null THEN 0
ELSE t1.building END AS Building,
t1.id, 
CASE WHEN t1.building is null THEN 0
ELSE t2.count END AS Count
FROM table t1
JOIN (SELECT building, COUNT(*) as count 
  FROM table 
  GROUP BY building) AS t2 ON t2.building = t1.building OR (t2.building is 
  null AND t1.building is null))

我的目标是使用基于每个ID号原始查询的值来更新count列。

发件人:

ID  Building  Count
1    10        
2    10        
3    11        
4    11        
5    11        
6    Null      

所需结果:

ID  Building  Count
1    10        2
2    10        2
3    11        3
4    11        3
5    11        3
6    Null      0

1 个答案:

答案 0 :(得分:3)

您可以尝试将JOIN UPDATECASE WHEN一起使用

UPDATE t1
SET Count = CASE WHEN t1.Building IS NULL THEN 0 ELSE t2.cnt END
FROM T t1
LEFT JOIN (
  select Building,COUNT(Building) cnt
  from T
  GROUP BY Building
) t2 on t1.Building = t2.Building 

sqlfiddle