Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
new2sqlplus
Starting Member
1 Post |
Posted - 2014-05-18 : 21:49:36
|
My goal is to with one update statement, fill TABLE1.counter (currently empty) with the total count of TABLE2.e# (employee). Also, if TABLE1.e# isn't in TABLE2.e# then it sets it to "0" (TABLE1.e# 8 and 9 should have a counter of 0)This is for sqlplus.e.g. TABLE2:e#--12345567712345UPDATE TABLE1SET counter = ( SELECT COUNT(TABLE2.e#) FROM TABLE2 INNER JOIN TABLE1 ON (TABLE2.e# = TABLE1.e#) GROUP BY TABLE2.e#);--^Doesn't workso my TABLE1 should be:e# counter-----------1 .. 22 .. 23 .. 24 .. 25 .. 36 .. 17 .. 28 .. 09 .. 0(The .. is just spacing to show the table here) |
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2014-05-19 : 13:57:51
|
UPDATE t1SET [counter] = CASE WHEN t2.e# IS NOT NULL THEN t2.[counter] ELSE 0 ENDFROM TABLE1 t1LEFT JOIN (SELECT e#, COUNT(*) as [counter] FROM TABLE2 GROUP BY e#) t2ON t1.e# = t2.e#Tara KizerSQL Server MVP since 2007http://weblogs.sqlteam.com/tarad/ |
 |
|
|
|
|