3

我正在尝试将计数器添加到 Select 结果列表中。保持简单,我的查询是这样的:

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) Select .... (@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' ;

我将不胜感激任何帮助。

谢谢。

4

1 回答 1

3

你说的计数器是什么意思?你想每行增加一个数字吗?如果是,试试这个:

select row_number() over (order by your_column), * 
from your_table
于 2012-05-04T09:49:01.183 回答