Tags
bitwise puzzle, bitwise sql puzzle, Complex SQL Challenges, Complex TSQL Challenge, Interview Qs.SQL SERVER Questions, Interview questions on Joins, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Joins, Joins Interview questions, Joins Puzzle, Learn complex SQL, Learn SQL, Learn T-SQL, msbi skills, msbiskills.com, Objective Puzzle, PL/SQL Challenges, Puzzles, Queries for SQL Interview, SELECT Puzzle, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL Joins, SQL pl/sql puzzles, SQL Puzzles, SQL Queries, SQL SERVER Interview questions, SQL Skills, SQL Sudoku, SQLSERVER, T SQL Puzzles, T-SQL Challenge, The Bitwise AND Puzzle, Tough SQL Challenges, Tough SQL Puzzles, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries
T-SQL Query | [ The Bitwise AND Puzzle ]
Puzzle Statement
1. We have a table named BitwiseAnd.
2. Here we have Id and Value columns, now iwe have group by column Id and Bitwise AND all the values in that group Id.
3. For Id = 1 there are three values so we have calculate the Bitwise And like 10 & 1 & 13 ; Output for this is 2
4. For details please check out the sample input and expected output
Sample Input
Id | Value |
1 | 10 |
1 | 3 |
1 | 14 |
3 | 13 |
4 | 1 |
4 | 12 |
Expected Output
Id | Bitwise |
1 | 2 |
3 | 13 |
4 | 0 |
Rules/Restrictions
- Your solution should be should use “SELECT” statement or “CTE”
- Your solution should be generic in nature.
- Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com
Script Use the below script to generate the source table and fill them up with the sample data.
—
CREATE TABLE BitwiseAnd ( Id INT ,Value INT ) GO INSERT INTO BitwiseAnd VALUES (1,10), (1,3), (1,14), (3,13), (4,1), (4,12) — |
Update May 14 | Solution
-- /************ SOLUTION 1 ****************/ ;WITH CTE AS ( SELECT * , ROW_NUMBER() OVER ( PARTITION BY Id ORDER BY %%Physloc%% ) rnk FROM BitwiseAnd ) ,CTE1 AS ( SELECT Id , Value final , rnk FROM CTE WHERE rnk = 1 UNION ALL SELECT c2.Id , c2.final & c1.Value final , c2.rnk + 1 FROM CTE1 c2 INNER JOIN CTE c1 ON c1.Id = c2.Id AND c1.rnk = c2.rnk ) SELECT x.Id , Final Bitwise FROM CTE1 x WHERE rnk = (SELECT MAX(rnk) FROM CTE1 y WHERE x.Id = y.Id ) ORDER BY Id -- |
Add a comment if you have any other solution in mind. We all need to learn.
Keep Learning
You must be logged in to post a comment.