解释起来很复杂。我举个例子
id value
-- -------
1 61
2 50
3 A
4 61
5 750
6 61
7 20
8 A
id value code
-- ----- ----
1 61 A
4 61 OTHER
6 61 A
它应该如何:
我想选择值 61
的行如果属于两个值61具有'A',那么代码值为'A'
,否则结果为'OTHER'我怎么能用一个select语句来做到这一点。
修改
逻辑:
如果value
61存在,并且前面的任何列包含A
,则列code
应写A
,否则OTHER
。在给定的数据示例中:
id value
-- -------
1 61
2 50
3 A
id 1,其值为61,并且它的前面的值(直到下一个61)包含A,因此它应该打印:
id value code
-- ----- ----
1 61 A
然而,接下来的61及其前面的行不会:
4 61
5 750
所以应该打印:
4 61 OTHER
提前致谢
答案 0 :(得分:0)
试试这个
create table #MyTable(id int, value varchar(10))
insert into #MyTable values(1,'61')
insert into #MyTable values(2,'50')
insert into #MyTable values(3,'A')
insert into #MyTable values(4,'61')
insert into #MyTable values(5,'750')
insert into #MyTable values(6,'61')
insert into #MyTable values(7,'20')
insert into #MyTable values(8,'A')
--insert into #MyTable values(9,'61')
--Select * from #MyTable
Select ROW_Number() over(order by id) as rn, *
into #tmp1
from #MyTable where value='61'
SELECT t1.id,t1.value
,CASE WHEN MAX(t.value) ='A' THEN 'A'
ELSE 'OTHER' END AS COde
FROM #MyTable t
JOIN #tmp1 t1 on t1.id<t.id
JOIN #tmp1 t2 on (t1.rn=t2.rn-1 and t.id<t2.id)
Group by t1.id,t1.value
UNION
/*For Last Row with 61*/
SELECT t1.id,t1.value
,CASE WHEN MAX(t.value) ='A' THEN 'A'
ELSE 'OTHER' END AS COde FROM
(SELECT TOP 1 * from #tmp1 order by rn desc) t1
JOIN #MyTable t on t.id>=t1.id
Group by t1.id,t1.value
Drop table #MyTable
Drop table #tmp1