现有一表
id name1 money1 name2 money2 year
1 张 100 王 200 2006
2 王 100 李 200 2007
3 王 50 王 500 2007想查询姓名为 王 时对应的 每年的钱数总额
返回表应该为
id money year求达人帮帮忙啊(最多只能发100,不够继续加分)
id name1 money1 name2 money2 year
1 张 100 王 200 2006
2 王 100 李 200 2007
3 王 50 王 500 2007想查询姓名为 王 时对应的 每年的钱数总额
返回表应该为
id money year求达人帮帮忙啊(最多只能发100,不够继续加分)
解决方案 »
- 信心完全遭打击
- 如何知道某表是否有触发器?有几种方法?
- 解析SQL Server中行转列问题
- 请问2005中如何修改存在的存储过程。2000里面在一个窗口修改。
- ********************请问关于权限的问题*********
- 超麻烦的问题 查询汇总的问题 急
- 一个dataset的update的问题,,急啊,,解出给分
- 请各位GGJJ帮忙:两个表结构不同,但有相同的字段,请问怎么比较它们不一样的记录,只能写两个循环实现吗????
- 如何解决多个MS SQL Server7中结构相同的多个库对相同结构的一个库的数据日日更新问题
- 求教一个sql语句,关于多字段排序的
- 关于查询问题?
- sql语句
from
(
select id,money1 money,year from tb
union all
select id,money2 money,year from tb
) x
group by id,year
union all
select id,money2 as [money],[year] from 表 where name2='王'
from
(
select id,name,money1 money,year from tb
union all
select id,name,money2 money,year from tb
) x
where name='王'
group by id,year
t.id,sum(t.[money]) as [money],t.[year]
from
(select id,money1 as [money],[year] from 表 where name1='王'
union all
select id,money2 as [money],[year] from 表 where name2='王') as t
group by
t.id,t.[year]
--> 生成测试数据: #T
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (id int,name1 nvarchar(2),money1 int,name2 nvarchar(2),money2 int,year int)
insert into #T
select 1,'张',100,'王',200,2006 union all
select 2,'王',100,'李',200,2007 union all
select 3,'王',50,'王',500,2007--SQL查询如下:select id,sum(money) money,year
from
(
select id,name1 name,money1 money,year from #T
union all
select id,name2 name,money2 money,year from #T
) x
where name='王'
group by id,year /*
id money year
----------- ----------- -----------
1 200 2006
2 100 2007
3 550 2007(3 行受影响)*/
SELECT ID,MONEY=SUM(MONEY1),YEAR FROM TB WHERE NAME1='王' GROUP BY YEAR,ID
UNION ALL
SELECT ID,MONEY=SUM(MONEY2),YEAR FROM TB WHERE NAME2='王' GROUP BY YEAR,ID
) A
GROUP BY YEAR,ID
from tab
where name1='王' or name2='王'