SQL 2000查询麻烦

时间:2010-11-15 17:02:47

标签: sql sql-server tsql sql-server-2000 pivot

考虑下表

create table sample(id, name, numeric, qno, ans1,ans2,ans3)

sample data

1, 'vivek', 1, 'a', 'b', ''
2, 'vivek', 1, 'c', 'd', ''
3, 'vivek', 2, 'e', 'f', 'g'
4, 'vivek', 3, 'h', 'i', 'j'
5, 'vijay', 1, 'k', '', 'l'
6, 'vijay', 2, 'm', '', 'n'
7, 'vijay', 2, 'o', '', 'p'
8, 'vikram', 3, 'q', 'r', 's'


output expected

column Names: name, info1, info2, info3

    values
'vivek','ab','ef','hij'
'vivek','cd','',''
'vijay','kl', 'mn',''
'vijay','','op',''
'vikram','','','qrs'

将行转换为列。

换句话说,

一个答案将有一行。一个问题可以有多个答案。

输出的答案号应为列。

在sql 2000中有没有快速简便的技术?

2 个答案:

答案 0 :(得分:2)

首先,如果我理解你的问题,那么我认为你的第一个结果应该是 'vivek','ab','efg','hij'而非'vivek','ab','ef','hij'

如果是这样,那么我认为以下可能做你想做的事。

IF OBJECT_ID('TempDB..#TempSample') IS NOT NULL
    DROP TABLE #TempSample

DECLARE @PrevName  nvarchar(80),
@PrevRow_number     INT,
@PrevQno int 


select
    isNull(id, 0)   as id , 
    isNull(sname, '')   as sName , 
    IsNull(qno,0)       as qno ,
    ans1, 
    ans2, 
    ans3  , 
    CAST(0 AS INT) AS row_number ,
    Cast('' as Nvarchar(80)) as newAns1, 
    Cast('' as Nvarchar(80)) as newAns2, 
    Cast('' as Nvarchar(80)) as newAns3
    INTO #TempSample
    from 
    (select id, sname, qno, ans1, ans2, ans3 from sample ) t3


ALTER TABLE #TempSample ADD PRIMARY KEY CLUSTERED (sName, qno , id)

UPDATE #TempSample 
    SET @PrevRow_number = row_number = CASE WHEN   sName = @PrevName and qno = @PrevQno THEN @PrevRow_number +1 ELSE 1 END,
        @PrevName  = sname ,
        @PrevQno   = qno,
        newAns1                        = case when sName = @PrevName and qno=1 Then newAns1 + ans1+ans2+ans3 else newAns1 end ,
        newAns2                        = case when sName = @PrevName and qno=2 Then newAns2 + ans1+ans2+ans3 else newAns2 end ,
        newAns3                        = case when sName = @PrevName and qno=3 Then newAns3 + ans1+ans2+ans3 else newAns3 end 
FROM #TempSample  WITH(TABLOCKX)
OPTION (MAXDOP 1)


Select sName,  Max(newAns1) as Ans1 , Max(newAns2) as Ans2, Max(newAns3) as Ans3 
From #TempSample 
Group by sName, Row_Number
Order By sName  

最近有一个与Sql 2000类似的问题,所以信用必须转到SqlServerCentral上的this article

答案 1 :(得分:0)

不,在sql 2000中创建枢轴没有简单的方法。