代码之家  ›  专栏  ›  技术社区  ›  Mongus Pong

筛选出所有列都=一个值的行的最整洁的方法

  •  1
  • Mongus Pong  · 技术社区  · 16 年前

    select * from table
    where 
    not
    ( column1 = 0 and
      column2 = 0 and
      column3 = 0 and
      ...
      column45 = 0)
    

    这真的是最整洁的方法吗?

    假设我需要在所有列都为1或负数时将其更改为忽略。。这是大量的剪贴画。。

    6 回复  |  直到 16 年前
        1
  •  1
  •   tvanfosson    16 年前

    您可以参数化查询并将其放入存储过程或表值函数中。您只需要将查询写入固定的次数(每个操作类型一次),而不必考虑您选择的值。

    create function dbo.fn_notequal_columns
    (
        @value int
    )
    returns table
    as
    (
        select * from [table]
        where column1 <> @value and column2 <> @value ...
    )
    
    select * from dbo.fn_notequal_columns(0)
    
        2
  •  3
  •   George Mastros    16 年前

        3
  •  1
  •   gbn    16 年前

    你可以用校验和。但是,我不知道校验和的内部结构,所以不能保证它能在大型数据集上工作。

    CREATE TABLE dbo.FooBar (
        keyCol int NOT NULL IDENTITY (1, 1),
        col1 int NOT NULL,
        col2 int NOT NULL,
        col3 int NOT NULL
        )
    
    INSERT FooBar (col1, col2, col3)
    SELECT -45, 0, 45
    UNION ALL
    SELECT 0, 23, 0
    UNION ALL
    SELECT 0, 0, 0
    UNION ALL
    SELECT 1, 0, 0
    
    SELECT
       CHECKSUM(col1, col2, col3)
    FROM
       dbo.FooBar
    
    SELECT
       *
    FROM
       dbo.FooBar
    WHERE
       CHECKSUM(col1, col2, col3) = 0
    
        4
  •  1
  •   Jonathan Leffler    16 年前

    (1) 你在条件中有错误的连接词-你需要与否和。

    (2) 如果你有45列需要过滤,你将很难做得比你写的更好。虽然痛苦。。。

    这一观点仍然正确。

        5
  •  0
  •   Aaron Bertrand    16 年前

    您可以添加一个计算列来为您进行计算。从技术上讲,它并不是更整洁的,只是现在当您在任何查询中使用它时,您只需要检查计算列,而不是重复计算。

    CREATE TABLE dbo.foo
    (
        col1 INT,
        col2 INT,
        col3 INT,
        all_0 AS
        (
            CONVERT(BIT, CASE 
                WHEN col1 = 0 AND col2 = 0 AND col3 = 0 
                THEN 1 ELSE 0 
            END)
        )
    );
    

    你也可以做一些稍微整洁的事情,比如:

    WHERE col1 + col2 + col3 = 0 -- or 45, if there are 45 such columns
                                 -- and you are looking for each column = 1
    
        6
  •  0
  •   Leslie    16 年前

    SELECT all other fields, 'Column1', COL1 FROM tableName
    UNION
    SELECT all other fields, 'Column2, COL2 FROM TableName
    UNION ...
    SELECT all other fields, 'Column45', COL45 FROM tableName

    推荐文章