过滤掉所有列=一个值的行的最简洁方法
我有一个包含大量列的查询。我想选择并非所有列都等于 0 的行。
select * from table
where
not
( column1 = 0 and
column2 = 0 and
column3 = 0 and
...
column45 = 0)
这真的是最简洁的方法吗?
假设我需要将其更改为忽略所有列均为 1 或负值时..需要大量剪切和粘贴..
I have a query with loads of columns. I want to select rows where not all the columns are equal to 0.
select * from table
where
not
( column1 = 0 and
column2 = 0 and
column3 = 0 and
...
column45 = 0)
Is this really the tidiest way to do it?
Supposing I then need to change it to ignore when all columns are 1, or negative.. Its a lot of cut and paste..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
45 个单独的列似乎具有类似的含义。因此,我鼓励您正确规范化该表。如果这样做,查询会更简单并且性能可能会更好。
It appears as though the 45 individual columns have a similar meaning. As such, I would encourage you to properly normalize this table. If you did, the query would be simpler and would likely perform better.
您可以参数化查询并将其放入存储过程或表值函数中。无论您选择什么值,您只需要编写固定次数的查询(每个操作类型一次)。
You could parameterize the query and put it in a stored procedure or table-valued function. You'd only need to write the query a fixed number of times (once per operation type) regardless of the value(s) you choose.
您可以使用 CHECKSUM。但是,我不知道 CHECKSUM 的内部结构,因此不能保证它可以在大型数据集上工作。
You could use CHECKSUM. However, I don't know the internals of CHECKSUM so can't guarantee it would work over large datasets.
(1) 条件中的连接词有误 - 您需要 OR 而不是 AND。问题修改后,上述观察结果不再正确。
(2) 如果你有 45 列需要过滤,你将很难做得比你所写的更好。尽管很痛苦...
这一观察结果仍然正确。
(1) You have the wrong connective in the condition - you need OR and not AND.With the question amended, the observation above is no longer correct.
(2) If you have 45 columns that you need to filter on, you are going to be hard pressed to do any better than what you have written. Pain though it be...
This observation remains true.
您可以添加一个计算列来为您进行计算。从技术上讲,它并没有变得更整洁,只是现在当您在任何查询中使用它时,您只需检查计算列而不是重复计算。
如果您的数字以某种方式限制为 >= 0,您可以做一些稍微整洁的事情,例如:
You could add a computed column that does the calculation for you. It is not technically any tidier, except that now when you use it in any query you only have to check the computed column as opposed to repeating the calculation.
If your numbers are constrained in some way to be >= 0, you could do something slightly tidier, such as:
您可以创建规范化结构的视图并将其用作此查询的源:
选择所有其他字段,“Column1”,COL1 FROM tableName
联盟
选择所有其他字段,'Column2, COL2 FROM TableName
联盟...
选择所有其他字段,“Column45”,COL45 FROM tableName
you could create a view of a normalized structure and use that as your source for this query:
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