| Author |
Topic |
|
hai
Yak Posting Veteran
84 Posts |
Posted - 2008-11-12 : 09:06:23
|
| declare @tbl1 table(id int, idname varchar(6))insert into @tbl1select 1, 'd/r-01' union allselect 2, 'd/r-02' union allselect 3, 'd/r-03' declare @tbl2 table(pk int, rowid int, id int)insert into @tbl2select 1, 1, 3 union allselect 2, 1, 2 union allselect 3, 1, 3 union allselect 4, 2, 2 union allselect 5, 1, 3 union allselect 6, 2, 2 union allselect 7, 2, 2 union allselect 8, 1, 3 union allselect 9, 4, 2 union allselect 10, 4, 1 union allselect 11, 4, 0 union allselect 12, 2, 2 union allselect 13, 2, 0select a.pk, a.rowid, a.id, b.idname from @tbl2 aleft join @tbl1 bon a.id=b.idorder by rowidpk rowid id idname1 1 3 d/r-032 1 2 d/r-023 1 3 d/r-038 1 3 d/r-035 1 3 d/r-036 2 2 d/r-027 2 2 d/r-0212 2 2 d/r-0213 2 0 NULL4 2 2 d/r-029 4 2 d/r-0210 4 1 d/r-0111 4 0 NULLhowever I want this result:pk rowid id idname1 1 3 d-032 1 2 d-023 1 3 d-038 1 3 d-035 1 3 d-036 2 2 r-027 2 2 r-0212 2 2 r-0213 2 0 r-024 2 2 r-029 4 2 r-0210 4 1 r-0111 4 0 r-02D assign only if id is not null from the groupR assign only if id is null from the group |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-11-12 : 10:05:57
|
| [code]select a.pk, a.rowid, a.id, CASE WHEN COALESCE(c.RecCnt,0)>0 THEN REPLACE(b.idname,'/r','') ELSE REPLACE(b.idname,'d/','')END AS idnamefrom @tbl2 aleft join @tbl1 bon a.id=b.idouter apply (select count(*) AS RecCnt from @tbl2 where rowid=a.rowid and b.idname IS NULL)corder by rowid[/code]didnt understand on what basis you decide values to be returned for idname in cases where its NULL though. |
 |
|
|
hai
Yak Posting Veteran
84 Posts |
Posted - 2008-11-12 : 10:59:48
|
| Hi Visak,How can I assign the max(c.RecCnt) to the same rowid?From your query:pk rowid id RecCnt idname1 1 3 0 r-032 1 2 0 r-023 1 3 0 r-038 1 3 0 r-035 1 3 0 r-036 2 2 0 r-027 2 2 0 r-0212 2 2 0 r-0213 2 0 5 NULL4 2 2 0 r-029 4 2 0 r-0210 4 1 0 r-0111 4 0 3 NULLI need to do this:pk rowid id RecCnt idname1 1 3 0 r-032 1 2 0 r-023 1 3 0 r-038 1 3 0 r-035 1 3 0 r-036 2 2 5 r-027 2 2 5 r-0212 2 2 5 r-0213 2 0 5 NULL4 2 2 5 r-029 4 2 3 r-0210 4 1 3 r-0111 4 0 3 NULL----Again, thank you for your help. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-11-12 : 11:07:45
|
| [code]select a.pk, a.rowid, a.id,c.RecCnt, CASE WHEN COALESCE(c.RecCnt,0)>0 THEN REPLACE(b.idname,'/r','') ELSE REPLACE(b.idname,'d/','')END AS idnamefrom @tbl2 aleft join @tbl1 bon a.id=b.idouter apply (select count(*) AS RecCnt from @tbl2 a1 left join @tbl1 b1 on a1.id=b1.id where a1.rowid=a.rowid and b1.idname IS NULL)corder by rowid[/code] |
 |
|
|
|
|
|