Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Auto number for SQL View

Author  Topic 

aron.ridgway
Starting Member

1 Post

Posted - 2014-04-07 : 11:11:44
Hi There, i have an SQL union view (see bellow) and i want to create a column with an Id number. The reason being the account ID has a mixture of number ID's and Text Id's as the information is coming from 5 different Sage company accounts.
Is there an easy way of doing this?
Many thanks
Aron

SELECT PLSupplierAccountID AS AccountID, SupplierAccountNumber AS AccountNumber, SupplierAccountName AS AccountName, 'RWL' AS Company
FROM Roth.dbo.PLSupplierAccount
UNION ALL
SELECT PLSupplierAccountID AS AccountID, SupplierAccountNumber AS AccountNumber, SupplierAccountName AS AccountName, 'FAH' AS Company
FROM FAH.dbo.PLSupplierAccount
UNION ALL
SELECT PLSupplierAccountID AS AccountID, SupplierAccountNumber AS AccountNumber, SupplierAccountName AS AccountName, 'RFG' AS Company
FROM RFG.dbo.PLSupplierAccount
UNION ALL
SELECT PLSupplierAccountID AS AccountID, SupplierAccountNumber AS AccountNumber, SupplierAccountName AS AccountName, 'RFP' AS Company
FROM RFP.dbo.PLSupplierAccount
UNION ALL
SELECT PLSupplierAccountID AS AccountID, SupplierAccountNumber AS AccountNumber, SupplierAccountName AS AccountName, 'RFW' AS Company
FROM ALOPS.dbo.PLSupplierAccount

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-04-07 : 13:16:36
You can use the ROW_NUMBER() function.

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

ScottPletcher
Aged Yak Warrior

550 Posts

Posted - 2014-04-07 : 13:18:17
Do you want the numbers to have no gaps? If so, that would be some overhead. You'd have to write to a temp table. Or, make the query below a derived table and sort all that data, which would be vastly slower than just using a temp table.
Go to Top of Page

sqlsaga
Yak Posting Veteran

93 Posts

Posted - 2014-04-07 : 17:14:13
You can use Ranking functions for this requirement. See this article I wrote on Ranking functions.. http://sqlsaga.com/sql-server/what-is-the-difference-between-rank-dense_rank-row_number-and-ntile-in-sql-server/

Visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles.
Go to Top of Page
   

- Advertisement -