首页 > 解决方案 > 如何对标志 bigint 列设置的 T-SQL 进行分组

问题描述

我正在从事一个搜索功能的效率至关重要的项目。

我有几个标志列(如 c# 中的枚举标志)。搜索这些数据的速度非常快(往返 3 毫秒),但现在我必须进行组计数了。

所以,我有一个包含红色 (1)、白色 (8) 和蓝色 (64) 的项目“A”,因此“颜色”列包含数字 73。

要搜索,我可以用这个搜索带有红色的项目

Declare @colour int
set @colour = 1

Select * 
From Items  
Where (Colour & @colour) > 0

这很好用。现在我必须对它进行分组(也超级快)

因此,如果我总共有 8 个项目,5 个包含红色,3 个包含白色,7 个包含蓝色,结果将如下所示:

Colour      Qty
------------------
1           5
8           3
64          7 ( I don't have to worry about the name )

所以:有什么办法可以把数字 73 按位分成几组?

(第 2 部分:如何将其转换为 Linq to SQL?)

任何建议将不胜感激

谢谢^_^

标签: c#linqtsqlbitwise-operators

解决方案


好的 - 我想我已经找到了最好的解决方案:

我尝试了一个 cte 的视图:

with cte as (
  select cast(1 as bigint) as flag, 1 pow
  union all
  select POWER(cast(2 as bigint),pow), pow + 1
  from cte
  where flag < POWER(cast(2 as bigint),62)
)
, cte2 as (
  select flag from cte
  union select -9223372036854775808
)

但这太慢了,所以现在我把它变成了一个静态表。我加入了按位“&”:

select Flag, Count(*)
From FlagValues fv 
inner join Items i on (fv.Flag & i.Colour)

快很多^_^


推荐阅读