动态地将列传递给COALESCE

时间:2014-01-18 12:18:03

标签: sql sql-server coalesce

我需要COALESCE的一些帮助。

语法:COALESCE(Col1,Col2,Col3...)这意味着每次我必须将列名称作为参数写入。

我的问题我们可以动态地将列名传递给此函数吗?因为我的表格中的列数不断变化。

谢谢, SID

2 个答案:

答案 0 :(得分:0)

听起来你有很多列,你想要将值移到左边,将NULL移到右边。

您可以通过计算每个值之前的非NULL值的数量,然后使用case语句来分配值来执行此操作。以下显示了四列的代码:

select (case when col1_n = 1 then col1
             when col2_n = 1 then col2
             when col3_n = 1 then col3
             when col4_n = 1 then col4
        end) as col1,
       (case when col2_n = 2 then col2
             when col3_n = 2 then col3
             when col4_n = 2 then col4
        end) as col2,
       (case when col3_n = 3 then col3
             when col4_n = 3 then col4
        end) as col3,
       (case when col4_n = 4 then col4
        end) as col4
from (select t.*,
             (case when col1 is not null then 1 end) as col1_n,
             ((case when col1 is not not null then 1 else 0 end) +
              (case when col2 is not null then 1 end)
             ) as col2_n,
             ((case when col1 is not not null then 1 else 0 end) +
              (case when col2 is not null then 1 else 0 end) +
              (case when col3 is not null then 1 end)
             ) as col3_n,
             ((case when col1 is not not null then 1 else 0 end) +
              (case when col2 is not null then 1 else 0 end) +
              (case when col3 is not null then 1 else 0 end) +
              (case when col4 is not null then 1 end)
             ) as col4_n             
      from t
     ) t;

你可以在SQL Fiddle(here)看到这项工作。

如果每个用户都有一个唯一的id,您也可以取消数据的显示,使用row_number()并重新投放数据。

答案 1 :(得分:0)

如果您不想写列名称,请尝试执行此类操作 除了您指定的列(IgnoreThisColumn1& IgnoreThisColumn2)之外,当所有列值都为null时,这将显示所有行。

DECLARE @query NVARCHAR(MAX);

SELECT @query = ISNULL(@query+', ','') + [name] 
                FROM  sys.columns 
                WHERE object_id = OBJECT_ID('yourTableName') 
                AND  [name] != 'IgnoreThisColumn1' 
                AND  [name] !=  'IgnoreThisColumn2';

SET @query = N'SELECT * FROM TmpTable WHERE COALESCE('+ @query +') IS NULL';

EXECUTE(@query)

结果

Result One

如果除了指定的列之外所有列都为空时不想要行,则只需使用IS NOT NULL代替IS NULL

SET @query = N'SELECT * FROM TmpTable WHERE COALESCE('+ @query +') IS NOT NULL';

结果

[Result Two[2]