上次没有说全消费表xf
id  product_h  sl  
1  P001     1
2  P002     2
3  P001     3价格表jg
id product_h jg
1  P001  10
2  P001  20
3  P002  30
我想要的效果是 统计金额,表xf的数量sl*价格表的同样货号的第一个记录
select a.product_h,sum(a.sl*(select top 1 jg  from jg where product_h=a.product_h)) as je  
from xf a 
group by a.product_h服务器: 消息 130,级别 15,状态 1,行 1
不能对包含聚合或子查询的表达式执行聚合函数。谢谢

解决方案 »

  1.   

    select 
    a.product_h,
    sum(a.sl* b.jg) as je   
    from xf a  
    left join (select distinct product_h,jg from jg) b
    on a.product_h = b.product_h
    group by a.product_h
      

  2.   

    select a.product_h,sum(a.sl)*(select top 1 jg from jg where product_h=a.product_h order by id) as je   
    from xf a  
    group by a.product_h
      

  3.   

    select product_h,sum(je)
    from(
    select a.product_h,a.sl*(select top 1 jg from jg where product_h=a.product_h) as je   
    from xf a  )T
    group by a.product_h
      

  4.   


    create table xf(id int,product_h varchar(4), sl int)
    insert into xf values (1, 'P001', 1)
    insert into xf values (2, 'P002', 2)
    insert into xf values (3, 'P001', 3)create table jg(id int,product_h varchar(4), sl int)
    insert into jg values (1, 'P001', 10)
    insert into jg values (2, 'P001', 20)
    insert into jg values (3, 'P002', 30)select xf.product_h,sum(xf.sl * x.sl)as je 
    from xf outer apply (select top 1 sl from jg where xf.product_h = jg.product_h)x
    group by xf.product_h