当前位置: 代码迷 >> Sql Server >> sqlServer,oracle,sql求教解决方案
  详细解决方案

sqlServer,oracle,sql求教解决方案

热度:70   发布时间:2016-04-24 09:57:02.0
sqlServer,oracle,sql求教

小弟今天遇到个问题,实在想不出来了,有张这样的Test表,列col1,col2,.... 均为int型且每条记录列上均有值,列值有正有负,如何才能查找出每条记录第一个出现负值的列在第几列,最好返回一个数字,返回列名也行,用sqlServer或oracle实现都可以参考参考,希望各位大神发挥自己的特长帮助下小弟
------解决思路----------------------



create table ttt
(
col1 int,
col2 int,
col3 int,
)

select * from ttt

insert into ttt values (1,2,-3)
insert into ttt values (-1,2,3)
insert into ttt values (1,-2,3)

--不好意思,上游标了,最笨的方法了
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#tmp') and type='U')
   drop table #tmp

DECLARE @a   int
DECLARE @b   int
DECLARE @c   int
DECLARE @msg nvarchar(20)
select col1,col2,col3,@msg as msg into #tmp from ttt where 1=2
DECLARE MyCursor CURSOR
FOR
    SELECT col1,col2,col3 FROM ttt
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @a,@b,@c
WHILE (@@FETCH_STATUS = 0)
BEGIN
    --循环对@a,@b做一些其他的处理
    if(@a<0)
     INSERT INTO #tmp values(@a,@b,@c,'1,col1小于0')
     else if(@b<0)
     INSERT INTO #tmp values(@a,@b,@c,'2,col2小于0')
     else if(@c<0)
     INSERT INTO #tmp values(@a,@b,@c,'3,col3小于0')
    FETCH NEXT FROM MyCursor INTO @a,@b,@c
END
CLOSE MyCursor
DEALLOCATE MyCursor

select * from #tmp

col1        col2        col3        msg
----------- ----------- ----------- --------------------
1           2           -3          3,col3小于0
-1          2           3           1,col1小于0
1           -2          3           2,col2小于0

(3 行受影响)


------解决思路----------------------

with a(a,b,c)as(
select 1,2,-1 union
select -1,0,-2 union
select 1,-3,0 union
select 1,2,3
),b as(
select NEW=
case when a>=0 then '0'+CONVERT(varchar,a) else CONVERT(varchar,a) end +
case when b>=0 then '0'+CONVERT(varchar,b) else CONVERT(varchar,b) end +
case when c>=0 then '0'+CONVERT(varchar,c) else CONVERT(varchar,c) end 
from a)
select (CHARINDEX('-',new)+1)/2 from b


提供个思路...
------解决思路----------------------
不过这种表,用unpivot也能实现,可以试下
------解决思路----------------------
create table test(col1 int,col2 int,col3 int,col4 int ,col5 int)
insert into test
select 1,2,3,4,-4
union all
select -1,-3,4,5,7
union all
select 3,-5,6,-9,6
union all
select 6,7,8,9,8

declare @i int 
declare @j int
declare @col1 varchar(20) 
declare @sql nvarchar(4000)
set @sql=''
set @j=1
select @i=max(colid) from   syscolumns where  id=object_id('test')
While  @j<=@i
begin
  Select @Col1=Name From Syscolumns Where ID=OBJECT_ID('Test') and ColID=@J
 set @sql=@sql+'+CAST('+@col1+' as varchar)'
 set @j=@j+1
end
set @sql=STUFF(@sql,1,1,'')
set @sql='select row_number() over( order by getdate()) as row, charindex(''-'', '+@sql+') as fristnum from test ' 
exec(@sql)
  相关解决方案