为SELECT查询的结果添加一个计数器

时间:2012-05-04 09:44:20

标签: sql-server-2008 ssms

我正在尝试将计数器添加到选择结果列表中。保持简单,我的疑问是:

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]

这让我知道了:

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"

但是,我需要这个:

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"

我试过用我在这里找到的东西: http://msdn.microsoft.com/en-us/library/ms187330%28v=sql.105%29.aspx

我试过了     DECLARE @pos nvarchar(30)     选择....(@ pos + = 1)....     from ....(SELECT @ pos = 0)....

但是我得到“'DECLARE'附近的语法不正确。期待'(',SELECT或WITH。”,加上“语法不正确=”

我尝试了这段代码:

GO
DECLARE @var1 nvarchar(30)
SELECT @var1 = 'Generic Name'
SELECT @var1 = (
SELECT AppUserName
FROM [AppUsers]
WHERE AppUserID = 1000)
SELECT @var1 AS 'Company Name' ;

我将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:3)

你的意思是什么?你想要每行增加一个数字吗?如果是,请尝试:

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