问题: 表 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 怎么写啊,谢谢啦!
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 怎么写啊,谢谢啦!
--> 测试数据:[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 all
select 2,'相当于Shift 2 Enabled' union all
select 3,'相当于Shift 1&2 Enabled' union all
select 4,'相当于Shift 3 Enabled]' union all
select 5,'相当于Shift 1&3 Enabled]' union all
select 6,'相当于Shift 2&3 Enabled]' union all
select 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 all
select 2,2 union all
select 3,3 union all
select 4,1 union all
select 5,2 union all
select 6,3select * from [shift]
where CHARINDEX(ltrim([shift_nbr]),(select [DESCRIPTION] from tbl where [VALUE]=4))>0
/*
id shift_nbr
3 3
6 3
*/
select * from [shift]
where CHARINDEX(ltrim([shift_nbr]),(select [DESCRIPTION] from tbl where [VALUE]=6))>0
/*
id shift_nbr
2 2
3 3
5 2
6 3
*/
select * from [shift]
where CHARINDEX(ltrim([shift_nbr]),(select [DESCRIPTION] from tbl where [VALUE]=7))>0
/*
id shift_nbr
1 1
2 2
3 3
4 1
5 2
6 3
*/
declare @str varchar(20)
set @str=''
select @str=@str+','+LTRIM([shift_nbr]) from(
select distinct [shift_nbr] from(
select * from [shift]
where CHARINDEX(ltrim([shift_nbr]),(select [DESCRIPTION] from tbl where [VALUE]=7))>0)a)b
select right(@str,len(@str)-1) as [shift_nbr]
/*
shift_nbr
1,2,3
*/
这个主要是做逻辑 与 操作,比如:
5 相当于Shift 1 & 3 Enabled, 相当于2进制101,对应1位和3位,故得出shift 1,3
6 相当于Shift 2 & 3 Enabled 相当于2进制110,对应2位和3位,故得出shift 2,3
7 相当于Shift 1, 2, & 3 Enabled 相当于2进制111,对应1,2位和3位,故得出shift 1,2,3
求解?
if object_id('tempdb.dbo.#') is not null drop table #
create table #(id int, shift_nbr int)
insert into #
select 1, 1 union all
select 2, 2 union all
select 3, 3 union all
select 4, 1 union all
select 5, 2 union all
select 6, 3declare @shift_cntrl_nbr int = 7
select * from # where @shift_cntrl_nbr & power(2, shift_nbr-1)>0/*
id shift_nbr
----------- -----------
1 1
2 2
3 3
4 1
5 2
6 3
*/
关联自己查询写。