add a counter to a SELECT query's results

sql-server-2008, ssms

Solution

what do you mean by counter? Do you want a incremental number per row? If yes, try this:

select row_number() over (order by your_column), * 
from your_table

Problem

I'm trying to add a counter to a list of Select results. Keeping it simple, my query is this: ``` Select distinct '"'+cast((product_sku) as varchar(30))+'"' as product_sku,preco,'"tamanhoecor::' + Left(Main.preco,Len(Main.preco)-1) + '"' As "custom_price" From( Select distinct ST2.product_sku, (Select cordesc + ' - ' + tamanho +':' + cast(price_dif as varchar) + ';' From [mg_produtos_preco] ST1 Where ST1.product_sku = ST2.product_sku ORDER BY ST1.product_sku For XML PATH ('')) [Preco], product_price, cordesc,tamanho From [mg_produtos_preco] ST2) [Main] ``` Which gets me this: ``` product_sku preco custom_price "340803 010" Preto - S:0;Preto - M:0;Preto - L:0;Preto - XL:0; "tamanhoecor::Preto - S:0;Preto - M:0;Preto - L:0;Preto - XL:0" "340803 100" Branco - S:0;Branco - M:0;Branco - L:0; "tamanhoecor::Branco - S:0;Branco - M:0;Branco - L:0" ``` However, I need this: ``` product_sku preco custom_price "340803 010" Preto - S:0:0;Preto - M:0:1;Preto - L:0:2;Preto - XL:0:3; "tamanhoecor::Preto - S:0:0;Preto - M:0:1;Preto - L:0:2;Preto - XL:0:3" "340803 100" Branco - S:0:0;Branco - M:0:1;Branco - L:0:2; "tamanhoecor::Branco - S:0:0;Branco - M:0:1;Branco - L:0:2" ``` I've tried to use what I've found here: http://msdn.microsoft.com/en-us/library/ms187330%28v=sql.105%29.aspx I've tried a DECLARE @pos nvarchar(30) Select .... (@pos + = 1) .... from .... (SELECT @pos=0) .... but I get a "Incorrect syntax near 'DECLARE'. Expecting '(', SELECT, or WITH.", plus a "Incorrect syntax near =" I tried this code, which worked: ``` GO DECLARE @var1 nvarchar(30) SELECT @var1 = 'Generic Name' SELECT @var1 = ( SELECT AppUserName FROM [AppUsers] WHERE AppUserID = 1000) SELECT @var1 AS 'Company Name' ; ``` I would appreciate any help. Thanks.

Original source

Related problems