当前位置: 代码迷 >> Sql Server >> SQL 高手:位数操作
  详细解决方案

SQL 高手:位数操作

热度:37   发布时间:2016-04-27 13:38:01.0
SQL 高手请指教:位数操作
问题: 表 a 列有列userID,以及 SHIFT_CNTRL_NBR,int,相当于做‘位’的操作,有数值:
VALUE DESCRIPTION
 
1 相当于shift 1 Enabled
2 相当于Shift 2 Enabled 
3 相当于 Shift 1 & 2 Enabled
4 相当于Shift 3 Enabled
5 相当于Shift 1 & 3 Enabled
6 相当于Shift 2 & 3 Enabled
7 相当于Shift 1, 2, & 3 Enabled
通过此列的值,和另一个表shift匹配。 
shift 表
id shift_nbr 
1 1  
2 2
3 3
4 1
5 2
6 3
如果表a 的选出某一行为6,那么相当于取出shift 表的所有shift_nbr=2, 3 的记录。
如果表a 的选出某一行为7,那么相当于取出shift 表的所有shift_nbr=1,2, 3 的记录。
这个sql 怎么写啊,谢谢啦!


------解决方案--------------------
SQL code
--> 测试数据:[tbl]if object_id('[tbl]') is not null drop table [tbl]create table [tbl]([VALUE] int,[DESCRIPTION] varchar(30))insert [tbl]select 1,'相当于shift 1 Enabled' union allselect 2,'相当于Shift 2 Enabled' union allselect 3,'相当于Shift 1&2 Enabled' union allselect 4,'相当于Shift 3 Enabled]' union allselect 5,'相当于Shift 1&3 Enabled]' union allselect 6,'相当于Shift 2&3 Enabled]' union allselect 7,'相当于Shift 1,2&3 Enabled'--> 测试数据:[shift]if object_id('[shift]') is not null drop table [shift]create table [shift]([id] int,[shift_nbr] int)insert [shift]select 1,1 union allselect 2,2 union allselect 3,3 union allselect 4,1 union allselect 5,2 union allselect 6,3select * from [shift] where CHARINDEX(ltrim([shift_nbr]),(select [DESCRIPTION] from tbl where [VALUE]=4))>0/*id    shift_nbr3    36    3*/select * from [shift] where CHARINDEX(ltrim([shift_nbr]),(select [DESCRIPTION] from tbl where [VALUE]=6))>0/*id    shift_nbr2    23    35    26    3*/select * from [shift] where CHARINDEX(ltrim([shift_nbr]),(select [DESCRIPTION] from tbl where [VALUE]=7))>0/*id    shift_nbr1    12    23    34    15    26    3*/
------解决方案--------------------
不是相当于做‘位’的操作,就是位操作。

SQL code
--> 测试数据:#if object_id('tempdb.dbo.#') is not null drop table #create table #(id int, shift_nbr int)insert into #select 1, 1 union allselect 2, 2 union allselect 3, 3 union allselect 4, 1 union allselect 5, 2 union allselect 6, 3declare @shift_cntrl_nbr int = 7select * from # where @shift_cntrl_nbr & power(2, shift_nbr-1)>0/*id          shift_nbr----------- -----------1           12           23           34           15           26           3*/
  相关解决方案