仅当总行数等于具有特殊 ID 的行数时才选择计数值
我需要选择具有特定 ID 的总行数 IF 它等于表中的总最大行数。
我在此示例中使用变量,但我想仅使用一个 select 语句来完成此
DECLARE @a int, @b int
--total with special field (redcar = yes)
SELECT @a = (SELECT COUNT(*) FROM dbo.car WHERE redcar = 'yes')
-- max total of table
SELECT @b = (SELECT COUNT(*) FROM dbo.car)
IF(@a = @b)
BEGIN
SELECT @a
END
操作 dbo.car
id redcar
1 yes
2
3 yes
4
5
6
输出应该为 0,因为红色汽车不等于表的总行数
I need to select the the total number of rows with a certain ID IF it equals the total max rows in table.
I am using variables in this example, but I would like to do it with only one select statement
DECLARE @a int, @b int
--total with special field (redcar = yes)
SELECT @a = (SELECT COUNT(*) FROM dbo.car WHERE redcar = 'yes')
-- max total of table
SELECT @b = (SELECT COUNT(*) FROM dbo.car)
IF(@a = @b)
BEGIN
SELECT @a
END
EXAMPLE
dbo.car
id redcar
1 yes
2
3 yes
4
5
6
The output should be 0 because red car doesn't equal total row count of table
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我能想到的最快的方法:
既然你想返回所有行,这只是检查是否有任何行不满足你的条件,如果是的话,它应该返回 0 或什么都不返回。
The fastest way I can think of:
Since you want to return all rows, this just checks if any rows don't meet your condition, and if so it should return 0 or nothing.
这应该可以解决问题:
This should do the trick:
我认为你可以做这样的事情:
或者这样:
但是你为什么想要一个查询?使用像代码这样的变量更容易阅读。
I think you could do something like this:
or this:
But why do you want one query? Doing with variables like your code is much more easy to read.
如果匹配的行数与总行数不同,您可以使用
case
返回0
:这将返回包含
0
的一行如果不满足条件。if
语句根本不会返回任何行集。您可能需要调整客户端代码来解决此问题。You could use a
case
to return0
if the matched row count is different from the total number of rows:This will return one row with
0
if the condition is not met. Theif
statement would return no rowset at all. You might have to adjust the client code to account for this.