0

2列のテーブルがあります:

select product, quantity from datainformation

このテーブルは次を返します。

product quantity
1        10
2        30
4        23
191      10
900       1
1234      5
12345     2
  1. 2 つの列は int です。
  2. テーブルは N 個のレコードを持つことができます

50 レコードごとに 2 つの文字列を取得する必要があります。私の質問は、これらの文字列を取得する方法です:

stringproducts='1    2    4    191  900  1234 12345'
stringquantity='10   30   23   10   1    5    2    '

現在、50 レコードごとにこれらの文字列が必要です。たとえば、51 レコードがある場合、最後の製品と最後の数量を保持するために 2 番目の「ブロック」が必要です。

別の言語では、ltrim(cad,5). SQLでこれを行うにはどうすればよいですか?

これに物を使用できますか?または、ループが必要で、それらを 1 対 1 で連結する必要がありますか? 私はそれがより簡単になる可能性があると信じています(ループ内のものかもしれませんが、すべてのレコードのループの方が簡単でしょう)

4

2 に答える 2

1

あなたは使用することができFOR XML PATHますSTUFF()

select 
  stuff((
        select ' ' + cast(product as char(10))
        from datainformation
        for XML path('')),1,1,'') as products,
 stuff((
        select ' ' + cast(quantity as char(10))
        from datainformation
        for XML path('')),1,1,'') as quantity

デモで SQL Fiddle を参照してください

于 2012-10-03T21:37:01.523 に答える
0

CHAR(5) としてキャストすると、適切にフォーマットされた連結文字列の 5 文字のブロックを構成する末尾のスペースが含まれます。

declare @t table (product int, quantity int);
insert @t select
1        ,10 union all select
2        ,30 union all select
4        ,23 union all select
191      ,10 union all select
900      , 1 union all select
1234     , 5 union all select
12345    , 2;

declare @products varchar(max);
declare @quantity varchar(max);

select @products = coalesce(@products,'')
                 + cast(product as char(5)),
       @quantity = coalesce(@quantity,'')
                 + cast(quantity as char(5))
from @t
order by product

select @products, @quantity
于 2012-10-03T21:21:57.653 に答える