简体   繁体   English

MSSQL-只能选择一行中具有不同值的列

[英]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? 是否有一条sql命令可以让我仅选择在weekday / weekday_old中的数据不同,或Weekend / weekend_old中的数据不同,或(在Weekday / weekday_old和Weekend / weekend_old时)不同的行并替换与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. 谢谢。

**I removed week4 from results table. **我从结果表中删除了第4周。 It was typo. 这是错别字。

What you described doesn't match your sample (why would week4 selected and is not null). 您描述的内容与您的样本不匹配(为什么选择week4并且不为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;

您可能可以使用CASE表达式,例如

CASE WHEN weekday =  weekday_old THEN NULL ELSE weekday END AS weekday

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM