Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.57/5 (3 votes)
I have have a table
 name  mark
u      23   
h      38   
j      20   
p      83 

and for output we need
name  mark
u      23   38
h      38   20
j      20   83
p      83    0


how do I write a quries in SQL to do this?
Posted
Updated 24-Aug-11 9:49am
v2
Comments
AspDotNetDev 24-Aug-11 16:52pm    
Do you have an identity field or some field you can use to sort by (e.g., date created)? If not, then you may have to use a cursor.
walterhevedeich 24-Aug-11 16:54pm    
Your question is not clear. How can we get the values on the third column? You somehow failed to explain this on your question.
Shahan Ayyub 25-Aug-11 6:46am    
In your question you have this at the end of each row:
38
20
83
0
Is this the "new column" ? or you have concatenated it to the second column with <space> ? Kindly mention it in you question.

I create a function in sql
CREATE FUNCTION UpdateNameMark(@name varchar(50)) 
returns int
as

   BEGIN 
   declare @No int
   if (@name='u')
   select @No= 38
   else if (@name='h')
   select @No =20
   else if (@name='j')
   select @No= 83
   else if (@name='p')
   select @No= 0
   
   return @No
      
 END


if want this
select name , mark , NameMark(name) from <your table="" name=""> </your>

if you want this
updaye <tablename> set mark= NameMark(name)</tablename>
 
Share this answer
 
Comments
fjdiewornncalwe 24-Aug-11 19:52pm    
I'm pretty sure hardcoding results is not the answer.
I have created a table with column [ID] int, [name] varchar, [marks] int where table name [tbl_Rep]is choosen, and add the records you have provided. Using the script below i am getting the same result you have asked for.

So, Check this script:

SQL
select * into #temp from tbl_Rep

alter table #temp add [marks2] int NULL

    DECLARE @count INT;
    Set @count = 0;
    DECLARE @max INT;
    Set @max = (Select Count(*) from tbl_Rep);
    print @count;
    WHILE (@count < @max)
    BEGIN
       update #temp Set [Marks2]=(select [Marks] from #temp where ID=@count+1) where ID=@count
       SET @count = (@count + 1)
    END
update #temp Set [Marks2]=0 where ID= (select MAX(ID) from #temp)
select * from #temp

drop table #temp
 
Share this answer
 
As an alternative, a more optimized way is to join ID+1 of table 'A' to ID of table 'B' instead of looping:

SQL
WITH
Test (ID, Name, Marks) AS
(
SELECT
ID,[name],[Marks]
FROM tbl_Rep
)

SELECT
A.[ID],A.[Name],A.[Marks],ISNULL(B.[Marks],0) as [Marks2]
FROM Test A
Left Join [tbl_Rep] B On A.[ID]+1=B.[ID]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900