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

时间:2016-07-21 17:49:04

标签: mysql sql-server

想象一下,我有一个包含以下列的审计表:

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  

是否有一个sql命令允许我只选择工作日/工作日_old中数据不同,或者周末/周末_old不同,或者(工作日/工作日_周末/周末/周末时间)不同的行并替换与null相同的列中的值?

因此,使用上表,我希望返回以下内容

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  

这可能听起来很疯狂,但我们尝试用我们所拥有的工具做我们所要求的事情。期待任何帮助。谢谢。

**我从结果表中删除了week4。这是错字。

2 个答案:

答案 0 :(得分:1)

您描述的内容与您的样本不匹配(为什么将选择week4并且不为null)。假设这是一个错字:

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;

答案 1 :(得分:0)

您可以使用{/ 1}}表达式

CASE