表A
ID Name
1 小名
2 小军表B
ID key ParentID Num Price
1 A 1 1 2
2 A 2 3 3
3 B 1 1 2
4 A 2 1 6
5 C 1 1 6
6 A 1 1 8表A的ID和表ParentID关联
现在输入条件列:Name=小名,求相同key,num和price的总和,记录数量
key Num Price 记录数量
A 6 19 4
B 1 1 2
C 1 1 6
ID Name
1 小名
2 小军表B
ID key ParentID Num Price
1 A 1 1 2
2 A 2 3 3
3 B 1 1 2
4 A 2 1 6
5 C 1 1 6
6 A 1 1 8表A的ID和表ParentID关联
现在输入条件列:Name=小名,求相同key,num和price的总和,记录数量
key Num Price 记录数量
A 6 19 4
B 1 1 2
C 1 1 6
解决方案 »
- cursor和sysname数据类型
- 求助~~~只有一张表,但是不知道怎么查
- SSIS中怎么根据动态的表名,传输不同的表的内容
- 关于触发器的简单问题(急)
- 大家帮我看看这是如何加密的
- 如何将每一天的都变成一条记录??
- 请各位老鸟提供通用存储过程,比如插入,查询,更新等,还有使用通用存储过程效率降低多少
- 2000S下设了几个用户怎么能让他们都能用C盘下的office2000啊?不会分别装吧
- 急急,一个数据备份问题。请教。急急急急急!!
- VFP的计算字段怎么自动完成?用量=本次-上次,让用量根据 本次,上次的数据自动填充
- 关于批量插入数据的问题
- 在开发网站项目的过程中,建立多个数据库与使用单个数据库的性能上差别大吗?
insert into test1(ID,Name)
select 1,'小名' union all
select 2,'小军'
go
create table test2(ID int ,[key] varchar(20),ParentID int,Num int,Price int)
insert into test2(ID,[key],ParentID,Num,Price)
select 1,'A',1,1,2 union all
select 2,'A',2,3,3 union all
select 3,'B',1,1,2 union all
select 4,'A',2,1,6 union all
select 5,'C',1,1,6 union all
select 6,'A',1,1,8
goselect [key],sum(num) as Num,sum(price) as Price,count([key]) as 记录数量
from test2
where ParentID = (select ID from test1 where Name ='小名')
group by [key]drop table test1
drop table test2
-------
select B.key,sum(num) as num ,sum(Price) as Price,count(*) as 记录数量
from A,B
where A.id=B.ParentID and A.name='小名'
group by B.key但你那数据是否有问题啊!!??
A 6 19 4
B 1 2 1
C 1 6 1
不好意思写错了!
to ping3000(Study All Day And All Night)
按照你的程序我试了下如果表A里面返回单条记录是正确的,如果返回多个记录就会出问题,我把=换成in的话,程序把每条记录都列出来了,不知道是什么原因?
to ping3000(Study All Day And All Night)
select [key],ID,sum(num) as Num,sum(price) as Price,count([key]) as 记录数量
from test2
where ParentID = (select ID from test1 where Name ='小名')
group by [key],ID
如果这样的话,结果就不一样了,
WITH TABCTE([key],Num,Price)
AS
(
SELECT [key],Num,Price
FROM test1 A INNER JOIN test2 B
ON A.ID=B.ParentID AND A.ID=(SELECT ID FROM test1 WHERE NAME='小名')
)
SELECT [key],Num=SUM(NUM),Price=SUM(Price),记录数量=COUNT(*) FROM TABCTE
GROUP BY [key]
--结果
/*
key Num Price 记录数量
-------------------- ----------- ----------- -----------
A 2 10 2
B 1 2 1
C 1 6 1(3 行受影响)
*/
from test1 A, test2 B
where A.id=B.ParentID and A.name='小名'
group by B.[key]
join #b as b on a.id=b.parentid and a.name='小明'
group by b.cdkey
数据好象有问题!