简体   繁体   English

sql读取n行数并以固定列数显示

[英]sql to read n number of rows and display in fixed number of columns

We are currently using SQL2005. 我们当前正在使用SQL2005。 I have a SQL table that stores serial numbers in a single column. 我有一个SQL表,将序列号存储在单列中。 Thus 10 000 serial numbers mean 10 000 rows. 因此,10000个序列号表示10000行。 When these are printed on an invoice, one serial number per row is being printed due to how the information is stored. 当这些打印在发票上时,由于信息的存储方式,每行将打印一个序列号。 We currently use the built-in invoice in our ERP system but will change to SSRS if I can get the printing of serials sorted. 我们目前在我们的ERP系统中使用内置发票,但如果可以打印序列号,则将更改为SSRS。

How can I read the serial numbers and display it (either in a view or sp) maybe 10 at a time per row . 如何读取序列号并在每行一次显示10个序列号(在视图或sp中)。 Thus if I am reading 18 serials it will be two rows (1st row with 10 serials and 2nd row with 8 serials). 因此,如果我正在读取18个序列号,它将是两行(第一行包含10个序列,第二行包含8个序列)。 If I am reading 53 serials, it will be 6 rows. 如果我正在阅读53个序列号,它将是6行。 Getting this right will cut down on the paper needed for invoice printing to roughly a tenth of what is currently required! 正确执行此操作可以将发票打印所需的纸张减少到当前所需纸张的十分之一左右!

Just to be clear...the serials are currently are stored and print like this : 只是要清楚...序列当前存储和打印如下:

Ser1  
Ser2  
Ser3  
Ser4  
Ser5  

I would prefer them to print like this : 我希望他们像这样打印:

Ser1 Ser2 Ser3 Ser4 Ser5 Ser6 Ser7 Ser8 Ser9 Ser10  
Ser11 Ser12 Ser13 Ser14 Ser15 Ser16....etc

Thanks 谢谢

You can use row_number() to assign a unique number to each row. 您可以使用row_number()为每行分配一个唯一的编号。 That allows you to group by rn / 10 , giving you groups of 10 rows. 这使您可以group by rn / 10进行group by rn / 10 ,从而为您提供10行的分组。

Here's an example for 3 instead of 10 rows: 这是3行而不是10行的示例:

select  max(case when rn % 3 = 0 then serialno end) as sn1
,       max(case when rn % 3 = 1 then serialno end) as sn2
,       max(case when rn % 3 = 2 then serialno end) as sn3
from    (
        select  row_number() over (order by serialno) -1 as rn
        ,       serialno
        from    @t
        ) as SubQueryAlias
group by
        rn / 3

See it working at SQL Fiddle. 看到它在SQL Fiddle上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM