Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
A single table with each row almost duplicated so there are two consecutive rows, only one of which needs to be shown under certain cicumstances. Hard to explain...

Column values:
A  X  X  DT    X
B  X  X  null  X


and so on, repeating the "paired" rows.

Is it possible, using just SQL, to

Return row A if the fourth value is null in row B,
Return row B if the fourth value is not null and NOT return row A no matter what the value,
Return both rows if the fourth values are null in both.

Can it be done on the server, or will I have to diddle with it on the client side?
Posted

You don't say what database. You also don't say if you have a primary key or which columns match between row A and row B. It makes it hard to come up with an exact solution. Here is a solution (not completely tested) that works in SQL server assuming that you can detect paired rows by columns 2, 3, and 5 matching and that column 1 is your primary key. If this is not the case, your only option may be "diddling with the client side".

with t1 as
(
select a.column1 as acol1, b.column1 as bcol1, a.column2, a.column3, a.column4 as acol4, b.column4 as bcol4, a.column5
from tab a inner join tab b on a.column2 = b.column2 and a.column3 = b.column3 and a.column5 = b.column5 and a.column1 < b.column1
)
--Return Row A if B is null no matter what A is.
select acol1, column2, column3, acol4, column5
from t1
where bcol4 is null
UNION ALL
--Add Row B when A is null
select bcol1, column2, column3, bcol4, column5
from t1
where acol4 is null and bcol4 is null
UNION ALL
--Add all row B's with a value
select bcol1, column2, column3, bcol4, column5
from t1
where bcol4 is not null
 
Share this answer
 
v6
Comments
GenJerDan 19-Aug-11 20:06pm    
MSSQL 2005, No primary key (it would be a combination of multiple columns if I could do it...but I don't own it). As far as which columns match...all, except the one that can differ and one differentiating the rows. I can deal with that. Thanks. Can't try it until Monday, but I have a feeling you have a 5 in your future. :-)
Can it be done on the server, or will I have to diddle with it on the client side?

Yes it can be done with T-SQL
 
Share this answer
 
Comments
GenJerDan 19-Aug-11 15:27pm    
GIMME COD URG^H^H^H^H^H^H^H^H^H^H^H^H^H ;^)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900