有关汇总时对某个INT型字段进行或运算的问题

hulose 2004-08-26 10:00:10
哪位高手知道下面的如何解决啊
假如有表Z

X字段 Y字段
127 A
1 B
12 A
... ...

想办法检索出来是 127|12 等值按分组进行与运算

select 与运算的(X字段),y字段 from 表Z
group by y字段

有点类似SUM函数的功能
有谁知道啊,救命啊
...全文
119 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
realgz 2004-08-27
  • 打赏
  • 举报
回复
修正:
select max(0x1&x)+max(0x10&x)+max(0x100&x)+……max(0x10000000&x) as x ,--对每个位求得是否有1 ,如果是tinyint 则写到 0x10000000(8位),smallint 到 0x1000000000000000(16位),int 到 0x1000000000000000000000000(32 位)
y from tb_test
group by y
对于整型数据,最高位为符号位,所以用 + 并不严密,另 位运算比 加法运算 好象会更好(?),因此改成:
select
max(0x1 & x) | max(0x10 & x) | max(0x100 &x ) | ……max(0x10000000 & x) as x ,y from tb_test
group by y
要更科学。
zjcxc 2004-08-26
  • 打赏
  • 举报
回复
无论那种方法,都可以用 distinct X,Y 过滤掉重复的,因为重复的没有意义
zjcxc 2004-08-26
  • 打赏
  • 举报
回复
--看了冒牌的,原来是那个意思,如果是那样的话,用临时表,效率应该会好些吧

--测试数据
create table Z(X int,Y varchar(10))
insert Z select 127,'A'
union all select 1,'B'
union all select 12,'A'
go

--统计
select id=identity(int),X,Y into #t from Z order by Y
declare @Y varchar(10),@i int
update #t set @i=case @Y when Y then @i|X else X end
,X=@i,@Y=Y

select a.X,a.Y
from #t a,(select id=max(id) from #t group by Y)b
where a.id=b.id

drop table #t
go

--删除测试
drop table z

/*--测试结果

X Y
----------- ----------
127 A
1 B

(所影响的行数为 2 行)
--*/

realgz 2004-08-26
  • 打赏
  • 举报
回复
select in(x) | max(x) as x,y from tb_test
group by y
=
select min(x) | max(x) as x,y from tb_test
group by y
realgz 2004-08-26
  • 打赏
  • 举报
回复
如果只有两个:
select in(x) | max(x) as x,y from tb_test
group by y
如果多个:
select max(0x1&x)+max(0x10&x)+max(0x100&x)+……max(0x10000000&x) as x ,--对每个位求得是否有1 ,如果是tinyint 则写到 0x10000000(8位),smallint 到 0x1000000000000000(16位),int 到 0x1000000000000000000000000(32 位)
y from tb_test
group by y
--暂时没发现一句话的第3种写法
CSDMN 2004-08-26
  • 打赏
  • 举报
回复
你的例子不太好,看不出 or 的效果,因为127|12=127
CSDMN 2004-08-26
  • 打赏
  • 举报
回复
用自定义函数(效率差很多):

--建立环境
create table tb_test (
x int,
y char(2)
)
go
insert tb_test
select
127 as x, 'A' as y
union all select
1, 'B'
union all select
12, 'A'
go

--函数
create function f_Or
(
@y char(2)
)
returns int
as
begin
declare @r int
set @r=1
select @r=@r | x from tb_test where y=@y
return @r
end
go

--调用
select dbo.f_or(y) as x,y from tb_test
group by y

--结果
/*
x y
----------- ----
127 A
1 B

(所影响的行数为 2 行)


*/
zjcxc 2004-08-26
  • 打赏
  • 举报
回复
没看明白,说清楚点.
Andy__Huang 2004-08-26
  • 打赏
  • 举报
回复
進行與運算得到的結果是12嗎?

27,581

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧