Question

It is really hard to find a good title for this.

Here is the question: I have a SELECT query GROUP BY a field which returns me up to three values (1,2,3). These values are representing the positions of '1' in a binary number. In other words:

Query Output    |     Reult
0,1,2           |      7 (111)
1,2             |      6 (110)
3               |      1 (001)
-               |      0 (000)

Ok, I know it is easy. But there are two constraints. First, I want a query not a function/store procedure. Second, the result should be a string (like '010') not the number.

I found the solution for integer value, but not the string (varchar)

SELECT COALESCE(sum(power(2, field)), 0) AS test FROM (
  SELECT field FROM  myTable GROUP BY field) a

I am using SQL server 2008, just in case.

I also have this solution, but this one cannot be extended to bigger number of outputs:

  SELECT output = 
  CASE TEST 
    WHEN  0 THEN '000'
    WHEN  1 THEN '001'
    WHEN  2 THEN '010'
    WHEN  3 THEN '011'
    WHEN  4 THEN '100'
    WHEN  5 THEN '101'
    WHEN  6 THEN '110'
    WHEN  7 THEN '111'
  END
  FROM(
  select COALESCE(sum(power(2, 3 - field)), 0) as test from (
  select field from myTable group by field) a) b
Was it helpful?

Solution

You can use binary and and string concatenation:

select (case when test&4 > 0 then '1' else '0' end) +
       (case when test&2 > 0 then '1' else '0' end) +
       (case when test&1 > 0 then '1' else '0' end)
from (select 6 as test) t;

If you are allergic to case statements, you could do this:

select CHAR(ascii(0) + (test&4)/4) +
       CHAR(ascii(0) + (test&2)/2) +
       CHAR(ascii(0) + (test&1)/1)
from (select 6 as test) t
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top