Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform bitwise OR operation between two rows in same SQL table?

I have an SQL table with a structure similar to the following:

  Name     Value
(varchar)  (bit)
__________________
 Val1       1
 Val2       1
 Val3       0
 Val4       0
 Val1       0
 Val2       0
 Val3       0
 Val4       1

So basically, I have two instances of the same row but with a different bit value. I want to retrieve distinct rows from this table, with the bit value being OR'ed. So for the given example, the result would look like:

Name    Value

Val1      1    (1 | 0)
Val2      1    (1 | 0)
Val3      0    (0 | 0)
Val4      1    (0 | 1)

Can this be achieved? I am working in Microsoft SQL Server 2012. Any kind of help is appreciated. Please do let me know if any further clarification is required.

like image 476
Prashant Tiwari Avatar asked Dec 28 '25 16:12

Prashant Tiwari


2 Answers

Observing that "bitwise OR" has the same function as the aggregate function MAX (assuming all inputs are either 0 or 1, if any input is 1, the result is 1, otherwise 0) and accounting for the fact that we can't directly aggregate bit, this seems to work:

declare @t table (Name varchar(17) not null,Value bit not null)
insert into @t(Name,Value) values
('Val1',1),
('Val2',1),
('Val3',0),
('Val4',0),
('Val1',0),
('Val2',0),
('Val3',0),
('Val4',1)

select Name,CONVERT(bit,MAX(CONVERT(int,Value))) as Value
from @t group by Name
like image 159
Damien_The_Unbeliever Avatar answered Dec 30 '25 06:12

Damien_The_Unbeliever


You can try this, hoping that value is numeric field with values 0 and 1.

SELECT Name, MAX(Value)
FROM [table]
GROUP BY Name
like image 42
Kiran Hegde Avatar answered Dec 30 '25 06:12

Kiran Hegde