我需要将一个表的总和与另一个表的总和进行比较,并且仅当一个表大于另一个表时才显示

时间:2016-06-07 19:03:42

标签: sql having

这是我的代码

select sum(IV.total) as total, 
       IV.sono, 
       sum(SO.total) as total2 
  from tblInvoiceDetail as IV 
       left join tblSO as SO on IV.sono=SO.sono 
 where IV.sono not in (108428,108368) 
 group by IV.sono  
having sum(SO.total) < sum(IV.total) 
 order by IV.sono DESC

1 个答案:

答案 0 :(得分:1)

您可以使用子查询来执行此操作:

select IV.sono, ivtotal, sototal
  from (select sono, sum(total) ivtotal from tblInvoiceDetail group by sono) as IV
       LEFT JOIN
       (select sono, sum(total) sototal from tblSO group by sono) as SO 
       ON IV.sono = SO.sono
 where SO.sototal < IV.ivtotal
   and IV.sono not in (108428,108368) 
 order by IV.sono DESC