结果来自添加不同的不同列

时间:2014-12-26 06:56:37

标签: sql-server sql-server-2008

这是给定的表数据,我希望输出像我这样给出。

slno    name        salary
-----------------------------
1       raj         5000.0000
2       laba        4000.0000
3       silu        3000.0000
4       jaya        6000.0000
5       papu        7000.0000
6       tikan       9000.0000
7       susanta     6000.0000
8       chiku       4500.0000
9       micky       5500.0000
10      susa        2500.0000
11      musa        6500.0000
12      pi          6500.0000
13      luna        7500.0000
14      tuna        9500.0000
15      tina        3500.0000

期望的输出

slno    name    salary
----------------------
1       raj     5000.0000
2       laba    4000.0000
3       silu    3000.0000
4       jaya    6000.0000
5       papu    7000.0000
6-10    ----    27500.0000(total salary from 6-10)
6-15    ----    61000.0000(total salary from 6-15)

1 个答案:

答案 0 :(得分:0)

试试这个:

create table #table_name (slno int, name varchar(20), salary float);
insert into #table_name (slno, name, salary) values
(1, 'raj', 5000.0000),
(2, 'laba', 4000.0000),
(3, 'silu', 3000.0000),
(4, 'jaya', 6000.0000),
(5, 'papu', 7000.0000),
(6, 'tikan', 9000.0000),
(7, 'susanta', 6000.0000),
(8, 'chiku', 4500.0000),
(9, 'micky', 5500.0000),
(10, 'susa', 2500.0000),
(11, 'musa', 6500.0000),
(12, 'pi', 6500.0000),
(13, 'luna', 7500.0000),
(14, 'tuna', 9500.0000),
(15, 'tina', 3500.0000);

select cast(slno as varchar(10)) [slno]
, name
, salary 
from #table_name where slno <= 5
union all
select '6-10'
, '----'
, sum(salary) 
from #table_name where slno between 6 and 10
union all
select '6-15'
, '----'
, sum(salary) 
from #table_name where slno between 6 and 15

结果

slno    name    salary
----------------------
1       raj     5000
2       laba    4000
3       silu    3000
4       jaya    6000
5       papu    7000
6-10    ----    27500
6-15    ----    61000