MaxAx MaxAx - 3 months ago 6x
MySQL Question

MSSQL - Can select only columns in a row that have different values

Imagine, I have an audit table that contains the following columns:

id schedule weekday weekday_old weekend weekend_old
1 week1 m,t,w th,f sa,su sa,su
1 week2 m,t,w m,t,w sa,su sa,su
1 week3 m,t,w w,th,f sa,su sa
1 week4 m,t,w m,t,w sa,su sa,su
1 week5 m,t,w m,t,w sa,su sa,su
1 week6 m,t,w m,t,w sa su
1 week7 m,t,w m,t,w sa su

Is there a sql command(s) that will allow me to select only the rows where data in the weekday/weekday_old is different, or weekend/weekend_old is different, or (when weekday/weekday_old and weekend/weekend_old) is different and replace the values in columns that are same with null?

So, using the above table, I would like the following to be returned

week1 m,t,w th,f null null
week3 m,t,w w,th,f sa,su sa
week6 null null sa su
week7 null null sa su

This probably sounds crazy, but we try to do what we're asked with the tools we have. Looking forward to any help. Thank you.


What you described doesn't match your sample (why would week4 selected and is not null). Assuming it was a typo:

SELECT schedule, 
NULLIF(weekday,weekday_old) AS weekday,
NULLIF(weekday_old,weekday) AS weekday_old,
NULLIF(weekend,weekend_old) AS weekend,
NULLIF(weekend_old,weekend) AS weekend_old
 FROM dbo.mytable 
 WHERE NULLIF(weekday,weekday_old) IS NOT NULL or NULLIF(weekend,weekend_old) IS NOT NULL;