首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

[]sql语句求和统计

2012-01-20 
[求助]sql语句求和统计在数据库中字段如下,调试环境asp+access:idt_name时间数值1数值2合计1a2007-65492a2

[求助]sql语句求和统计
在数据库中字段如下,调试环境asp+access:
id       t_name         时间               数值1                 数值2         合计
1           a                     2007-6         5                           4               9
2           a                     2007-5         3                           7               10
3           b                     2007-6         6                           6               12
4           b                     2007-5         7                           7               14

怎样通过一句sql,将数据显示为
姓名     5月         6月         合计
a           10             9             19
b             14           12           26

sql是:
SELECT   *   FROM   B1   LEFT   JOIN   (
select   t_name,sum(iif(时间= '2007-5 ',合计,0))   as   5月,
sum(iif(时间= '2007-6 ',合计,0))   as   6月,sum(合计)   as   hj
from   tt   group   by   T_name)   A
ON   A.T_NAME=B1.T_NAME

现在的问题是数据显示为
姓名     5月         6月         合计
a           10             9             19
b             14           12           26
a           10             9             19
b             14           12           26
多循环了一次,sql   语句怎样修改。谢谢。

[解决办法]
直接要

select t_name,sum(iif(时间= '2007-5 ',合计,0)) as 5月,
sum(iif(时间= '2007-6 ',合计,0)) as 6月,sum(合计) as hj
from tt group by T_name


[解决办法]
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(id int,t_name varchar(10), 时间 varchar(10),数值1 int,数值2 int,合计 int)
insert into tb values(1, 'a ', '2007-6 ', 5, 4, 9)
insert into tb values(2, 'a ', '2007-5 ', 3, 7, 10)
insert into tb values(3, 'b ', '2007-6 ', 6, 6, 12)
insert into tb values(4, 'b ', '2007-5 ', 7, 7, 14)


go

select t_name 姓名,
sum(case 时间 when '2007-5 ' then 合计 end) '5月 ',
sum(case 时间 when '2007-6 ' then 合计 end) '6月 ',
sum(合计) 合计
from tb
group by t_name

drop table tb

/*
姓名 5月 6月 合计
---------- ----------- ----------- -----------
a 10 9 19
b 14 12 26

(所影响的行数为 2 行)
*/

热点排行