0

我有一个表格输出,例如....

srno billno particular Qty rate vat amount paid balance
 1     25     aaa       5   20   5    105   400   135
 2     25     qqq       5   50   5    225   400   135
 3     25     fff       10  20   5    205   400   135
 4     26     aaa       10  20   5    205   300   245
 5     26     fff       10  20   5    205   300   245    

但我想要像这样的输出:

srno billno particular Qty rate vat amount paid balance
 1     25     aaa       5   20   5    105   400   135
              qqq       5   50   5    225         
              fff       10  20   5    205         
 2     26     aaa       10  20   5    205   300   245
              fff       10  20   5    205         

如何使用 T-SQL 选择命令获取此输出......

4

1 回答 1

1

您应该能够通过使用排名函数row_number()和来做到这一点dense_rank

select 
  case when rn = 1 then cast(rnk as varchar(10)) else '' end srno,
  case when rn = 1 then cast(billno as varchar(10)) else '' end billno,
  [particular], 
  [Qty], 
  [rate], 
  [vat], 
  [amount], 
  case when rn = 1 then cast([paid] as varchar(10)) else '' end [paid], 
  case when rn = 1 then cast([balance] as varchar(10)) else '' end [balance]
from
(
  select [srno], [billno], [particular], [Qty], [rate], [vat], [amount], [paid], [balance],
    row_number() over(partition by billno order by srno) rn,
    dense_rank() over(order by billno) rnk
  from yourtable
) src;

请参阅带有演示的 SQL Fiddle

结果是:

| SRNO | BILLNO | PARTICULAR | QTY | RATE | VAT | AMOUNT | PAID | BALANCE |
---------------------------------------------------------------------------
|    1 |     25 |        aaa |   5 |   20 |   5 |    105 |  400 |     135 |
|      |        |        qqq |   5 |   50 |   5 |    225 |      |         |
|      |        |        fff |  10 |   20 |   5 |    205 |      |         |
|    2 |     26 |        aaa |  10 |   20 |   5 |    205 |  300 |     245 |
|      |        |        fff |  10 |   20 |   5 |    205 |      |         |
于 2013-02-06T10:55:16.993 回答