表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

解决方案 »

  1.   

    create table test1(ID int,Name nvarchar(20))
    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
      

  2.   

    现在输入条件列:Name=小名,求相同key,num和price的总和,记录数量
    -------
    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但你那数据是否有问题啊!!??
      

  3.   

    key    Num    Price 记录数量
        A      6       19     4
        B      1       2      1
        C      1       6      1
    不好意思写错了!
    to ping3000(Study All Day And All Night) 
    按照你的程序我试了下如果表A里面返回单条记录是正确的,如果返回多个记录就会出问题,我把=换成in的话,程序把每条记录都列出来了,不知道是什么原因?
      

  4.   

    现在结果是正确了,但是还有个问题,如果我想取key所对应的ID应该怎么改下语句
    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
    如果这样的话,结果就不一样了,
      

  5.   

    -借用楼上测试数据
    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 行受影响)
    */
      

  6.   

    -借用楼上测试数据select B.[key],sum(num) as num ,sum(Price) as Price,count(*) as 记录数量
    from test1 A, test2 B
    where A.id=B.ParentID and A.name='小名'
    group by B.[key]
      

  7.   

    select b.cdkey,sum(b.num),sum(b.price)  from #a as a 
    join #b as b on a.id=b.parentid and a.name='小明'
    group by b.cdkey 
    数据好象有问题!