Question

What script would return a table that amalgamates rows by ID in the following table and remove NULL values where an ID appears more than once. So for instance ID 3 appears twice and and ID 217 appears once and after the script is run below is how they would look The script has to be old school to be compatible with SQL2000. Thank you.

ID  PreOpOrg    PreOpTreatment      PostOpOrg   PostOpTreatment
3   RBA11           02              RBA11       06
217 NULL            NULL            RN325       02

and so on

ID      PreOpOrg    PreOpTreatment      PostOpOrg   PostOpTreatment
3       RBA11           02              NULL        NULL
3       NULL            NULL            RBA11       06
217     NULL            NULL            RN325       02
364     NULL            NULL            RBA11       02
369     NULL            NULL            RN325       02
481     GR123           05              NULL        NULL
834     RBA11           02              NULL        NULL
834     NULL            NULL            RBA11       04
1066    NULL            NULL            RBA11       05
2123    NULL            NULL            RBA11       05
2246    NULL            NULL            RBA11       02
2246    RBA11           02              NULL        NULL
2512    RBA11           04              NULL        NULL
2512    NULL            NULL            RBA11       06
2694    NULL            NULL            RN325       05
2892    NULL            NULL            RBA11       06
2892    RBA11           05              NULL        NULL
3311    RBA11           05              NULL        NULL
3311    NULL            NULL            RBA11       06
3344    RBA11           02              NULL        NULL
3362    RBA11           02              NULL        NULL
3770    RBA11           05              NULL        NULL
Était-ce utile?

La solution

You can do this as an aggregation:

select ID, max(PreOpOrg) as PreOpOrg, max(PreOpTreatment) as PreOpTreatment,
       max(PostOpOrg) as PostOpOrg, max(PostOpTreatment) as PostOpTreatment
from table t
group by id;

This works for the data you have provided, because only one field is populated. There is no danger of "losing" information in one of the columns, if this is true.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top