SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 need help writing a query
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

tocroi72
Yak Posting Veteran

89 Posts

Posted - 09/28/2005 :  17:36:05  Show Profile  Reply with Quote
Hi,
I have a table with the below data:

Billnumber
11111
11111
11111
33333
33333
44444
44444
44444
44444
I want to create an additional field lineItem like below
BillNumber LineItem
11111 1
11111 2
11111 3
33333 1
33333 2
44444 1
44444 2
44444 3
44444 4

Could somebody help me to write this query? Thanks

madhivanan
Premature Yak Congratulator

India
22460 Posts

Posted - 09/29/2005 :  00:27:03  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
It is not possible until you have other unique column
If you have then

Select BillNumber,(select count(*) from yourTable where BillNumber=T.BillNumber and UniqueCol<=T.UniqueCol) as LineItem from yourTable T

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

sreeram84n
Starting Member

India
4 Posts

Posted - 06/08/2012 :  12:12:49  Show Profile  Reply with Quote
select BillNumber,
(select COUNT(*) from yourTable where yourTable .BillNumber<=t.BillNumber) as rowid from yourTable t
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47051 Posts

Posted - 06/08/2012 :  12:18:39  Show Profile  Reply with Quote
if you're on sql 2005 or above you can use like

SELECT Billnumber,Seq AS LineItem
FROM
(
SELECT Billnumber,ROW_NUMBER() OVER (PARTITION BY Billnumber ORDER BY (SELECT NULL)) AS Seq
FROM table
)t


if sql 2000 this is one way
CREATE TABLE #temp
(
ID int IDENTITY(1,1),
Billnumber int
)
INSERT #Temp (Billnumber)
SELECT Billnumber
FROM table
ORDER BY Billnumber

SELECT Billnumber,
COALESCE((SELECT COUNT(*) FROM #Temp WHERE Billnumber = t.Billnumber AND ID < t.ID),0)+1 AS LineItem
FROM #temp t

DROP Table #temp


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

bitsmed
Yak Posting Veteran

Denmark
98 Posts

Posted - 06/10/2012 :  17:28:13  Show Profile  Reply with Quote
quote:
Originally posted by sreeram84n

select BillNumber,
(select COUNT(*) from yourTable where yourTable .BillNumber<=t.BillNumber) as rowid from yourTable t


Maybe not the fastest code to perform, but very clever thumbs up from me
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000