問題描述
作為復(fù)雜聚合的一部分,我想知道一些數(shù)據(jù)的按位總和,即如果我有值為 1,1,1,2,2,8 的行,按位 sum 是 11.在這種情況下,這些值都是 2 的精確冪(單個位),因此我可以通過對組進行分組和求和來繞過它(顯然,與實際查詢相比,這個示例有點受折磨)):
As part of a complex aggregate I want to know the bitwise sum of some data, i.e. if I have rows with values 1,1,1,2,2,8 the bitwise sum is 11. In this case the values are all exact powers of two (single bits), so I can hack around it by grouping and summing over the groups (obviously this example is a bit tortured compared to the real query):
select SUM(y.test)
from (
select x.test
from ( -- garbage test data
select 1 as [test]
union all select 1
union all select 1
union all select 2
union all select 2
union all select 8) x
group by x.test) y
但是有沒有一種干凈的方法可以在 [T]SQL 中執(zhí)行按位求和?
but is there a clean way to perform a bitwise sum in [T]SQL?
推薦答案
如果您的所有測試值都是單個位,如您的示例 (1, 2, 8) - 只需使用 SUM(DISTINCT col)
在您的查詢中.
If all of your test values are single bits as in your example (1, 2, 8) - simply use SUM(DISTINCT col)
in your query.
希望有所幫助.
(參考:http://msdn.microsoft.com/en-us/library/ms187810.aspx)
這篇關(guān)于執(zhí)行按位求和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!