这个sql语句怎么写!急。 (200分)

  • 主题发起人 freesoft
  • 开始时间
F

freesoft

Unregistered / Unconfirmed
GUEST, unregistred user!
A表 B表
id ge id ge cz
1001 1 1001 1 1
1002 2 1001 2 1
1003 3
1004 5 1001 5 0
1002 2 1
1002 3 0
1002 8 0
1003 4 1
处理结果为:
id ge
1001 4
1001 5
1002 4
1002 3
1002 8
1003 7
1004 5
也就是说如果cz值为1则累加ge,就是B表中CZ为1的和A中的记录累加。
如果cz为0,则在处理结果中添加。
不好意思,处理结果还要加上,A表中有的,但在B表中没有出现的!
这个sql语句怎么写!急。
 
select a.id,a.ge+t2.Bge AS sumge from a,(select id,sum(ge) AS Bge from b where cz=1 group by id) AS t2
where a.id=t2.id
union all
select id,ge from b where cz=0
order by id
 
这个类似的SQL语句以前写过,要用到Case之类的关键字,而且在SqlServer和Oracle中还不一样。
建议你根据具体的数据库查一下它的语法。
 
不好意思,处理结果还要加上,A表中有的,但在B表中没有出现的!
你这样写有点问题。
如:
在A、B中有
1008 3 1008 5 0
那么只出现一条,是B的!
 
select a.id,a.ge+isnull(t2.Bge,0) AS sumge from a left outer join (select id,sum(ge) AS Bge from b where cz=1 group by id) AS t2
ON a.id=t2.id
union all
select id,ge from b where cz=0
order by id

这是SQL SERVER的写法
 
SELECT a.id, a.ge + b.ge
FROM (SELECT id, SUM(ge) AS ge
FROM a
GROUP BY id) a,
(SELECT id, SUM(ge) AS ge
FROM (SELECT a.id as id, isnull(ge, 0) as ge, cz AS cz
FROM b,
(SELECT DISTINCT (id) AS id
FROM a) a
WHERE a.id *= b.id AND b.cz = 1) b group by id) b
WHERE a.id = b.id

union all
select id ,ge from b
where cz =0
order by a.id
 
我已经写出来了,不过还是要感谢各位!
以下是我的答案。
select a.id,a.ge+h.ge from a,(select id,sum(ge) from b where cz=1) as h
where a.id=b.id
union
(select b.id,b.ge from a,b where b.cz='0')
union
(select a.id,a.ge from a wher a.id
not in (select id from b where b.cz='1')
) order by jpid
不知道大家看懂了没有,我已经调试成功,不过我还是希望用存储过程来做,可是
还没有写出来呢?哈哈,是不是有人有兴趣,大家一起努力吧
 
我第二次写的不对吗?
 
草央包包 解法是对的!应当得分,freesoft要是有自己的方法,就不要用union语句
 
呵,我的解法也是对的呀,
 
TO::草央包包,天真。
感谢!你们的大力帮助,同时也感谢IMKING的提醒。不过包包的想法是怪了点,我还以为是
错的呢!后来试过了,是对的,不过我希望用存储过程来写这个报表要用的SQL语句,
以前不大用存储过程,不知道你们是否可以帮一下忙,或者提醒一下,谢谢,分数近日分分
 
直接放在存储过程中运行就好了呀
 
顶部