简体   繁体   English

t-SQL聚合逻辑

[英]t-SQL Aggregate Logic

Lets say we have a table with an ID and a bit column. 假设我们有一个带有ID和位列的表。 We execute a query that returns any number of rows (for this example with ID>5). 我们执行一个返回任意行数的查询(对于此示例,ID> 5)。 What I want to do is to have an AND aggregate operation across the results of the bit column. 我想要做的是在位列的结果上进行AND聚合操作。 I have figured out a workaround, but it's not pretty: 我找到了一个解决方法,但它并不漂亮:

SELECT 
CASE WHEN COUNT(ID) = SUM(CAST(isTrue AS INT)) THEN 1 ELSE 0 END AS areTrue
FROM Table
WHERE ID > 5

What I'm doing here, since there is no aggregate function to multiply the results, is practically comparing the total number of records with the sum of the integer representation of the bit column. 我在这里做的,因为没有聚合函数来乘以结果,实际上是将记录总数与位列的整数表示之和进行比较。 If they're equal, there are no 'falses', so it works as an AND operation between them. 如果它们相等,则没有“谬误”,所以它在它们之间作为AND操作。

An OR would be to get the MAX from the column, which is pretty straightforward. OR是从列中获取MAX,这非常简单。

The only problem is that this is particularly ugly and should be killed with fire. 唯一的问题是,这是特别难看,应该用火杀死。 Is there any elegant, proper, way to do this? 有没有优雅,正确的方法来做到这一点?

If you want to do logic on the bits, how about: 如果你想对这些位做逻辑,怎么样:

select max(cast(isTrue as int)) as AnyTrue,
       min(cast(isTrue as int)) as AllTrue,
       max(1 - cast(isTrue as int)) as AnyFalse,
       min(1 - cast(isTrue as int)) as AllFalse

You could achieve this by using a variable to store the calculation, for example: 您可以通过使用变量来存储计算来实现此目的,例如:

Declare @result bit = 1

SELECT @result = @result & isTrue 
FROM Table
WHERE ID > 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM