SQL函数显示基于其他列的值

时间:2018-10-12 19:50:37

标签: sql sql-server

我有一个包含5列的表。 Person ID, C11,c12,c13,c14。因此,我想编写一个选择Person ID的查询,仅在所有四个列都具有值的情况下选择C11 c12 c13 c14。如果存在C11,而C12null,则显示所有列null

下面是我有一个示例查询的restester链接。

https://rextester.com/YJG20854

有什么帮助吗?!

3 个答案:

答案 0 :(得分:4)

一种解决方案使用case

select person_id,
       (case when not (c11 is null or c12 is null or c13 is null or c14 is null)
             then c11 end),
       (case when not (c11 is null or c12 is null or c13 is null or c14 is null)
             then c12 end),
       (case when not (c11 is null or c12 is null or c13 is null or c14 is null)
             then c13 end ),
       (case when not (c11 is null or c12 is null or c13 is null or c14 is null)
             then c14 end)
from temp1;

这只是您查询的一个细微变化,已修复了一些语法问题。

一种更聪明的方法使用left join

select t1.person_id, null1.cl1, null1.cl2, null1.cl3, null1.cl4
from temp1 t1 left outer join
     temp1 null1
     on t1.person_id = null1.person_id and
        not (t1.c11 is null or t1.c12 is null or t1.c13 is null or t1.c14 is null);

或使用cross apply

select t1.person_id, null1.*
from temp1 t1 cross apply
     (select top (1) c11, c12, c13, c14
      from (values (c11, c12, c13, c14, 1), (null, null, null, null, 0)) v(c11, c12, c13, c14, ord)
      order by (case when c11 is null or c12 is null or c13 is null or c14 is null then 1 else 0 end), ord
     ) null1;

答案 1 :(得分:1)

您可以这样做:

select person_id,
    case when c11 + c12 + c13 + c14 is not null then c11 else null end c11,
    case when c11 + c12 + c13 + c14 is not null then c12 else null end c12,
    case when c11 + c12 + c13 + c14 is not null then c13 else null end c13,
    case when c11 + c12 + c13 + c14 is not null then c14 else null end c14
from person

或者这个:

select person_id,c11,c12,c13,c14
from person
where c11 + c12 + c13 + c14 is not null
union
select person_id,null,null,null,null
from person
where c11 + c12 + c13 + c14 is null

答案 2 :(得分:1)

SELECT * FROM temp1
WHERE c11 + c12 + c13 + c14 IS NOT NULL

UNION

SELECT person_id, NULL AS c11, NULL AS c12, NULL AS c13, NULL AS c14 
FROM temp1
WHERE c11 IS NOT NULL AND c12 IS NULL

输出:

1005  NULL NULL NULL NULL           
1001  NULL NULL NULL NULL           
1002     1    1    3    4